Python Unit1
Python Unit1
A class is a collection of objects. A class contains the blueprints or the prototype from which
the objects are being created. It is a logical entity that contains some attributes and
methods.
class ClassName:
# Statement-1
.
.
.
# Statement-N
Python Objects
In object oriented programming Python, The object is an entity that has a state and
behavior associated with it. It may be any real-world object like a mouse, keyboard, chair,
table, pen, etc. Integers, strings, floating-point numbers, even arrays, and dictionaries, are
all objects. More specifically, any single integer or any single string is an object. The number
12 is an object, the string “Hello, world” is an object, a list is an object that can hold other
objects, and so on. You’ve been using objects all along and may not even realize it.
Creating an Object
This will create an object named obj of the class ClassName defined above.
Obj= ClassName()
Python Inheritance
Inheritance is the capability of one class to derive or inherit the properties from another
class. The class that derives properties is called the derived class or child class and the class
from which the properties are being derived is called the base class or parent class.
The benefits of inheritance are:
It represents real-world relationships well.
It provides the reusability of a code. We don’t have to write the same code again and
again. Also, it allows us to add more features to a class without modifying it.
It is transitive in nature, which means that if class B inherits from another class A, then
all the subclasses of B would automatically inherit from class A.
Types of Inheritance
Python Polymorphism
Polymorphism simply means having many forms. For example, we need to determine if the
given species of birds fly or not, using polymorphism we can do this using a single function.
Polymorphism in Python.
Python Encapsulation
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP).
It describes the idea of wrapping data and the methods that work on data within one unit.
This puts restrictions on accessing variables and methods directly and can prevent the
accidental modification of data. To prevent accidental change, an object’s variable can only
be changed by an object’s method. Those types of variables are known as private variables.
A class is an example of encapsulation as it encapsulates all the data that is member
functions, variables, etc.
Data Abstraction
It hides unnecessary code details from the user. Also, when we do not want to give out
sensitive parts of our code implementation and this is where data abstraction came.
5. Code Maintenance
This feature is more of a necessity for any programming languages; it helps users
from doing re-work in many ways. It is always easy and time-saving to maintain
and modify the existing codes by incorporating new changes into them.
6. Design Benefits
If you are practicing on OOPs, the design benefit a user will get is in terms of
designing and fixing things easily and eliminating the risks (if any). Here the
Object-Oriented Programs forces the designers to have a long and extensive
design phase, which results in better designs and fewer flaws. After a time when
the program has reached some critical limits, it is easier
7. Better productivity
With the above-mentioned facts of using the application definitely enhances its
users overall productivity. This leads to more work done, finishing a better
program, having more inbuilt features, and easier reading, writing and
maintaining. An OOP programmer cans stitch new software objects to make
completely new programs. A good number of libraries with useful functions in
abundance make it possible.
8. Polymorphism Flexibility
Let’s see a scenario to better explain this behavior.
You behave in a different way if the place or surrounding gets change. A person
will behave like a customer if he is in a market, the same person will behave like
a student if he is in a school and as a son/daughter if put in a house. Here we can
see that the same person showing different behavior every time the surroundings
are changed. This means polymorphism is flexible and helps developers in a
number of ways.
It’s simplicity
Extensibility
9. Problems solving
Decomposing a complex problem into smaller chunks or discrete components is
a good practice. OOP is specialized in this behavior, as it breaks down your
software code into bite-sized – one object at a time. The broken components can
be reused in solutions to different other problems (both less and more complex),
or either they can be replaced by the future modules that relate to the same
interface with implementations details.
A general relatable real-time scenario – at a high level, a car can be decomposed
into wheels, engine, and chassis soon. Each of those components can be further
broken down into even smaller atomic components like screws and bolts. The
engine’s design doesn’t need to know anything about the tires’ size to deliver a
certain amount of power (as output) has little to do with each other.
APPLICATION OF OOP:
The most popular application of oops up to now, has been in the area of user
interface design such as windows. There are hundreds of windowing systems
developed using oop techniques.
Real business systems are often much more complex and contain many more
objects with complicated attributes and methods. Oop is useful in this type of
applications because it can simplify a complex problem. The promising areas
for application of oop includes.
1. Real – Time systems.
2. Simulation and modelling
3. Object oriented databases.
4. Hypertext, hypermedia and expert text.
5. Al and expert systems.
6. Neural networks and parallel programming.
7. Decision support and office automation systems.
8. CIM / CAM / CAD system.
POP VS OOP:
OOP:
In the object oriented approach, large programs are divided into smaller
programs known as objects.
In OOP, the major emphasis is on data rather than procedure (function).
It ties data more closely to the function that operates on it, and protects it
from accidental modification from outside functions.
POP:
In the procedure oriented approach, large programs are divided into smaller
programs known as functions.
In POP, a program is written as a sequence of procedures or functions.
While we concentrate on the development of functions, we give very little
attention to the data that are being used by various functions.
OOP and POP Difference
Let’s dive deep into the comparison points between the two programming
paradigms in terms of certain parameters.
Inheritance is supported in
Inheritance three modes: public, private Inheritance is not supported.
& protected.
Problem Used for solving big Not suitable for solving big
Solving problems. problems.
Python Features
Python is a dynamic, high-level, free open source, and interpreted programming
language. It supports object-oriented programming as well as procedural-oriented
programming. In Python, we don’t need to declare the type of variable because it
is a dynamically typed language. For example, x = 10 Here, x can be anything
such as String, int, etc.
Features in Python
There are many features in Python, some of which are discussed below as follows:
1. Free and Open Source
Python language is freely available at the official website and you can download
it from the given download link below click on the Download
Python keyword. Download Python Since it is open-source, this means that
source code is also available to the public. So you can download it, use it as well
as share it.
2. Easy to code
Python is a high-level programming language. Python is very easy to learn the
language as compared to other languages like C, C#, Javascript, Java, etc. It is
very easy to code in the Python language and anybody can learn Python basics in
a few hours or days. It is also a developer-friendly language.
3. Easy to Read
As you will see, learning Python is quite simple. As was already established,
Python’s syntax is really straightforward. The code block is defined by the
indentations rather than by semicolons or brackets.
4. Object-Oriented Language
One of the key features of Python is Object-Oriented programming. Python
supports object-oriented language and concepts of classes, object encapsulation,
etc.
5. GUI Programming Support
Graphical User interfaces can be made using a module such as PyQt5, PyQt4,
wxPython, or Tk in python. PyQt5 is the most popular option for creating
graphical apps with Python.
6. High-Level Language
Python is a high-level language. When we write programs in Python, we do not
need to remember the system architecture, nor do we need to manage the memory.
7. Extensible feature
Python is an Extensible language. We can write some Python code into C or C++
language and also we can compile that code in C/C++ language.
8. Easy to Debug
Excellent information for mistake tracing. You will be able to quickly identify
and correct the majority of your program’s issues once you understand how
to interpret Python’s error traces. Simply by glancing at the code, you can
determine what it is designed to perform.
9. Python is a Portable language
Python language is also a portable language. For example, if we have Python code
for windows and if we want to run this code on other platforms such as Linux,
Unix, and Mac then we do not need to change it, we can run this code on any
platform.
10. Python is an Integrated language
Python is also an Integrated language because we can easily integrate Python with
other languages like C, C++, etc.
11. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by line
at a time. like other languages C, C++, Java, etc. there is no need to compile
Python code this makes it easier to debug our code. The source code of Python is
converted into an immediate form called bytecode.
12. Large Standard Library
Python has a large standard library that provides a rich set of modules and
functions so you do not have to write your own code for every single thing. There
are many libraries present in Python such as regular expressions, unit-testing, web
browsers, etc.
13. Dynamically Typed Language
Python is a dynamically-typed language. That means the type (for example- int,
double, long, etc.) for a variable is decided at run time not in advance because of
this feature we don’t need to specify the type of variable.
14. Frontend and backend development
With a new project py script, you can run and write Python codes in HTML with
the help of some simple tags <py-script>, <py-env>, etc. This will help you do
frontend development work in Python like javascript. Backend is the strong forte
of Python it’s extensively used for this work cause of its frameworks
like Django and Flask.
15. Allocating Memory Dynamically
In Python, the variable data type does not need to be specified. The memory is
automatically allocated to a variable at runtime when it is given a value.
Developers do not need to write int y = 18 if the integer value 15 is set to y. You
may just type y=18.
DATA TYPES IN PYTHON
What is a Data Type?
Data type represents the different kinds of values that we store in the
variable.
What is a variable?
Variable is the name of the memory location where we store different types
of values.
type()
It is a built-in function that returns the type of the objects/data elements
stored in any data type.
Syntax:
type(object)
• In python, the data types are:
Note: We do not need to specify the data type explicitly, the interpreter
automatically defines the data type during run time. Python is a dynamically
typed language.
1.NUMERIC
Numeric data type represents the data which has numeric value. Numeric
value can be integer, floating number or even complex numbers.
• Integers:
This value is represented by “int” class. It contains positive or negative
whole numbers (without fraction or decimal).
For example: 5,-10
• Complex:
Complex number is represented by “complex” class. It is specified as (real
part) + (imaginary part)j.
For example – 2+3j
• Float:
This value is represented by float class.
It is a real number with floating point representation. It is specified by a
decimal point.
/* Python program to demonstrate numeric value*/
a=5
print(“Type of a: “,type(a))
b=5.0
print(“Type of b: “,type(b))
c=2+4j
print(“Type of c: “,type(c))
OUTPUT:
Type of a: <class ‘int’>
Type of b: <class ‘float’>
Type of c: <class ‘complex’>
2.DICTIONARY
Python dictionary is an unordered collection of items. Each item of a dictionary has
a key pair.
In Python, a Dictionary can be created by placing a sequence of elements within
curly {} braces, separated by ‘comma’. Values in a dictionary can be of any
datatype and can be duplicated, whereas keys can’t be repeated and must be
immutable (value of the object cannot be changed overtime).
Example: {1: ‘a’, 2: ‘b’}
/* Python program to demonstrate Dictionary*/
a = {1: ‘Anurag’, 2: ‘University’, 3: ‘IT-B’}
print(“Type of a: “,type(a))
OUTPUT:
Type of a: <class ‘dict’>
3.BOOLEAN
Python boolean type is one of the built-in data types, which represents one of the
two values i.e. True or False.
Generally, it is used to represent the truth values of the expressions.
For example, 1==1 is True whereas 2<1 is False.
/* Python program to demonstrate Boolean*/
a=True
print(“Type of a: “,type(a))
b=False
print(“Type of b: “,type(b))
OUTPUT:
Type of a: <class ‘bool’>
Type of b: <class ‘bool’>
4.SET
A Set is an unordered collection data type that is iterable, mutable and has no
duplicate elements.
For example:
{2,4,6}
/* Python program to demonstrate set*/
a={45,56,12}
print(“Type of a: “,type(a))
b={“apple”,”kiwi”,”banana”}
print(“Type of b: “,type(b))
OUTPUT:
Type of a: <class ‘set’>
Type of b: <class ‘set’>
5.SEQUENCE
Sequence is the ordered collection of similar or different data types. Sequences
allows to store multiple values in an organized and efficient fashion. There are
several sequence types in Python.
• String:
Strings in python are surrounded by either single quotation marks, or double
quotation marks.
Example: ‘hello’ is same as “hello”
• List:
Lists are used to store multiple items in a single variable.
The items in the list are separated with the comma (,) and enclosed with the
square brackets [ ].
Example:
[2,’a’,5.7]
• Tuple
Tuples are used to store multiple items in a single variable.
Tuples are written with round brackets
The key difference between tuples and lists is that while the tuples are
immutable objects, lists are mutable. This means that tuples cannot be
changed while lists can be modified.
Example: (3,4.5,’b’)
/* Python program to demonstrate Sequences*/
a=[3,5.6,”hello”]
print(“Type of a: “,type(a))
b=(3,5.6,”hello”)
print(“Type of b: “,type(b))
OUTPUT:
Type of a: <class ‘list’>
Type of b: <class ‘tuple’>
***OPERATORS***
OPERATOR: It is a Symbol.
* It is used to perform the operation on operands.
* Based on no. of operands, it is clarified into 2 types...
(1).Unary operator. (2).Binary operator.
* Operators are divided into 7 types.
*Arithmatic operator:
Arithmetic operators are used to perform mathematical
operations like addition, subtraction, multiplication and
division.
There are 7 arithmetic operators in Python :
b= 3
print(a+b)
Output :
5
Output :
-1
Output :
6
Output :
1.5
5. Modulus Operator : In Python, % is the modulus operator.
It is used to find the remainder when first operand is divided
by the second.
Example :
a= 3
b=2
print(a%b)
Output :
1
Output :
8
*Assignment operator:
1) Assign: This operator is used to assign the value of the right
side of the expression to the left side operand.
Syntax:
x=y+z
Example:
a=3
b=5
c=a+b
print(c)
Output:
8
2) Add and Assign: This operator is used to add the right side
operand with the left side operand and then assigning the
result to the left operand.
syntax:
x += y
Example:
a=3
b=5
a += b
print(a)
Output:
8
3) Subtract and Assign: This operator is used to subtract the
right operand from the left operand and then assigning the
result to the left operand.
Syntax:
x -= y
Example:
a=3
b=5
a -= b
print(a)
Output:
-2
4) Multiply and Assign: This operator is used to multiply the
right operand with the left operand and then assigning the
result to the left operand.
Syntax:
x *= y
Example:
a=3
b=5
a *= b
print(a)
Output: 15
5) Divide and Assign: This operator is used to divide the left
operand with the right operand and then assigning the result
to the left operand.
Syntax:
x /= y
Example:
a=3
b=5
a /= b
print(a)
Output:
0.6
6) Modulus and Assign: This operator is used to take the
modulus using the left and the right operands and then
assigning the result to the left operand.
Syntax:
x %= y
Example:
a=3
b=5
a %= b
print(a)
Output:
3
7) Divide (floor) and Assign: This operator is used to divide the
left operand with the right operand and then assigning the
result(floor) to the left operand.
Syntax:
x //= y
Example:
a=3
b=5
a //= b
print(a)
Output:
0
8) Exponent and Assign: This operator is used to calculate the
exponent(raise power) value using operands and then
assigning the result to the left operand.
Syntax:
x **= y
Example:
a=3
b=5
a **= b
print(a)
Output:
243
9) Bitwise AND and Assign: This operator is used to perform
Bitwise AND on both operands and then assigning the result
to the left operand.
Syntax:
x &= y
Example:
a=3
b=5
a &= b
print(a)
Output:
1
10) Bitwise OR and Assign: This operator is used to perform
Bitwise OR on the operands and then assigning result to the
left operand.
Syntax:
x |= y
Example:
a=3
b=5
a |= b
print(a)
Output:
7
11) Bitwise XOR and Assign: This operator is used to perform
Bitwise XOR on the operands and then assigning result to the
left operand.
Syntax:
x ^= y
Example:
a=3
b=5
a ^= b
print(a)
Output:
6
12) Bitwise Right Shift and Assign: This operator is used to
perform Bitwise right shift on the operands and then assigning
result to the left operand.
Syntax:
x >>= y
Example:
a=3
b=5
a >>= b
print(a)
Output:
0
13) Bitwise Left Shift and Assign: This operator is used to
perform Bitwise left shift on the operands and then assigning
result to the left operand.
Syntax:
x <<= y
Example:
a=3
b=5
a <<= b
print(a)
Output:
96
==
Equal to: True if both operands are equal x == y
!=
Not equal to – True if operands are not equal x != y
Programs:
a =9
b = 5
print((a > b),(a<b),(a<=b),(a>=b),(a==b),(a!=b))
output:?
And Logical AND: True if both the operands are true x and y
if a and b and c:
print("All the numbers have boolean value as True")
else:
print("Atleast one number has boolean value as False")
output:?
2) Logical or operator:
if a or b or c:
print("Atleast one number has boolean value as True")
else:
print("All the numbers have boolean value as False")
output:?
if not a:
print("Boolean value of a is True")
output:?
*Identity operator:
• is and is not are the identity operators both are used to check if two
values are located on the same part of the memory. Two variables that
are equal do not imply that they are identical.
• is : True if the operands are identical
• is not : True if the operands are not identical
program:
a = 10
b = 20
c = a
print(a is not b)
print(a is c)
output:?
*Membership operator:
• in and not in are the membership operators; used to test whether a
value or variable is in a sequence.
• in : True if value is found in the sequence
• not in : True if value is not found in the sequence
program:
x = 24
y = 20
list = [10, 20, 30, 40, 50]
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
output: ?
*Bitwise operator: In Python, bitwise operators are used to performing
bitwise calculations on integers. The integers are first converted into binary
and then operations are performed on bit by bit, hence the name bitwise
operators. Then the result is returned in decimal format.
Example:
AND Bitwise:
OR Bitwise:
• 1|1=1
• 1|0=1
XOR Python:
● Equals: a == b
● Not Equals: a != b
● Less than: a < b
● Less than or equal to: a <= b
● Greater than: a > b
● Greater than or equal to: a >= b
1) Simple if
if statement is the most simple decision-making statement. It is used to
decide whether a certain statement or block of statements will be executed
or not i.e. if a certain condition is true then a block of statement is executed
otherwise not.
Syntax-
if condition:
statement 1
statement 2
.
.
.
Statement n
Example
if statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
EXPLANATION: In this example we use two variables, a and b,
which are used as part of the if statement to test whether b is greater than a.
As a is 33, and b is 200, we know that 200 is greater than 33, and so we print
to screen that "b is greater than a".
2) if else
The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false it won’t. But what if we
want to do something else if the condition is false. Here comes
the else statement. We can use the else statement with if statement to
execute a block of code when the condition is false.
Syntax-
if condition:
statement 1
statement 2
.
.
Statement n
else:
statement 1
statement 2
.
.
Statement n
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
3) Else if ladder
The elif keyword is pythons way of saying "if the previous conditions were
not true, then try this condition".
Here, a user can decide among multiple options. The if statements are
executed from the top down. As soon as one of the conditions controlling
the if is true, the statement associated with that if is executed, and the rest
of the ladder is bypassed. If none of the conditions is true, then the final
else statement will be executed.
Syntax-
if condition:
statement 1
statement 2
.
.
Statement n
elif:
statement 1
statement 2
.
.
Statement n
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
a=int(input(“enter number”)
if a==143:
OUTPUT:
enter number
143
I hate you
2)Biggest of 2 no.s
a=int(input("enter a no."))
b=int(input("enter a no."))
if(a>b):
print(a,"is biggest")
else:
print(b,"is biggest")
OUTPUT:
enter a no.4
enter a no.5
5 is biggest
a=int(input("enter a no."))
if(a%2==0):
print(a,"is even")
else:
print(a,"is odd")
OUTPUT:
enter a no.5
5 is odd
y=int(input("enter a no."))
if(x%y==0):
print(y,"is a factor")
else:
OUTPUT:
enter a no.6
enter a no.3
3 is a factor
5)WAP to read selling price and cost price and tell whether it is
profit or loss
sp=int(input("enter a no."))
cp=int(input("enter a no."))
if(sp>cp):
print("profit")
else:
print("loss")
OUTPUT:
enter a no.65
enter a no.75
loss
ch=input("enter a character")
else:
print(ch,"is a consonant")
OUPUT:
enter a character
a is a vowel
print("leap year")
else:
OUTPUT:
print(a,"is biggest")
print(b,"is biggest")
print(c,"is biggest")
elif(d>e):
print(d,"is biggest")
else:
print(e,"is biggest")
OUTPUT:
a=int(input("enter a no"))
b=int(input("enter a no "))
print(a+b)
elif(k==2):
print(a-b)
elif(k==3):
print(a*b)
elif(k==4):
print(a/b)
OUTPUT:
enter a no4
enter a no 5
1.ADD
2.SUb
3.MUL
4.Div
20
a=int(input("enter a no"))
if(a==1):
print("sunday")
elif(a==2):
print("monday")
elif(a==3):
print("tuesday")
elif(a==4):
print("wednesday")
elif(a==5):
print("thursday")
elif(a==6):
print("friday")
elif(a==7):
print("saturday")
OUTPUT:
enter a no5
thursday
n=int(input("enter a no"))
while(n!=0):
r=n%10
print(r)
n=n//10
OUTPUT:
enter a no376
6
s=0
n=int(input("enter a no"))
while(n!=0):
r=n%10
s=s+r
n=n//10
print("sum of digits",s)
OUTPUT:
enter a no467
sum of digits 17
s=0
n=int(input("enter a no"))
while(n!=0):
r=n%10
s=s*10+r
n=n//10
print("reverse of a number",s)
OUPUT:
enter a no467
13)Palindrone
s=0
n=int(input("enter a no"))
k=n
while(n!=0):
r=n%10
s=s*10+r
n=n//10
if(k==s):
print("palindrone")
else:
print("not palindrone")
OUTPUT:
enter a no2647
not palindrome
14)Armstrong
n=int(input("enter a no"))
k=n
while(n!=0):
r=n%10
s=s+(r*r*r)
n=n//10
if(k==s):
print("Armsrtong")
else:
print("not Armstrong")
OUTPUT:
enter a no153
Armsrtong
LOOPS
In general, statements are executed sequentially: the first statement in a
function is executed first, followed by the second, and so on. There may be
a situation when you need to execute a block of code several number of times.
Programming languages provide various control structures that allow for more
while expression:
statement(s)
Output:
print "Factorial is",f
Enter the number: 5
Factorial is 120
The for loop:
The for loop is useful to iterate over the elements of a sequence. It means, the for loop
can be used to execute a group of statements repeatedly depending upon the number of
elements in the sequence. The for loop can work with sequence like string, list, tuple, range
etc.
The syntax of the for loop is given below:
for var in sequence:
statement (s)
The first element of the sequence is assigned to the variable written after „for‟ and
then the statements are executed. Next, the second element of the sequence is assigned to the
variable and then the statements are executed second time. In this way, for each element of
the sequence, the statements are executed once. So, the for loop is executed as many times as
there are number of elements in thesequence.
Examples
printletter
print ""
print""
print ""
a=1
for i in range(1,5):
for j in range(1,i+1):
print a,
a=a+1
print ""