0% found this document useful (0 votes)
7 views

Python Unit 2

This document covers Python operators and control flow statements, detailing various types of operators including relational, logical, identity, membership, and bitwise operators. It explains how these operators function and their precedence in expressions, as well as the importance of control flow in executing code conditionally or repeatedly. The document provides examples and descriptions to illustrate the usage of these operators in Python programming.

Uploaded by

phalketanu1205
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Python Unit 2

This document covers Python operators and control flow statements, detailing various types of operators including relational, logical, identity, membership, and bitwise operators. It explains how these operators function and their precedence in expressions, as well as the importance of control flow in executing code conditionally or repeatedly. The document provides examples and descriptions to illustrate the usage of these operators in Python programming.

Uploaded by

phalketanu1205
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

UNIT II

Python Operators and Control Flow statements


2.0 INTRODUCTION
- Python operators are unique symbols that make working with variables and values easier.
They give you the ability to work with data, compare values, do mathematical
computations, and manage the program's flow. There are multiple types of operators in
Python, each with a specific function.
- Operators are constructs that may modify the value of operands. When the operator and
operand combine to perform a specific operation, the result is an expression. For example,
a + b , a and b are the operands and the plus (+) is the operator.
- The order in which statements are performed is referred to as the "flow of execution." That
is to say, the program's initial statement is where execution always begins. Additionally,
statements run one at a time. Everything takes place in a top-to-bottom order.
- Further, functions definitions do not alter the flow of execution of the program.The
programmer may need to alter the flow of program execution or to perform some
statements multiple times.
- for this problem, control structures are provided by python which transfers control from
one statement to another statement in program.
- Programming requires control structures because they let you define how your code will
execute. There are various kinds of control structures in Python such as conditional
statements, looping statements and loop control.

3.1 Relational and logical operators


- Relationships and logic are the fundamental building blocks of a program that
determine its functionality. Using these pillars, you may determine the proper
execution flow and the conditions that must be satisfied to ensure that the flow
continues in that direction.
- Conditions are necessary in all programming languages, including Python, to control
how a program flows. Relational and logical operators are needed to define those
conditions.
- The traditional symbols known as operators combine one, two, or more operands to
create an expression. Two important determinants of the output are operators and
operands.

3.1.1 Relational Operators


- Python's relational operators compare the values of the operands on either side.
Python's relational operators return boolean values, or either True or False, depending
on the operands' values.
- To put it simply, relational operators are used to compare values. Comparison
operators are another name for the relational operators.
- When comparing strings, the characters are compared alphabetically.
- Because there could be precision problems, exercise caution when comparing floating-
point figures. If you want to compare something, think about utilizing a very small
tolerance number rather than exact equivalence.
- There are six types of relational operators in python:
-
Sr. Operator Description
No
1 Equality Operator (= =) This operator determines whether the values on
both sides are equal. It returns True if that is the
case, and False otherwise.
Ex: 5 = = 5 Ex: 5 = = 10
Print(5 = = 5) Print(5 = = 10)
O/p : True O/p : False
2 Not Equality Operator This operator determines whether the values on
(! =) both sides are not equal. It returns True if the
operands are not true and False otherwise.
Ex: 5 ! = 6 Ex: 5 ! = 5
Print(5 ! = 6) Print(5 ! = 5)
O/p : True O/p : False
3 Greater than Sign (>) This operator determines whether the value on the
left is greater than the value on the right side.
Ex: 6 > 5 Ex: 5 > 6
Print(6 > 5) Print(5 > 6)
O/p : True O/p : False
4 Less than Sign ( < ) This operator determines whether the value on the
left is less than the value on the right side.
Ex: 4 < 5 Ex: 5 < 4
Print(4 < 5) Print(5 < 4)
O/p : True O/p : False
5 Greater than or Equal to This operator determines whether the value on the
(>=) left is greater than or equal to the value on the
right side.
Ex: 5 > =5 Ex: 5 > =6
Print(5 >= 5) Print(5 > =6)
O/p : True O/p : False
6 Less than or Equal to This operator determines whether the value on the
(<=) left is less than or equal to the value on the right
side.
Ex: 4 < =5 Ex: 5 <= 4
Print(4 <= 5) Print(5 <= 4)
O/p : True O/p : False
Example :
a=7
b = 10

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
___________________________________________________________________

3.1.2 Logical Operators :


- Python Logical Operators allow you to conduct logical operations on two or more
conditions. These operators are used for calculating the truth value of a given condition.
The logical operators AND, OR, and NOT are the most often utilized ones in Python.
- Conditional statements can be combined with logical operators in Python to perform
operations based on various conditions.
- Python understands None, numeric zeros of all sorts, empty sequences (strings, tuples,
lists), empty dictionaries, and empty sets as False, in addition to the keyword False. We
treat all other values as True.
- There are three logical operators, They are "and", "or" and "not". They must be in
lowercase.
Sr. Operator Description
No
1 and This operator determines whether the values on
both sides are true; if so, the result is true;
otherwise, it is false.
Ex:
x=5
print(x > 2 and x < 10)
O/P: True.
2 or This operator determines whether the values on
either side is true; if so, the result is true;
otherwise, it is false.
Ex:
x=5
print(x > 3 or x < 2)
O/P: True
3 not This operator determines whether the operand is
true it returns false and vice-versa. It is negative
operation.
Ex:
x=5
print(not(x > 3 and x < 10))
O/P: False

Example 1:
a= 5

b=6
print("and Operation : ",(a > 2) and (b >= 6))

print("or Operation : ",(a < 2) or (b >= 6))


print("not Operation : ",not(a > 2) and (b >= 6))

Output :
and Operation : True

or Operation : True
not Operation : False

Example 2:
a= True
b = False

print("and Operation : ",a and b)


print("or Operation : ",a or b)

print("not Operation : ",not a)


print("not Operation : ",not b)

Output :
and Operation : False

or Operation : True
not Operation : False
not Operation : True

______________________________________________________________________________

3.1.3 Identity operators


- The objects are compared by the identity operators to see if they relate to the same
object data type and share the same memory.
- Two identity operators were provided by Python, and these are “is” and “is not”.

Sr. Operator Description


No
1 is if returns true when two variables have the same
object, and false otherwise.
Ex:
x=8 , y=9
print(x is y)
O/P: False
2 Is not If two variables have the same object, if returns
false; otherwise, it returns true.
x=8 , y=9
print(x is not y)
O/P: True

Example 1:
a=3
b=3
print(a is b)

Output: True

Example 2:
# Comparing strings

string1 = "Hello"
string2 = "Python"

print(string1 is not string2)


Output: True

______________________________________________________________________________
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”.

Sr. Operator Description


No
1 in if a sequence with the specified value is present in
the object, it returns true otherwise false.
Ex:
x = ["ABC", "XYZ"]
print("ABC" in x)
O/P: True
2 Not in if a sequence with the specified value is not
present in the object, it returns true otherwise
false.
Ex:
x = ["ABC", "XYZ"]
print("XYZ" not in x)
O/P: True

Example :
a= "Hello Python"
print("Py" in a)

print("Hel" not in a)

Output:
True
False

___________________________________________________________________

3.1.5 Bitwise Operators


- Bitwise operations on integers are carried out using Python bitwise operators. The term
"bitwise operators" refers to the process of performing operations on single bits or related
pairs of bits after converting the integers into binary. After that, the result is given back in
decimal format.
Sr. Operator Description
No
1 & (binary and) If both bits in two operands are 1, 1 gets copied to the
result. Otherwise, zero is copied.
Ex: : if a = 5; b = 7; then,
binary (a) = 0101 binary (b) = 0111
a & b = 0101
O/P: 5
2 | (binary or) If both the bits are 0, The resulting bit will be 0
Otherwise the resulting bit will be 1.
Ex: : if a = 5; b = 7; then,
binary (a) = 0101 binary (b) = 0111
a | b = 0111
O/P: 7
3 ^ (binary xor) If both the bits are different, The resulting bit will be 1
Otherwise the resulting bit will be 0.
Ex: : if a = 5; b = 7; then,
binary (a) = 0101 binary (b) = 0111
a ^ b = 0010
O/P: 2
4 ~ (negation) If the bit is 0, the resulting bit will be 1 and vice versa.It
calculates the negation of each bit of the operand, i.e.,
Ex: : if a = 5; b = 7; then,
binary (a) = 0101 binary (b) = 0111
~a = -0110
O/P: -6
5 << (left The left operand value is moved left by the number of
shift) bits present in the right operand.
Ex: : if a = 5; b = 7; then,
binary (a) = 0101 binary (b) = 0111
a << 2
O/P: 20
6 >> (right The left operand is moved right by the number of bits
shift) present in the right operand.
Ex: : if a = 5; b = 7; then,
binary (a) = 0101 binary (b) = 0111
a >> 2
O/P: 1

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

______________________________________________________________________________

3.1.6 Operator Precedence:


- An expression may include numerous operators to be evaluated. Operator precedence
determines the order in which operators are evaluated.
- In other words, the sequence in which operators are evaluated depends upon their
precedence.
- If an expression has numerous operators, the order of precedence determines which ones
are evaluated.
- If we just consider the arithmetic operators in Python, the Python interpreter follows the
usual BODMAS rule, which evaluates brackets first, then division and multiplication
operators, and finally addition and subtraction operators.
- If two operators have the same precedence, the expression is evaluated from left to right.
For Example, 2 * 3 + ( 6 / 2) , it will evaluate bracket first which results 3 , then
multiplication which results 6 and then addition of both which is 9.
- In Below table, Precedence order is described, Starting with highest precedence
which is brackets to the lowest precedence which is or operator.

Precedence Operator Description


High to low

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 Decision Making statements: if, if-else, if-elif-else statements.


- Decision making statements are also called as Conditional Statements.
- Decisions in a program are used when the program has conditional choices to execute
a block of code.
- It is the predicting of conditions that happen during program execution in order to
define actions. Several expressions are tested, and the results are either TRUE or
FALSE.
- These are logical decisions, and Python also includes decision-making statements that
allow you to make judgments within a program for an application based on user input.
- Python offers multiple types of conditional statements, if statements, if-else statements,
if- elif-else statements.

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 :

Fig 3.3.1 : if statement – flowchart


- Syntax :
1. if condition:
# Statements to execute if condition is true
2. if condition:
statement1
statement2
# Here if the condition is true, if block will consider only statement1 to be inside
its block and when condition is false statement2 will print.

___________________________________________________________________________

- 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.

3.3.2 if-else Statement


- The if statement itself indicates that a block of statements will be executed if a condition is
true and won't be executed if it is false. However, we can use the else statement together
with the Python if statement to run a block of code when the if condition is false if we
want to do something different.
- The if-else statement checks the expression and performs the if block of code when the
expression is True; otherwise, it executes the else block of code. This is implied by the
name of the statement. When the expression is False, the else block executes and should
come immediately after the if block.

- Flowchart of if-else statement:

Fig 3.3.2 : if-else statement – flowchart


- Syntax:
1. if( condition ):
Statement
else:
Statement
________________________________________________________________________
- Example 1:
num1 = 10
num2 = 20
if(num1 >= num2 ):
print('number 1 is greater than number 2')
else:
print('number 2 is greater than number 1')

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
______________________________________________________________________________

3.3.3 if-elif-else Statement

- In python, elif keyword is used for else-if statement.


- The elif keyword in Python allows us to check multiple conditions together one after the
other. The elif keyword in Python allows us to check Complex decision-making statements
can be made with elif ladder.
- The elif keyword in Python allows us to check When one of the conditions controlling the
if condition is true, the statement associated with that if is executed, and the remaining part
of the ladder is skipped. If none of the conditions are satisfied, the final "else" expression
will be executed.
- Flowchart of if-else statement:

Fig 3.3.3 : if-elif-else statement – flowchart

- 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')

choice = int( input() )

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.

Flowchart of if-else statement:

Fig 3.3.4 : Nested if Statement – flowchart

- 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:

Enter the number : 10


i is smaller than 15
i is greater than 10

Output 2:
Enter the number : 25

i is greater than 12 too

Output 3:
Enter the number : 12
i is smaller than 15

i is greater than 10
________________________________________________________________________

3.4 Looping Statements: while loop, for loop, nested loops


- In general, statements are executed in a sequential order: the first statement in a function is
executed first, then the second, and so on. You may need to execute a block of code
multiple times.
- Programming languages have a variety of control structures, allowing for more complex
execution methods.
- Python loops enable us to run a statement or group of statements repeatedly.
- Python provides three types of loops for looping requirements are while loop, for loop and
nested loops.
-

3.4.1 For Loop


- For loops are used When you wish to repeat a block of code a certain number of times.
A list or range is an example of an iterable object that is always used together with a
for-loop.
- An iterator is a Python object that can be used to iterate over data collections such as
lists, tuples, dictionaries, and sets. Python iterators follow the iterator design pattern,
which enables you to navigate a container and access its elements.
- The Python for statement iterates through the items of a sequence in order, executing
the block each time. Anytime you have need to repeat a block of code a fixed amount
of times.
- Flowchart of For Loop

- 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 :

print("Enter the value of n") n=int(input())


sum=0
for i in range(1,n+1):
sum=sum+i
print("The sum of numbers is: ",sum)

- 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.

- Flowchart of While Loop:

- 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

while test_condition-1: # Outer while loop


statement(s)
while test_condition-2: # Inner while loop

statement(s)
statement(s)

statements
______________________________________________________________________________

- Example 1:
# outer loop

print(“Table of 1 and 2”)


for i in range(1, 3):
# nested loop
# to iterate from 1 to 10
for j in range(1, 11):
# print multiplication
print(i * j, end=' ')
print()
- Output :
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20

- 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.

3.5.1 Break Statement


- It ends the current loop and resumes execution with the next statement.
- The most common application for break is when an external event occurs that requires a
quick exit from a circular path.
- The break statement can be used in both while and for loops. If you are utilizing nested
loops, the break statement will stop the execution of the innermost loop and begin
executing the next line of code following the block.
- Flowchart of Break:

- 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.

- Flowchart for Pass :

- 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 :

1. Write a program to accept value of Celsius and convert it to Fahrenheit.

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
______________________________________________________________________________

3. Write a python program to check whether a input number is positive, negative or


zero using if-elif-else statement.
Program :
num = int(input("Enter the number: "))
if num > 0:
print("It is a positive number")
elif num == 0:
print("It is zero")
else:
print("It is a negative number")

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: "))

# Check for equilateral triangle


if side1 == side2 == side3:
print("It's an Equilateral Triangle.")
# Check for isosceles triangle
elif side1 == side2 or side1 == side3 or side2 == side3:
print("It's an Isosceles Triangle.")
# If it's neither equilateral nor isosceles, it must be scalene
else:
print("It's a Scalene Triangle.")

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

________________________________________________________________________

8. Write a Program to print prime numbers.

Program:
lower = 1
upper = 100
print("Prime numbers between", lower, "and", upper, "are:")

for num in range(lower, upper + 1):


# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num,',', end=' ')

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
______________________________________________________________________________

9. Program to print following Pyramid


1
12
123
1234
12345

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()

You might also like