Python Unit 2
Python Unit 2
print("Equality : ",a == b)
print("Not Equality : ",a != b)
print("Less than : ",a < b)
print("Greater Than : ",a > b)
print("Less than or equal to : ",a >= b)
print("Greater than or equal to : ",a <= b)
output :
Equality : False
Not Equality : True
Less than : True
Greater Than : False
Less than or equal to : False
Greater than or equal to : True
___________________________________________________________________
Example 1:
a= 5
b=6
print("and Operation : ",(a > 2) and (b >= 6))
Output :
and Operation : True
or Operation : True
not Operation : False
Example 2:
a= True
b = False
Output :
and Operation : False
or Operation : True
not Operation : False
not Operation : True
______________________________________________________________________________
Example 1:
a=3
b=3
print(a is b)
Output: True
Example 2:
# Comparing strings
string1 = "Hello"
string2 = "Python"
______________________________________________________________________________
3.1.4 Membership operators
- The membership operator is used to test memberships. That is, if that specific part is in
the given data structure, string, or not.
- The membership operator can be used with strings, lists, and tuples. There are two
membership operators in python are “in” and “not in”.
Example :
a= "Hello Python"
print("Py" in a)
print("Hel" not in a)
Output:
True
False
___________________________________________________________________
Example:
x = 10
y=7
print("result of Binary And :", x&y)
print("result of Binary OR :", x|y)
print("result of Binary XOR :", x^y)
print("result of Binary Ones complement :", ~x)
print("result of Binary left shift:", x<<2)
print("result of Binary right shift:", x>>2)
Output:
result of Binary And : 2
result of Binary OR : 15
result of Binary XOR : 13
result of Binary Ones complement : -11
result of Binary left shift: 40
result of Binary right shift: 2
______________________________________________________________________________
1 () Parentheses
Ex:
print((6 + 4) - (6 + 3))
O/P: 1
2 ** Exponentiation
Ex:
print(50 - 2 ** 3)
O/P : 42
3 +x -x ~x Unary plus, unary minus, and bitwise NOT
Ex:
print(100 + ~3) #~3=-4
O/P : 96
4 * / // % Multiplication, division, floor division, and
modulus
Ex:
print(10 + 5 * 2)
O/P : 20
5 + - Addition and subtraction
Ex:
print(50 - 5 * 2)
O/P : 40
6 << >> Bitwise left and right shifts
Ex:
print(6 >> 4 - 2)
O/P : 1
7 & Bitwise AND
Ex:
print(10 & 2 + 1)
O/P : 2
8 ^ Bitwise XOR
Ex:
print(6 ^ 2 + 1)
O/P : 5
9 | Bitwise OR
Ex:
print(6 | 2 + 1)
O/P : 7
10 == , !=, >, >=, <, <=, is, is Comparisons, identity, and membership
not, in, not in operators
Ex:
print(5 == 4 + 1)
O/P : True
11 not Logical NOT
Ex:
print(not 10 == 10)
O/P : True
12 and AND
Ex:
print(1 or 2 and 3)
O/P : 1
13 or OR
Ex:
print(4 or 5 + 10 or 8)
O/P : 4
______________________________________________________________________________
3.2 Control Flow
- Python executes programs sequentially, The Python interpreter executes a program line by
line, from top to bottom, left to right, the same way you are reading this page. Operations
and functions are performed by the interpreter in the order that they are presented. We
refer to this as control flow.
- Control flow allows you to execute specific code blocks repeatedly or conditionally. By
combining these fundamental building blocks, you may write complicated code. Without
control flow expressions, a program is just a collection of statements that are performed
sequentially.
- Python uses Conditional Statements, looping statements and loop manipulation statements
for control flow.
3.3.1 If Statements:
- The most basic decision control statement in Python is the if statement.
- The if statement is used to test a condition and if the condition is true, it executes a block
of code called as if-block.
- If condition is not true then it will not execute statements in if block, it will execute
statements after if block.
- The colon (:) sign must come after a boolean expression in order to use the if keyword. An
indented block is initiated by the colon (:) character. If the boolean expression in the if
statement is True, the sentences with the same level of indentation are carried out.
- In the event that the expression is not True (False), the interpreter executes statements at
an earlier indentation level and passes over the indented block.
- Flow chart of if statement :
___________________________________________________________________________
- Example1 :
a= int(input('Enter the number:'))
if (a<0):
print('The number is greater than 0')
Output 1:
Enter the number: 3 # the print statement was not executed because
of condition is false.
Output 2:
Enter the number:-2
The number is less than 0 # condition is true so, print statement is
executed.
_______________________________________________________________________
- Example2 :
a= int(input('Enter the number:'))
if (a<0):
print('The number is less than 0')
print('The number is greater than 0')
Output 1:
Enter the number:3
The number is greater than 0 # the print statement outside if block is
executed because of condition is false
Output 2:
Enter the number:-2
The number is less than 0
The number is greater than 0 # condition is true so, both print statements
are executed.
Output:
number 2 is greater than number 1
______________________________________________________________________________
- Example 2:
x = int(input("Enter the number : "))
if(x > 10):
print('x is greater than 10')
else:
print('x is less than 10')
Output:
Enter the number : 5
x is less than 10
______________________________________________________________________________
- Syntax:
if( condition ):
statement
elif (condition 2 ) :
statement
elif(condition 3 ):
statement
.
else:
statement
______________________________________________________________________________
- Example 1:
x = int(input("Enter the number : "))
if (x < 0):
print('x is negative number...')
elif (x > 0):
print('x is positive number...')
else:
print('x is 0...')
Output:
Enter the number : -5
x is negative number...
- Example 2:
print(“Select your Branch:”)
print('1. Computer')
print('2. IT')
print('3. AI-ML')
if( choice == 1 ):
print('You have selected Computer')
elif( choice == 2 ):
print('You have selected IT')
elif( choice == 3 ):
print('You have selected AI-ML')
else:
print('Wrong choice!')
Output 1:
Select your Branch:
1. Computer
2. IT
3. AI-ML
enter your choice number : 4
Wrong choice!
Output 2:
Select your Branch:
1. Computer
2. IT
3. AI-ML
enter your choice number : 1
You have selected Computer
______________________________________________________________________________
3.3.4 Nested if
- Nested if statements mean an if statement inside another if statement.
- If statements can be nested inside other if statements in Python. That is, we are able to nest
one if statement inside of another.
- They are useful when we have to make a number of decisions.
- Syntax:
if (expression):
if(expression):
Statement of nested if
else:
Statement of nested if else
Statement of outer if
Statement outside if block
______________________________________________________________________________
- Example 1:
i = int(input("Enter the number"))
if (i > 0):
if (i < 15):
print("i is smaller than 15")
if (i > 12):
print("i is greater than 12 too")
else:
print("i is greater than 10")
- In the above example, first we give any number as an input; if the input number is greater
than 0, control goes to nested if condition(i<15); if condition is true, it will print the
statement “i is smaller than 15”; and goes to next if condition, if this is also true, it will
print("i is greater than 12 too"); if it is false, then else condition will be executed.
- Output 1:
Output 2:
Enter the number : 25
Output 3:
Enter the number : 12
i is smaller than 15
i is greater than 10
________________________________________________________________________
- Syntax :
for itarator_variable in sequence_name:
Statements
...
Statements
- For and in are Python keywords, but you can call your iterator variable and iterable
whatever you want. Remember to include a colon after your for loop statement and to
indent any code that appears in the loop body.
- Example 1:
print("String Iteration")
string = "PYTHON"
for i in string:
print(i)
- Output:
String Iteration
P
Y
T
H
O
N
- Example 2:
A for loop can traverse any type of sequence item. In our first example, we'll assign
the name x to each of the three elements in a list, from left to right, and then execute the
print statement for each. In the print statement, the name x refers to the current item in the
list.
for x in ["Apple","Mango","Orange"]:
print(x, end=' ')
- Output:
Apple Mango Orange
- Example 3:
- The next example calculate the of all elements in a list.
list = [1,2,3,4]
sum = 0
for x in list:
sum = sum + x
print("sum of all numbers : ",sum)
- Output:
sum of all numbers : 10
- Range ()
Example 4 :
- Output:
Enter the value of n 5
The sum of numbers is: 1
The sum of numbers is: 3
The sum of numbers is:
6 The sum of numbers is:
10 The sum of numbers is: 15
______________________________________________________________________________
3.4.2 While Loop
- A while loop statement in the Python programming language repeatedly executes a
target statement as long as a specific condition is satisfied.
- Statements may be single or many statements. The condition can be any expression,
and true means any non-zero value.
- As long as the condition is true, the loop iterates. Programme control moves to the
next line after the loop when the condition is false.
- here, main point of the while loop is that the loop might not ever run. when the
condition is tested and the result is false, the loop body will be skipped and the first
statement after the while loop will be executed.
- Syntax:
While expressions:
Statements
- Example 1:
The print and increment instructions in the while block are continually run until
count is less than 10. The index count is incremented by 1 after the current value is
shown for each repetition.
count=0
while (count < 10):
print(count)
count = count + 1
Output :
0
1
2
3
4
5
6
7
8
9
- Example 2:
In the below example, initially, 0 is assigned to a variable number. In the while
loop, it checks if the condition is true or not; if the condition is true, it will execute
the statements in the while loop body and increment the number by 1 in each loop.
If the while condition is false, it goes to the else block and executes.
number=0
while number < 6:
print(number, " is less than 6")
number = number+1
else:
print(number, "is not Less than 6")
- Output :
0 is less than 6
1 is less than 6
2 is less than 6
3 is less than 6
4 is less than 6
5 is less than 6
6 is not Less than 6
- Example 3:
a=int(input("enter table number"))
i=1
while i<=10:
print(a,"x",i,"=",a*i) i=i+1
O/p:
enter table number 5
5x1=5
5x2=10
5x3=15
5x4=20
5x5=25
5x6=30
5x7=35
5x8=40
5x9=45
5x10=50
3.4.3 Nested Loops
- Python programming, allows using one loop inside another loop. On loop nesting is
that you can put any type of loop inside of any other type of loop. For example a for
loop can be inside a while loop or vice versa.
- Both for loops execute based on the test conditional expression. When the outer for
loop repeats its execution, the programme control returns to the inner for loop and
begins its second execution.
- That is, the programme control will enter the inner for loop each time the outer for
loop repeats the loop. When the inner for loop completes its execution, the outer for
loop ends.
Syntax :
# Outer for loop
for iterating_var in sequence:
statements # Outer block statement.
# Inner for loop
for iterating_var in sequence:
statements # Inner block statement.
statements # Outer block statement.
Statements
OR
statement(s)
statement(s)
statements
______________________________________________________________________________
- Example 1:
# outer loop
- Example 2:
n=int(input("enter the number of rows : "))
i=1
while i<=n:
j=1
while j<=i:
print("*",end="")
j=j+1
print()
i=i+1
- Output:
Enter the numbr of rows : 5
*
**
***
****
*****
______________________________________________________________________________
3.5 Loop manipulation
- The typical sequence of execution is altered by loop control statements. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.
- In Python, loop control statements are mostly used to break out of a loop, skip a specific
block of code, or even to abort program execution.
- Python control statements are used to manage a program's flow of execution. There are
three different kinds of control statements: pass, continue, and break. These statements
enable us to run particular parts of code only in response to specific conditions.
- Syntax :
Loop
Condition:
break
- Example :
n=0
while n<=10:
print(n)
n=n+1
if n==5:
break # if i is equals to 5,break all the next iterations without printing.
print("end")
- Output:
0
1
2
3
4
End
3.5.2 Continue
- The continue statement returns control to the beginning of the while loop.
- The continue statement rejects all remaining statements in the loop and returns control to
the top.
- Flowchart of Break:
- Syntax :
while True:
...
if x == 10:
continue
print(x)
- Example :
# loop from 1 to 10
for i in range(1, 11):
if i == 6: # If i is equals to 6,continue to next iteration without printing
continue
else:
print(i) # otherwise print the value of i
- Output :
1
2
3
4
5
7
8
9
10
_____________________________________________________________________________
3.5.3 Pass
- Python pass is a null statement provided by the Python programming language for
ignoring a set of code that should not be executed.
- It is used for linguistic statements that do not require a command or code to execute.
- The pass explanation is a null operation, which means that nothing happens when
executed. The pass is also useful in situations where your code is going to be utilized but
has yet to be written.
- Example :
for i in range(1, 11):
if i == 6:
pass
print("this is pass block")
print(i)
Output :
1
2
3
4
5
this is pass block
6
7
8
9
10
______________________________________________________________________________
Extra Programs :
Program :
celsius = int(input("Enter the Temperature in Celsius :\n"))
fahrenheit = (1.8 * celsius) + 32
print("Temperature in Fahrenheit :", fahrenheit)
Output :
Enter the Temperature in Celsius :
15
Temperature in Fahrenheit : 59.0
________________________________________________________________________
2. Write a python program to find whether the given number is even or odd using if -
else statement.
Program :
num = int(input('Enter the number to check if it is even or odd: '))
if (num % 2) == 0:
print ('The number is even')
else:
print ('The number is odd')
Output :
Enter the number to check if it is even or odd: 5
The number is odd
Enter the number to check if it is even or odd: 6
The number is even
______________________________________________________________________________
Output :
Enter the number: 10
It is a positive number
Enter the number: 0
It is zero
Enter the number: -6
It is a negative number
______________________________________________________________________________
4. Write a program to accept the three sides of a triangle to check whether the triangle
is isosceles,equilateral, right angled triangle.
Program :
side1 = float(input("Enter the length of the first side: "))
side2 = float(input("Enter the length of the second side: "))
side3 = float(input("Enter the length of the third side: "))
Output :
Enter the length of the first side: 2
Enter the length of the second side: 2
Enter the length of the third side: 2
It's an Equilateral Triangle.
----------------------------------------------------------
Enter the length of the first side: 2
Enter the length of the second side: 3
Enter the length of the third side: 3
It's an Isosceles Triangle
________________________________________________________________________
5. Write a python program for printing multiplication table of a given number using for
loop.
Program :
Num = int(input("Enter the number for table: "))
i=1
while i < 11:
result = Num * i
print(Num, " * ", i," = ",result)
i=i+1
Output :
Enter the number for table: 12
12 * 1 = 12
12 * 2 = 24
12 * 3 = 36
12 * 4 = 48
12 * 5 = 60
12 * 6 = 72
12 * 7 = 84
12 * 8 = 96
12 * 9 = 108
12 * 10 = 120
________________________________________________________________________
6. Write a python Program to Find Factorial of a Number.
Program :
n = int (input ("Enter a number: "))
factorial = 1
if n >= 1:
for i in range (1, n+1):
factorial=factorial *i
print("Factorial of the given number is: ", factorial)
Output :
Enter a number: 5
Factorial of the given number is: 120
7. Write a Program to Display student result of five subjects and display the percentage
with grade.
Program :
print("student result")
Maths = int(input("Enter the marks of Maths : "))
English = int(input("Enter the marks of English : "))
Science = int(input("Enter the marks of Science : "))
History = int(input("Enter the marks of History : "))
German = int(input("Enter the marks of German : "))
Total = Maths + English + Science + History + German
Percentage = Total/5
print("Total Marks out of 500 :", Total)
print("Percentage :", Percentage)
if Percentage >=75:
print("Distinction")
elif Percentage >=60 and Percentage < 75:
print("First Class")
elif Percentage >=45 and Percentage < 60:
print("Second Class")
elif Percentage >=40 and Percentage < 45:
print("Pass Class")
else:
print("Fail")
Output:
student result
Enter the marks of Maths : 80
Enter the marks of English : 70
Enter the marks of Science : 56
Enter the marks of History : 85
Enter the marks of German : 47
Total Marks out of 500 : 338
Percentage : 67.6
First Class
________________________________________________________________________
Program:
lower = 1
upper = 100
print("Prime numbers between", lower, "and", upper, "are:")
Output:
2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 ,
83 , 89 , 97
______________________________________________________________________________
Program:
for i in range(1,6):
for j in range(1,i+1):
print(j,end=' ')
print()
Output:
1
12
123
1234
12345
______________________________________________________________________________
10. Program to print following Pattern
1
121
12321
1234321
123454321
Program:
for row in range(1,6):
for j in range(1,6-row):
print(' ',end=' ')
for col in range(1,row+1):
print(col, end=' ')
for erow in range(col-1,0,-1):
print(erow,end=' ')
print()