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

UNIT 2 Python

Uploaded by

papakhanna78
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

UNIT 2 Python

Uploaded by

papakhanna78
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

UNIT 2:

PYTHON PROGRAM FLOW CONTROL


CONDITIONAL BLOCKS
SUBJECT :PYTHON PROGRAMMING
input() Function in Python
The input function in Python is a powerful tool for interacting with users
and collecting data from the keyboard during program execution.

The input function in python reads the input as a string, which can then
be converted into other data types, such as integers, floating-point
numbers, or booleans.

Syntax of Input Function in Python : input([prompt])


Example 1 , of input() Function in Python: taking the Name and ID of
the user as the input from the user and printing it.
Example 2 :Taking two numbers from the users as input
and then printing the multiplication of those numbers.
• Converting Input into other Data Types
To convert the input into other data types, such as integers or floating-point
numbers, we can use the built-in conversion functions, such as int(), float(),
or bool().

• Handling Exceptions
When converting the input into other data types, it is essential to handle
exceptions. If the input provided by the user cannot be converted into the
desired data type, it will cause an error.

• Default Value
The input function also allows us to provide a default value, which will
be used if the user does not provide any input.
Conditional Statements in Python
• Conditional Statements are statements in Python that provide a
choice for the control flow based on a condition.
• It means that the control flow of the Python program will be
decided based on the outcome of the condition.
Types of Conditional Statements in Python
1. If Conditional Statement in Python
2. If else Conditional Statements in Python
3. Nested if..else Conditional Statements in Python
4. If-elif-else Conditional Statements in Python
5. Ternary Expression Conditional Statements in Python
If Conditional Statement in Python

• The if-else statement in Python is used to execute a block of code


when the condition in the if statement is true, and another block of
code when the condition is false.
Flowchart of If Statement :-
Syntax of If Statement:

if condition:
# Statements to execute if
# condition is true

# if statement example
if 10 > 5:
print("10 greater than 5")

print("Program ended")
Python supports the standard mathematical logical
conditions:
• 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
These conditions can be utilized in a variety of ways in the if
statement.
Practice Question :Program using ‘if’ statement
1. Python program to illustrate if the number is even using if
statement
2. Program to print the largest of the three numbers.
1.
2.
The if-else statement
• The if-else statement provides an else block combined with
the if statement which is executed in the false case of the
condition.

• If the condition is true, then the if-block is executed.


Otherwise, the else-block is executed.
The syntax of the if-else
statement is given below

if condition:
#block of statements
else:
#another block of statements
(else-block)
Practice questions : ‘if-else’ statement
1. Program to check whether a person is eligible to vote or not.
2. Program to check whether a number is even or not.
1.
2.
The elif statement
• The elif statement enables us to check multiple conditions and
execute the specific block of statements depending upon the true
condition among them.

• We can have any number of elif statements in our program depending


upon our need. However, using elif is optional.

• The elif statement works like an if-else-if ladder statement in C. It


must be succeeded by an if statement
• The syntax of the elif statement is given below:-
if expression 1:
# block of statements

elif expression 2:
# block of statements

elif expression 3:
# block of statements

else:
# block of statements
One line if statement:
if a > b: print("a is greater than b“)

One line if else statement:


a=2
b = 330
print("A") if a > b else print("B")

One line if else statement, with 3 conditions:


a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
Practice Question: elif statement
1. Write a program that takes user marks obtained in 5 subjects as
input and print their grade based on criteria (A,B,C,D,E)
2. Write a program to check whether a given year is a Leap Year.
• If a year is evenly divisible by 4 means having no remainder then go to next step.
If it is not divisible by 4. It is not a leap year. For example: 1997 is not a leap year.
• If a year is divisible by 4, but not by 100. For example: 2012, it is a leap year. If a
year is divisible by both 4 and 100, go to next step.
• If a year is divisible by 100, but not by 400. For example: 1900, then it is not a
leap year. If a year is divisible by both, then it is a leap year. So 2000 is a leap year

3. Python Program to check whether a number is positive or negative.


• 1.
• 3.


Python For Loops
• A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).

• With the for loop we can execute a set of statements, once for each
item in a list, tuple, set etc.

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
Lets examine the basic structure of a for loop in python :

animal = [“cat” ,”dog”,”penguin”,”whale”,”zebra”]

For x in animal :
print(x)
# you can understand this as ; for every animal ‘x’ in the list ‘animal’ ,print
the animal ‘x’.
#’x’ is known as the iterator and ‘animals’ is known as the iterable
Output :- cat
dog
penguin
whale
zebra **for and in are both Python keywords**
How to write a for loop in Python
Step 1
Tell Python you want to create a for loop by starting the statement with
for.
Step 2
Write the iterator variable (or loop variable). The iterator takes on each
value in an iterable (for example a list, tuple, or range) in a for loop one
at a time during each iteration of the loop.
**iterable means an object that can be looped over.
String Iteration

or
Python for Loop with Strings

Example
The following example compares each character and displays if it is not a
vowel ('a', 'e', 'i', 'o', 'u').
Text =
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Practice Program :
1. Write a for loop that prints the numbers from 1 to 10, inclusive.
(Hint: There's more than one way to do this)

2. Suppose you have a list called box_of_kittens


['fluffy','whiskers','mittens','socks'] as your iterable. You could name
your iterator variable anything you want, but you might choose to
call it 'kitten' to reference that you'll be looping through each
individual kitten [😺] in box_of_kittens.
• 2.
for Loop with Python range()
• In Python, the range() function returns a sequence of numbers. For
example,
Here, range(4) returns a sequence of 0, 1, 2 ,and 3.
Since the range() function returns a sequence of numbers, we can
iterate over it using a for loop. For example:-

o/p =
• The range() function has the following syntax −
range(start, stop, step)
Where,
• Start − Starting value of the range. Optional. Default is 0
• Stop − The range goes upto stop-1
• Step − Integers in the range increment by the step value. Option,
default is 1.
• Example :
Output :
PROGRAMS FOR PRACTICE :
• Python program to calculate the sum of all numbers from 1 to a given
number.
• Python program to calculate the sum of all the odd numbers within
the given range.
• Python program to print a multiplication table of a given number.
• Python program to display numbers from a list using a for loop.
• Python program to check if the given string is a palindrome.
• Python program to check if a given number is an Armstrong number
• Python program to check whether a given num is prime number or
not.
• Python program to get the Fibonacci series between 0 to 50
#Taking user input
Prime num inputn = int(input("Enter a number: "))

if inputn > 1:
# check for factors
for i in range(2,inputn):
if (inputn % i) == 0:
print(inputn,"is not a prime number.")
print(i,"times",inputn//i,"is",inputn)
break
else:
print(inputn,"is a prime number.")

#If the input number is less than or equal to 1, then it is not prime
else:
print(inputn,"is not a prime number.")
Algorithm
1.Add integer value to num variable.
2.Then initialize two variables n1 and n2 with value 0 and 1.
3. Check if num value is equal to 1, then print n1 only.
4.Else
1.Print the value of n1 and n2.
2.Then run a for loop from range(2, num) and inside the for loop perform the
following operations.
1.Initialize n3 with value of n1 + n2.
2.Update n1 to n2.
3.Update n2 to n3.
4.At last print n3.
• Tip: We can end a for loop before iterating through all the items by
using a break statement.
The continue Statement
With the continue statement we can stop the current iteration of the
loop, and continue with the next:
Example
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
In the above program, let's see how the pattern is printed.

• First, we get the height of the pyramid rows from the user.
• In the first loop, we iterate from i = 0 to i = rows.
• The second loop runs from j = 0 to i + 1. In each iteration of this loop,
we print i + 1 number of * without a new line. Here, the row number
gives the number of * required to be printed on that row. For example,
in the 2nd row, we print two *. Similarly, in the 3rd row, we print three
*.
• Once the inner loop ends, we print new line and start printing * in a
new line.
Example 4: Inverted half pyramid using *
*****
****
***
**
*
rows = int(input("Enter number of rows: "))

for i in range(rows, 0, -1):


for j in range(0, i):
print("* ", end=" ")

print()

(note** you can use ur logic as well **)


Python for Loop with Dictionaries :
• Unlike a list, tuple or a string, dictionary data type in Python is not a
sequence, as the items do not have a positional index.
(Dictionaries are used to store data values in key:value pairs,a
dictionary is a collection which is ordered*, changeable and do not
allow duplicates.)

• Traversing a dictionary is still possible with the for loop.


Example :
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers:
print (x)
Output :-
10
20
30
40

Example : 2
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers:
print (x,":",numbers[x])
Output :
10 : Ten
20 : Twenty
30 : Thirty
40 : Forty
Example 3:
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers.items():
print(x)
Output :
Difference in While and For loop :
• A While loop operates without prior knowledge of iterations
and allows for flexible initialization within its body.

• In general a while loop is used if you want an action to repeat


itself until a certain condition is met i.e. if statement. An for
loop is used when you want to iterate through an object. i.e.
iterate through an array.

• for loop is used when the number of iterations is known,


whereas execution is done in a while loop until the statement
in the program is proved wrong
• Example :

F-string is a way to format strings in Python, it aims to make it easier for


users to add variables, comma separators.
WHILE LOOP : Syntax >>
Print i as long as i is less than 6:

Note: remember to increment i, or else the loop will continue


forever.
Break , continue , pass keywords :
• break , continue , pass keyword used to control flow of loops in
python.
• break statement is used to exit a loop prematurely when a specific
condition is met .
• continue statement is used to skip the current iteration of loop when
a specific condition is met and it continue with the next iteration of
the loop.
• pass statement is no-op statement in python, meaning it does
nothing when executed.
The break Statement
• With the break statement we can stop the loop even if the while condition is true:
• Example
• Exit the loop when i is 3:
x= 0
while x < 8:
print(x)
if x == 4:
break
x += 1
o/p = 0
1
2
3
4
The continue Statement

• With the continue statement we can stop the current iteration, and
continue with the next:
Example
• Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i) // print is inside while loop and outside if loop
Pass statement :
• When the user does not know what code to write, So user simply
places a pass at that line.
• When the pass statement is executed, nothing happens, but you
avoid getting an error when empty code is not allowed.
When to use: When you don't know what to code or want to skip
an iteration of a loop.
How it works: The pass statement is executed by skipping past the
loop condition, function, or class.
Why it's useful: It can be used to prevent scripts from crashing,
focus on the structure of a script, or design class architecture
Example 1: Creating Empty Blocks of Code

if x < 0:
# TODO: Handle negative values
pass
else:
# TODO: Handle positive values
pass
In this example, an if statement checks whether x is less than 0. If it is, we
need to handle negative values. However, we have yet to decide what to
do, so we use the pass statement to create an empty code block. Similarly,
we use the pass statement for the else block since we have yet to decide
what to do with positive values
Using pass With Conditional Statement
Eg :- 1
n = 10

# use pass inside if statement


if n > 10:
pass

print('Hello')
Output :- Hello
Suppose we didn't use pass or just put a comment as:

n = 10

if n > 10:
# write code later

print('Hello')

Output : Here, we will get an error message: IndentationError: expected


an indented block
• Example of pass Statement:-

for letter in 'Python':


if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
print ("Good bye!")
Output :

Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
Faq :
Q: What is the while loop in Python?
A: The while loop in Python is a control flow statement that allows you
to repeatedly execute a block of code as long as a specified condition is
true. It provides a way to create iterative processes in your program.

Q: What is the difference between a while loop and a for loop in


Python?
A: The main difference between a while loop and a for loop is the way
they control the flow of execution. A while loop repeatedly executes a
block of code as long as a condition is true, whereas a for loop iterates
over a sequence (such as a list or a range) and executes the block of code
for each element in the sequence.

Q: How to avoid infinite loops with while loops?


A: To avoid infinite loops while loops, ensure that the condition within
the loop will eventually become False. Otherwise, the loop will continue
indefinitely. Make sure to include code within the loop that modifies the
variables involved in the condition, allowing the condition to become
False at some point.
The else Statement
• With the else statement we can run a block of code once when
the condition no longer is true:
• Example
• Print a message once the condition is false:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Program example for logic building :-
1. Adding elements to a list using while loop.
2. Python while loop to print a number series
3. Printing the items in a tuple using while loop
4. Finding the sum of numbers in a list using while loop.
5. Popping out elements from a list using while loop
1.
myList = []
i=0

while len(myList) < 4 :


myList.append(i)
i += 1

print(myList)

Output :-
2.
n = 10

while n <= 100:


print(n ,end = ",")
n = n+10

Output :-
3.
myTuple = (10,20,30,40,50,60)
i=0

while i < len(myTuple):


print(myTuple[i])
i += 1

Output :-
4.
myList = [23,45,12,10,25]
i=0
sum = 0

while i < len(myList):


sum += myList[i]
i += 1

print(sum)
5.
fruitsList = ["Mango","Apple","Orange","Guava"]

while fruitsList:
print(fruitsList.pop())

print(fruitsList)

Output :-

You might also like