Python Programming - Unit 1
Python Programming - Unit 1
• Variable names are case-sensitive (age, Age and AGE are three different
variables)
Assigning Values to Variables:
• C = "John" # A string
Multiple Assignment:
• Python allows you to assign a single value to several variables simultaneously.
• Eg:
a=b=c=1
a=1; b=2
Here, an integer object is created with the value 1, and all three variables are assigned to
the same memory location. You can also assign multiple objects to multiple variables.
Eg:
a,b,c = 1,2,"mrcet”
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively,
and one string object with the value "john" is assigned to the variable c.
Output Variables:
• The Python print statement is often used to output variables. Variables do not
need to be declared with any particular type and can even change type after they
have been set.
Example:
x=5 # x is of type int
x = "mrcet " # x is now of type str
print(x)
• To combine both text and a variable, Python uses the “+” character:
Example :
x = "awesome"
print("Python is " + x) OutPut : Python is awesome
Operators in Python
Operators are used to perform operations on variables and values. Python divides the
operators in the following groups:
•Arithmetic operators
•Assignment operators
•Comparison operators
•Logical operators
•Identity operators
•Membership operators
•Bitwise operators
Arithmetic operators
3 Comparison Operators
- Subtract two operands or unary
>>3-1
2
subtract >>-2
4 Logical Operators
5 Bitwise Operators
* Multiply two operands >>2*3
6
6 Identity Operators
/ Divide left operand with the right >>6/3
7 Membership Operators and result is in float 2.0
Arithmetic operators
5 Bitwise Operators
//
Division that results into whole number >>7//3
6 Identity Operators adjusted to the left in the number line 2
7 Membership Operators
Arithmetic operators
7 Membership Operators
Assignment Operators
Assignment operators are used to assign value to a variable
Assignment operators
>>x=5
1 Arithmetic Operators
Arithmetic Operators
+= >>x+=3
x=x+3 >>print(x)
8
2 Assignment Operators
-= x=x-5
>>x-=5
3 Comparison Operators >>print(x)
0
4 Logical Operators
*= >>x*=2
5 Bitwise Operators x=x*2 >> print(x)
10
6 Identity Operators
>> x/=2
/= x=x/3 >> print(x)
7 Membership Operators 2.5
Comparison operators
1 Arithmetic Operators
Arithmetic Operators
> True if left operand is greater than >>2>3
the right False
2 Assignment Operators
3 Comparison Operators
< True if left operand is less than the >>2<3
right True
4 Logical Operators
==
>>2==2
5 Bitwise Operators True if left operand is equal to right
True
6 Identity Operators
!= True if left operand is not equal to >>x!=2
7 Membership Operators the right True
Comparison operators
#Comparison/Relational Operators
1 Arithmetic Operators
Arithmetic Operators n1=10
2 Assignment Operators n2=20
n3=30
3 Comparison Operators Print(n3>n2)
Print(n2 == n3)
4 Logical Operators
Print( n!= n2)
5 Bitwise Operators
Output :
6 Identity Operators True
>>x!=2
7 Membership Operators
False True
True
Logical operators
1 Arithmetic Operators
Arithmetic Operators
6 Identity Operators not Reverse the result, returns False if the result >>not (x<5
is true and x<10)
7 Membership Operators
Logical operators
1 Arithmetic Operators
Arithmetic Operators
#Logical Operator
2 Assignment Operators x=3
y=4
3 Comparison Operators
print(x>5 and y<6)
4 Logical Operators print(x>5 or y<6)
print(not x!=5)
5 Bitwise Operators
1 Arithmetic Operators
Arithmetic Operators
1 Arithmetic Operators
Arithmetic Operators
6 Identity Operators
7 Membership Operators
a=6 #110
Output :
b=2 #010
Bitwise and = 2
print('Bitwise and =', a&b) Bitwise or = 6
Bitwise xor = 4
print('Bitwise or =', a| b) right shift = 1
print('Bitwise xor =', a^b) left shift = 8
1 Arithmetic Operators
Arithmetic Operators
4 Logical Operators
Is not True if the operands are not identical (do >>x=y
>>x is not y
5 Bitwise Operators not refer to the same object)
False
6 Identity Operators
7 Membership Operators
Membership Operators
X=[1,2,3,4,5]
1 Arithmetic Operators
Arithmetic Operators
6 Identify Operators
7 Membership Operators
#Identity operators #Membership operators
a=10 L1=[1,2,3,4]
b=10 print(3 in L1)
print(a is b)
Output : True
Output : True
L1=[1,2,3,4]
a=10
print(5 not in L1)
b=20
print(a is not b)
Output : True
Output : True
Operator Precedence
Precedence of Operators:
• This is is used in an expression with more than one operator with
different precedence to determine which operation to perform first.
Example 1:
>>> 3+4*2
11
>>> (10+10)*2
40
Conditional expression:
• Syntax:
true_value if Condition else false_value
Output : smaller
CONDITIONAL STATEMENTS (Decision Making)
if statement
(if-else)statement
Nested if statement
if...elif..else ladder
33
The if statement
• The if statement is a decision making statement. It is used to control the flow of
execution of the statements and also used to test logically whether the condition is
true or false.
Syntax
if Test expression:
statement(s)
34
Example program Example program
a=10 a=10
if (a<=10): if (a<=10):
print("condition is true") print("condition is true")
Output :
Output :
condition is true
File "<string>", line 3
print("condition is true")
^
IndentationError: expected an indented block
35
n=4
if n%2==0:
print(n,"is even")
Output : 4 is even
Output :
Enter any positive integer : 2
2 is even
If … else Statement
The if…else statement is called alternative execution, in which there are two
possibilities and the condition determines wich one gets executed.
Syntax
if Test_expression:
Body of if
else:
Body of else
37
Write a program to check if a number is Odd or Even
OUTPUT
Enter any positive integer : 7
7 is Odd
38
Note : If u have only one statement to execute you can put it on the same line
Example:
a=int(input("Enter a value:"))
b=int(input("Enter b value:"))
Output :
Enter a value:8
Enter b value:42
b is greater
Nested if - else :We can write an entire if… else statement in another if… else
statement called nesting, and the statement is called nested if.
Syntax:
if condition 1 :
if condition 2 :
statement 1
else :
statement 2
else:
statement 3
Nested if-else statement-Example
n = int(input("Enter number:"))
if (n<=15):
OUTPUT
if (n == 10): Enter number : 10
print("play cricket")
Play cricket
else:
print("play kabaddi")
else:
print("Don't play game")
42
if-elif - else ladder statement
• elif – is a keyword used in Python in replacement of else if to place another condition
in the program. This is called chained conditional.
Syntax:
if Condition 1 :
statement block1
elif Condition 2 :
statement block2
elif Condition 3 :
statement block3
….
else :
default statement
Example1: largest among three numbers
44
Example2:
avg=int(input("Enter average of a student : "))
if avg>=70:
print("Distinction")
elif avg>=60:
print("First Class")
Output :
elif avg>=50:
Enter average of a student : 65
print("Second Class") First Class
elif avg>=40:
print("Third Class")
else:
print("failed")
LOOPS/REPETITIVE STATEMENTS
1. While Loop
2. For Loop
3. Nested For Loops
s 46
While loop
• Loops are either infinite or conditional. Python while loop keeps reiterating a block
of code defined inside it until the desired condition is met.
• The statements that are executed inside while can be a single line of code or a block
of multiple statements.
Syntax:
while(expression):
Statement(s)
#Example Program to demonstrate while loop
OUTPUT :
i=1
WELCOME TO MRCET
while i<=5: WELCOME TO MRCET
WELCOME TO MRCET
print("WELCOME TO MRCET") WELCOME TO MRCET
WELCOME TO MRCET
i=i+1
OUTPUT :
Enter any positive integer: 5
Factoril of a given number is = 120
Write a program to find sum of n natural numbers
50
Using else statement with while loops
Python supports t have an else statement associated with a loop
statement.
If the else statement is used with a while loop, the else statement
is executed when the condition false.
Program to illustrate the else in while loop
counter=0
while counter < 3: OUTPUT
Inside loop
print("Inside loop")
Inside loop
counter = counter + 1 Inside loop
else: Outside loop
print("Outside loop")
51
For loop statement
• The for loop is another repetitive control structure, and is used to execute a set of
instructions repeatedly, until the condition becomes false.
• The for loop in Python is used to iterate over a sequence (list, tuple, string) or
other iterable objects. Iterating over a sequence is called traversal
Syntax
Syntax: for var in sequence: A sequence of values assigned to
Statement(s) var in each iteration
OUTPUT :
1
4
16
36
121
400
Iterating over a list: Iterating over a Tuple:
list = [6, 5, 3, 8, 4, 2, 5, 4]
sum = 0 tuple = (2,3,5,7)
for val in list: for a in tuple:
print (a)
sum = sum+val
print("The sum is", sum)
OUTPUT :
2
3
5
OUTPUT : 7
The sumis 37
54
Iterating over a String: OUTPUT :
M
R
College=“MRCET”
C
for name in College: E
print(name) T
Example1:
OUTPUT :
for x in range(6):
0 1 2 3 4 5
print(x,end=' ')
Example2:
for x in range(2,6): OUTPUT :
2 3 4 5
print(x, end=' ')
Note : The range() function defaults to increment the sequence by 1,however it is
possible to specify the increment value by adding third parameter.
Example:
for x in range(2,20,2): OUTPUT :
print(x, end=' ') 2 4 6 8 10 12 14 16 18
Syntax:
Example2:
OUTPUT :
1
for i in range(1,5):
22
for j in range(i):
print(i , end=" ")
333
print( )
4444
Break and continue
You might face a situation in which you need to exit a loop completely when an
external condition is triggered or there may also be a situation when you want to
skip a part of the loop and start next execution.
Python provides break and continue statements to handle such situations and to
have good control on your loop.
Break:
• The break statement is used to terminate the loop or statement in which it is
present.
• If the break statement is present in the nested loop, then it terminates only those
loops which contains break statement.
FLOW CHART
while test expression:
if condition:
break
Output:
11
9
The number 88 is found
Terminating the loop
#Example:
for letter in "Python": # First Example
if letter == "h":
break
print("Current Letter :", letter )
Output:
Current Letter : P
Current Letter : y
Current Letter : t
CONTINUE:
• The continue statement is used to skip the rest of the code inside a loop for the
current iteration only. Loop does not terminate but continues on with the next
iteration.
Output:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
# Program to show the use of # program to display only odd numbers
continue inside loops
for val in "string": for num in [20, 11, 9, 66, 4, 89, 44]:
if val == "i": if num%2 == 0:
continue continue
print(val) print(num)
Output: Output:
s
t 11
r 9
n 89
g
Pass statement
• As the name suggests pass statement simply does nothing. The pass statement in Python is
used when a statement is required syntactically but you do not want any command or code
to execute.
• It is like null operation, as nothing will happen is it is executed. Pass statement can also be
used for writing empty loops.
• Pass is also used for empty control statement, function and classes.
Syntax:
pass
# Python program to demonstrate pass statement
s='MRCET' Output:
for i in s: M
if i == 'C': R
pass # No error will be raised C
print(i) E
T
List Comprehension:
• List Comprehension provide a concise way to create lists.
• List comprehension offers a shorter syntax when you want to create a new list based
on the values of an existing list.
• For example, assume we want to create a list of squares like,
Output:
Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Example: Based on a list of fruits, you want a new list, containing only the fruits
with the letter "a" in the name. Without list comprehension you will have to write
a for statement with a conditional test inside:
Output :
print(newlist)
Output :
['apple', 'banana', 'mango']
x=[m for m in range(8)]
List1=[x**2 for x in range(10) if x>4]
print(x) print(List1)
Output : Output:
[0, 1, 2, 3, 4, 5, 6, 7] [25, 36, 49, 64, 81]
Output :
[1, 9, 25, 49, 81]
Tuple Comprehension:
Tuple Comprehensions are special: The result of a tuple comprehension is special. You might expect
it to produce a tuple, but what it does is produce a special "generator" object that we can iterate
over.
For example:
x = (i for i in 'abc’) #tuple comprehension
print(x)
Output:
<generator object <genexpr> at 0x033EEC30>
we might expect this to print as ('a', 'b', 'c') but it prints as <generator object <genexpr> at
0x02AAD710>
• The result of a tuple comprehension is not a tuple: it is actually a generator. The only
thing that you need to know now about a generator now is that you can iterate over it,
but ONLY ONCE.
Output:
x = (i for i in 'abc')
a
for i in x:
b
print(i) c
Example:2
Output:
x={3*x for x in range(10) if x>5}
{18, 21, 24, 27}
print(x)
Dictionary Comprehension:
Output: Output:
Enter a number :567 Enter a number :978
sum= 18 sum = 24
# Program to check the given no is Armstrong or not