0% found this document useful (0 votes)
11 views42 pages

Unit 3 Python Program Flow

The document is an introduction to Python programming, focusing on control flow structures such as conditional statements (if, if...else, if...elif...else) and loops (while, for). It provides syntax, examples, and flowcharts to illustrate how these structures work in Python. Additionally, it discusses the use of the assert keyword for debugging purposes.

Uploaded by

Ishan Dipte
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)
11 views42 pages

Unit 3 Python Program Flow

The document is an introduction to Python programming, focusing on control flow structures such as conditional statements (if, if...else, if...elif...else) and loops (while, for). It provides syntax, examples, and flowcharts to illustrate how these structures work in Python. Additionally, it discusses the use of the assert keyword for debugging purposes.

Uploaded by

Ishan Dipte
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/ 42

2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

Subject

Introduction to Python
by
Prof. M. V. Tiwari

(B. E. in Electronics & Telecommunication Engineering, H.V.P.M., C.O.E.T., Amravati,


2009.)
(M. Tech. in Electronic System & Communication, An Autonomous Institute of GCOE,
Amravati, 2013.)
(Pursuing Ph.D. from P.G. Department of Applied Electronics, S.G.B.A.U. under the
guidance of Dr. S. V. Dudul, Head PGDAE.)

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

Python Program Flow

Conditional Statements are handled by if statements.


Python provides the following options
• if statement
• if...else statement
• if...elif...else statement

Iterations handled by while and for statements.


Python provides the following options.
•while statement
•for statement
DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari
2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

1. If Loop
If statement in Python is required when there is a need to
make some kind of Decision. This decision making is used
to execute a code only if certain condition is satisfied.

Python if statement Syntax:


if test expression:
statement(s)

• Here, the program evaluates the test expression and will


execute statement(s) only if the test expression is True. If
test expression is False, the statement (s) is not executed.
• In Python, the body of the if statement is indicated by the
indentation. The body starts with an indentation and the
first unindented line marks the end.

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

Flow Chart of If statement

Syntax:
if test expression: False

statement(s) Test
Expression

True

Body of if

Fig : - Operation of if statement


DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari
2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

Example : - Python if statement

# If the number is positive, we print an appropriate message


num = int(input(‘Enter the number for testing : ’))
if num > 0:
print(num, "is a positive number.")

O/p :-
Enter the number for testing : 2
2 is a positive number.

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

Python if .... else statement

Syntax of if...else

if test expression:
Body of if
else:
Body of else

•The if...else statement evaluates test expression and will execute


the body f it only when the test condition is True.
•If condition is False, the body of else is executed.
•Indentation is used to separate the block.

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

Flowchart of if...else statement

Syntax of if...else False


if test expression: Test
Body of if Expression
else:
Body of else
True
Body of else
Body of if

Fig: - Operation of if...else statement


DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari
2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

Example of if...else statement.

# Program checks if the number is positive or negative


# And displays an appropriate message
num = int(input(“Enter the value for testing : ”))
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")

O/P : -
Enter the value for testing : -2
Negative number

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

Python if....elif....else Statement


Syntax of if...elif...else

if test expression:
Body of if
elif test condition:
Body of elif
else:
Body of else
•The elif is short for else if. It allows us to check for multiple expressions.
•If the condition for if is False, it checks the condition of the next elif block
and so on.
•If all the conditions are False, the body of else is executed.
•Only one block among the several if...elif...else blocks is executed according
to the conditions.
•The if block can have only one else block. But it can have multiple elif
blocks.
DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari
2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

Flow chart of if...elif...else Statement

Syntax of if...elif...else

if test expression:
Body of if
elif test condition:
Body of elif
else:
Body of else

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

Example of if...elif...else statement.

# Program checks if the number is zero or positive or negative


# And displays an appropriate message
num = int(input(“Enter the value for testing : ”))
if num = 0:
print(“It is Zero")
elif num>=0 :
print(“Positive number")
else:
print(“Negative number”)

O/P : -
Enter the value for testing : -2
Negative number
DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari
2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

2. While Statement
•The while loop in Python is used to iterate over a block of code as long as the
test expression (condition) is true.
•We generally use this loop when we don't know the number of times to iterate
beforehand.

Syntax of while Loop in Python


while test_expression:
Body of while

•In the while loop, test expression is checked first. The body of the loop is entered only if
the test_expression evaluates to True. After one iteration, the test expression is checked again.
This process continues until the test_expression evaluates to False.
•In Python, the body of the while loop is determined through indentation.
•The body starts with indentation and the first unindented line marks the end.
•Python interprets any non – zero value are True.
•None and 0 are interpreted as False

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

Flow Chart of While loop

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

# Program to add natural


# numbers up to
# sum = 1+2+3+...+n

n = int(input("Enter n: ")) # To take input from the user

#initialize sum and counter


sum = 0
i=1

while i <= n:
sum = sum + i
i = i+1 # update counter

# print the sum


print("The sum is", sum)

O/p :-
Enter n: 10
The sum is 55
DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari
2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

While loop with else


•Same as with for loop, while loops can also have an optional else block.
•The else part is executed if the condition in the while loop evaluates to False.
•The while loop can be terminated with a break statement.
•In such cases, the else part is ignored. Hence, a while loop's else part runs if no break
occurs and the condition is false.
Example :-
'''Example to illustrate the use of
else statement with the while loop''' O/p :-
counter = 0 0) Inside loop
while counter < 3: 1) Inside loop
print("Inside loop") 2) Inside loop
counter = counter + 1 3) Inside else
else:
print("Inside else")
DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari
2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

3. Python for Statement


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 of for loop


for val in sequence:
Body of for
Where val is the variable that takes the value of the item inside the sequence on each
iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is
separated from the rest of the code using indentation.
DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari
2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

Example of Python for loop


# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum += val # sum = sum + val
print("The sum is", sum)

O/p :-
The sum is 48

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

The range() function


➢range () function is very frequently used in for loop.
➢We can generate a sequence of numbers using range() function.
➢range(10) will generate numbers from 0 to 9 (10 numbers).
➢We can also define the start, stop and step size as range(start, stop, step_size).
Note : - step_size defaults to 1 if not provided.
➢The range object is "lazy" in a sense because it doesn't generate every number that it
"contains" when we create it. However, it is not an iterator since it
supports in, len and __getitem__ operations.
➢This function does not store all the values in memory; it would be inefficient. So it
remembers the start, stop, step size and generates the next number on the go.
➢To force this function to output all the items, we can use the function list().
DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari
2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

The following example will illustrate the use of range() function


1. print(range(10))
2. print(list(range(10)))
3. print(list(range(2, 8)))
4. print(list(range(2, 20, 3)))

O/P :-
1. range(0, 10)
2. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3. [2, 3, 4, 5, 6, 7]
4. [2, 5, 8, 11, 14, 17]

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

We can use the range() function in for loops to iterate through a


sequence of numbers. It can be combined with the len() function to
iterate through a sequence using indexing. Here is an example.

# Program to iterate through a list using indexing


genre = ['pop', 'rock', 'jazz']
# iterate over the list using index
for i in range(len(genre)):
print("I like", genre[i])

O/P :-
I like pop
I like rock ​
I like jazz

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

for loop with else


A for loop can have an optional else block as well. The else part is executed if the
items in the sequence used in for loop exhausts.
The break keyword can be used to stop a for loop. In such cases, the else part is
ignored.
Hence, a for loop's else part runs if no break occurs.
Here is an example to illustrate this.
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")

O/P :-
0
1
5
No items left.
DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari
2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

assert
1. Assert is one of the keywords in Python
2. The assert keyord is used when debugging code.
3. The assert keyword lets you test if a condition in your code returns True, if not,
the program will raise an AssertionError.
4. You can write a message to be written if the code returns False.

Syntax:-
assert condition, error_message(optional)

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

Why assertion is used?


It is a debugging tool, and its primary task is to check the condition. If it finds that
the condition is true, it moves to the next line of code, and If not, then stops all its
operations and throws an error. It points out the error in the code.

Where Assertion in Python used?


1. Checking the outputs of the functions.
2. Used for testing the code.
3. In checking the values of arguments.
4. Checking the valid input.

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

x = "hello"
#if condition returns True, then nothing happens:
assert x == "hello"
#if condition returns False, AssertionError is raised:
assert x == "goodbye“

In the above example (assert x = “hello”) nothing will happens since the condition is true.

When (assert x == “goodbye”) AssertionError will raised since the condition is false.

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

x = "welcome"
#if condition returns False, AssertionError is raised:
assert x == "hello", “should be ‘hello’ ”
In this code x holds “welcome” and assert statement checks for x == “hello”
condition. As this condition is false then assert will raised an error with message
(“should be ‘hello’ ”)
o/p:- AssertionError: x should be 'hello
'

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNX01 : Introduction to Python P R M I T & R ,B A D N E R A

Q 1)

even = False
if even = True:
print(“It is even ! ”)

A)The program has a syntax error in line 1 (even = False)


B) The program has syntax error in line 2 if even = True is not a correct
condition. It should be replaced by if even == True: or if even:
C) The program runs, but displays nothing.
D)The program runs and displays It is even !

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNT : Introduction to Python P R M I T & R ,B A D N E R A

Q 2) Suppose income is 4001, what will be displayed by the


following code ?

if income > 3000:


print(“Income is greater than 3000”)
elif income > 4000:
print(“Income is greater than 4000”)

A) Income is greater than 3000


B) Income is greater than 3000 followed by Income is greater
than 4000
C) Income is greater than 4000
D) Income is greater than 4000 followed by Income is greater
than 3000

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNT : Introduction to Python P R M I T & R ,B A D N E R A

Q 3) You are coding a math utility by using Python. You are writing a function
to compute roots. The function must meet the following requirements:
If a is non – negative
return a**(1/b)
If a is negative and even
return “result is imaginary number”
If a is negative and odd
return – (-a)**(1/b)
How should you complete the code ?
Using the following options:

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNT : Introduction to Python P R M I T & R ,B A D N E R A

if a >= 0:
elif a % 2 ==0:
else:
elif:

def safe_root(a, b):


__________
answer = a ** (1/b)
__________
answer = “result is imaginary number”
__________
answer = - (-a) ** (1/b)

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNT : Introduction to Python P R M I T & R ,B A D N E R A

Q 4) You are designing a decision structure to convert a student's numeric


grade to a letter grade. The program must assign a letter grade as specified in
the following table:
Percentage Letter
Range Grade
For example, if the user enters a 90, the output
90 through 100 A
should be, “Your letter grade is A.” Likewise, if
80 through 89 B a user enter an 89, the output should be “Your
70 through 79 C letter grade is B.” How should you complete the
65 through 69 D code ? To answer, select the appropriate code
segments in the answer area.
0 through 64 F

#Letter Grade converter


grade = int(input(“Enter a numeric grade”)) [4]________________________.
[1]________________________. letter_grade = ‘D’
letter_grade = ‘A’ else:
[2]__________________ letter_grade = ‘F’
letter_grade = ‘B’ Print(“Your letter grade is :”, letter_grade)
[3]__________________
letter_grade = ‘C’

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNT : Introduction to Python P R M I T & R ,B A D N E R A

Option 1: Option 2:
A. if grade = 90: B. if gade >= 90: A. if grade = 800: B. if gade >= 80:
C. elif grade >90: D. elif grade >= 90: C. elif grade >80: D. elif grade >= 80:

Option 1: Option 1:
A. if grade = 70: B. if gade >= 70: A. if grade = 65: B. if gade >= 65:
C. elif grade >70: D. elif grade >= 70: C. elif grade >965: D. elif grade >= 65:

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNT : Introduction to Python P R M I T & R ,B A D N E R A

Q 5) What is the output of the code shown below ?

if (9 < 0) and (0 < -9):


print(“hello”)
elif (9 > 0) or False:
print(“good”)
else:
print(“bad”)

A) error B) hello
C) good D) bad

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNT : Introduction to Python P R M I T & R ,B A D N E R A

Q 6) You are writing a Python Practice Test program to ask the user to enter a number and determine if the
number is 1 digit 2 digits or more than 2 digits long. You need to write the program. How should you
complete the code ? To answer, select the appropriate code segment in the answer area.

num = int(input(“Enter a number with a 1 or 2 digits : ”))


digits = 0
[1] ____________
digits = “1”
[2] ____________
digits = “2”
[3] ____________
digits = “>2”
print(digits + “digits.”)
[1]
A) If num > -10 and num < 10: B) if num > -100 and num < 100:
[2]
A) If num > -100 and num < 100: B) elif num > -100 and num < 100 :
C) If num > -10 and num < 10: D) elif num > -10 and num < 10:
[3]
A) else: B) elif:
DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari
2SAEKNT : Introduction to Python P R M I T & R ,B A D N E R A

Q 7) How many times will be the following code print “Welcome


to Python” ?
count = 0
while count < 10:
print(“Welcome to Python”)

A)9
B) 10
C) 11
D)Infinite number of times

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNT : Introduction to Python P R M I T & R ,B A D N E R A

Q 8) What will be displayed when the following code is executed ?

number = 6
while number > 0:
number -= 3
print(number, end = ‘ ‘)

Options :

A)6 3 0 B) 6 3
C) 3 0 D) 3 0 -3

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNT : Introduction to Python P R M I T & R ,B A D N E R A
Q 9) What is the output of the following ?

i=1
while True:
if i % 2 == 0:
break
print(i, end = ‘ ‘)
i += 2

Options :
A)1 B) 1 2
C) 1 2 3 4 5 6 ...... D) 1 3 5 7 9 11 .........

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNT : Introduction to Python P R M I T & R ,B A D N E R A
Q 10) A Classmate has asked you to debug the following code :

x=4
while x >= 1:
if x % 4 == 0:
print(“Party”, end = ‘ ‘)
elif x – 2 < 0:
print(“cake”, end = ‘ ‘)
elif x / 3 == 0:
print(“greeting”, end = ‘ ‘)
else:
print(“birthday”, end = ‘ ‘)
x = x -1

Options :

A) Birthday party greeting cake


B) Party birthday birthday cake
C) Party greeting birthday cake
D) Birthday greeting party cake
DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari
2SAEKNT : Introduction to Python P R M I T & R ,B A D N E R A

Q 11) What is the output of the following ?

for i in range (2.0):


print(i)

Options :
A)0 0 1 0
B) 0 1
C) Error
D)None of the mentioned

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNT : Introduction to Python P R M I T & R ,B A D N E R A

Q 12) The following loop displays _____________


for i in range (1, 11):
print(i, end = ‘ ‘ )

A)1 2 3 4 5 6 7 8 9
B) 1 2 3 4 5 6 7 8 9 10
C) 1 2 3 4 5
D)1 3 5 7 9

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNT : Introduction to Python P R M I T & R ,B A D N E R A

Q 13) What is the output for y ?

y=0
for i in range (10, 1, -2)
y += i
print(y)

A) 10
B) 40
C) 30
D) 20

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari


2SAEKNT : Introduction to Python P R M I T & R ,B A D N E R A

Q 14) What is the output of the following ?

x = ‘abcd’
for i in range (len(x)):
print(i, end = ‘ ‘)

A)a b c d
B) 0 1 2 3
C) Error
D)1 2 3 4

DEPARTMENT OF ELECTRONICS & TELECOMMUNICATION ENGINEERING PROF. M. V. Tiwari

You might also like