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

Python Unit-2

The document provides an overview of control statements in Python, including conditional statements (if, if-else, if-elif-else, nested if-else), iterative statements (while loop, for loop, nested loops), and jump statements (break, continue, pass). It explains the syntax and provides examples for each type of statement, illustrating how they can be used to control the flow of a Python program. The document serves as a guide for understanding and implementing these fundamental programming concepts in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Python Unit-2

The document provides an overview of control statements in Python, including conditional statements (if, if-else, if-elif-else, nested if-else), iterative statements (while loop, for loop, nested loops), and jump statements (break, continue, pass). It explains the syntax and provides examples for each type of statement, illustrating how they can be used to control the flow of a Python program. The document serves as a guide for understanding and implementing these fundamental programming concepts in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Department of Computer Science

I – B.Sc., Computer Science


23UCSCC13
23UCSCC13: PYTHON PROGRAMMING

Unit - 2: Control Statements: Selection/Conditional Branching statements: if, if- if


else, nested if and if-elif-else
else statements. Iterative Statements: while loop, for
loop, else suite in loop and nested loops. Jump Statements: break, continue and
pass statements.

Control Flow Statements


The flow control statements are divided into three categories
1. Conditional statements
2. Iterative statements.
3. Transfer statements

Conditional statements
In Python, condition statements act depending on whether a given condition is true or false. You
can execute different blocks of codes depending on the outcome of a condition. Condition
statements always evaluate to either True or False.
There are three types of conditional statements.
1. if statement
2. if-else
3. if-elif-else
4. nested if-else
5. If statement
In control statements, The if statement is the simplest form. It takes a condition and evaluates to
either True or False.
If the condition is True, then the True block of code will be executed, and if the condition is False,
then the block of code is skipped, and The controller moves to the next line
Syntax of the if statement
if condition:
statement 1
statement 2
statement n

Let’s see the example of the if statement. In this example, we will calculate the square of a
number if it greater than 5
Example
number = 6
if number > 5:
# Calculate square
print(number * number)
print('Next lines of code')
Output
36
Next lines of code
If – else statement
The if-else statement checks the condition and executes the if block of code when the condition is
True, and if the condition is False, it will execute the else block of code.
Syntax of the if-else statement
if condition:
statement 1
else:
statement 2
If the condition is True, then statement 1 will be executed If the condition is False, statement 2
will be executed. See the following flowchart for more detail.
Example
password = input('Enter password ')

if password == "PYnative@#29":
print("Correct password")
else:
print("Incorrect Password")

Output 1:
Enter password PYnative@#29
Correct password
Output 2:
Enter password PYnative
Incorrect Password
Chain multiple if statement in Python ( Ifelif else statement)
In Python, the if-elif-else condition statement has an elif blocks to chain multiple conditions one
after another. This is useful when you need to check multiple conditions.
With the help of if-elif-else we can make a tricky decision. The elif statement checks multiple
conditions one by one and if the condition fulfills, then executes that code.
Syntax of the if-elif-else statement:
if condition-1:
statement 1
elif condition-2:
stetement 2
elif condition-3:
stetement 3
...
else:
statement
Example
def user_check(choice):
if choice == 1:
print("Admin")
elif choice == 2:
print("Editor")
elif choice == 3:
print("Guest")
else:
print("Wrong entry")
user_check(1)
user_check(2)
user_check(3)
user_check(4)
Output:

Admin
Editor
Guest
Wrong entry
Nested if-else statement
In Python, the nested if-else statement is an if statement inside another if-else statement. It is
allowed in Python to put any number of if statements in another if statement.
Indentation is the only way to differentiate the level of nesting. The nested if-else is useful when
we want to make a series of decisions.
Syntax of the nested-if-else:
if conditon_outer:
if condition_inner:
statement of inner if
else:
statement of inner else:
statement ot outer if
else:
Outer else
statement outside if block
Example: Find a greater number between two numbers
num1 = int(input('Enter first number '))
num2 = int(input('Enter second number '))

if num1 >= num2:


if num1 == num2:
print(num1, 'and', num2, 'are equal')
else:
print(num1, 'is greater than', num2)
else:
print(num1, 'is smaller than', num2)
Output 1:
Enter first number 56
Enter second number 15
56 is greater than 15
Output 2:
Enter first number 29
Enter second number 78
29 is smaller than 78

Iteration statements

Iteration statements or loop statements allow us to execute a block of statements repeatedly as long as the
condition is true. (Loops statements are used when we need to run same code again and again)
Type of Iteration Statements In Python 3

In Python Iteration (Loops) statements are of three types :-

1. While Loop

2. For Loop

3. Nested Loops

While Loop
In Python, a while loop is used to execute a block of statements repeatedly until a given
condition is satisfied. When the condition becomes false, the line immediately after the loop
in the program is executed.
Python While Loop Syntax:
while expression:
statement(s)
All the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code. Python uses indentation as its
method of grouping statements.
Let’s learn how to use a while loop in Python with Examples:
Example of Python While Loop
Let’s see a simple example of a while loop in Python. The given Python code uses
a ‘while' loop to print “Hello Geek” three times by incrementing a variable called ‘count' from
1 to 3.
Python
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")

Output
Hello Geek
Hello Geek
Hello Geek
Using else statement with While Loop in Python
The else clause is only executed when your while condition becomes false. If you break out of
the loop, or if an exception is raised, it won’t be executed.
Syntax of While Loop with else statement:
while condition:
# execute these statements
else:
# execute these statements
Here is an example of while loop with else statement in Python:
The code prints “Hello Geek” three times using a ‘while' loop and then, after the loop, it
prints “In Else Block” because there is an “else” block associated with the ‘while' loop.
Python
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
else:
print("In Else Block")

Output
Hello Geek
Hello Geek
Hello Geek
In Else Block
Infinite While Loop in Python
If we want a block of code to execute infinite number of time, we can use the while loop in
Python to do so.
The code uses a ‘while' loop with the condition (count == 0). This loop will only run as long
as count is equal to 0. Since count is initially set to 0, the loop will execute indefinitely because
the condition is always true.
Python
count = 0
while (count == 0):
print("Hello Geek")
Note: It is suggested not to use this type of loop as it is a never-ending infinite loop where the
condition is always true and you have to forcefully terminate the compiler.
For Loop
For loops are used for sequential traversal. For example: traversing
a list or string or array etc. In Python, there is “for in” loop which is similar to foreach loop
in other languages. Let us learn how to use for loops in Python for sequential traversals
with examples.
For Loop Syntax:
for iterator_var in sequence:
statements(s)
It can be used to iterate over a range and iterators.
Example:
The code uses a Python for loop that iterates over the values from 0 to 3 (not including 4),
as specified by the range(0, n) construct. It will print the values of ‘i' in each iteration of the
loop.
Python
n=4
for i in range(0, n):
print(i)

Output
0
1
2
3
Example with List, Tuple, String, and Dictionary Iteration Using for Loops in
Python
We can use for loop to iterate lists, tuples, strings and dictionaries in Python.
The code showcases different ways to iterate through various data structures in Python. It
demonstrates iteration over lists, tuples, strings, dictionaries, and sets, printing their
elements or key-value pairs.
The output displays the contents of each data structure as it is iterated.
Python
print("List Iteration")
l = ["geeks", "for", "geeks"]
for i in l:
print(i)

print("\nTuple Iteration")
t = ("geeks", "for", "geeks")
for i in t:
print(i)

print("\nString Iteration")
s = "Geeks"
for i in s:
print(i)

print("\nDictionary Iteration")
d = dict({'x':123, 'y':354})
for i in d:
print("%s %d" % (i, d[i]))

print("\nSet Iteration")
set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
print(i),

Output
List Iteration
geeks
for
geeks

Tuple Iteration
geeks
for
geeks

String Iteration
G
e
e
k
s
Dictionary Iteration
xyz 123
abc 345

Set Iteration
1
2
3
4
5
6
Iterating by the Index of Sequences
We can also use the index of elements in the sequence to iterate. The key idea is to first
calculate the length of the list and in iterate over the sequence within the range of this
length. See the below
Example: This code uses a ‘for' loop to iterate over a list and print each element. It iterates
through the list based on the index of each element, obtained using ‘range(len(list))'. The
result is that it prints each item in the list on separate lines.
Python
list = ["geeks", "for", "geeks"]
for index in range(len(list)):
print(list[index])

Output
geeks
for
geeks
Using else Statement with for Loop in Python
We can also combine else statement with for loop like in while loop. But as there is no
condition in for loop based on which the execution will terminate so the else block will be
executed immediately after for block finishes execution.
In this code, the ‘for' loop iterates over a list and prints each element, just like in the
previous example. However, after the loop is finished, the “else” block is executed. So, in this
case, it will print “Inside Else Block” once the loop completes.
Python
list = ["geeks", "for", "geeks"]
for index in range(len(list)):
print(list[index])
else:
print("Inside Else Block")

Output
geeks
for
geeks
Inside Else Block
Nested Loops in Python
Python programming language allows to use one loop inside another loop which is
called nested loop. Following section shows few examples to illustrate the concept.
Nested Loops Syntax:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in the Python programming language is as
follows:
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that we can put any type of loop inside of any other type of
loops in Python. For example, a for loop can be inside a while loop or vice versa.
Example: This Python code uses nested ‘for' loops to create a triangular pattern of
numbers. It iterates from 1 to 4 and, in each iteration, prints the current number multiple
times based on the iteration number. The result is a pyramid-like pattern of numbers.
Python
from __future__ import print_function
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()

Output
1
22
333
4444
Jump Statements

Jump Statement: As the name suggests, a jump statement is used to break the normal flow
of the program and jump onto a specific line of code in the program if the specific condition
is true. In simple words, it transfers the execution control of the program to another
statement if a specific condition associated becomes true. As we proceed further you will get
a better understanding of this concept.
Types of Jump Statements:
 Break: As the name suggests, a break statement is used to break or stop a flow control.
This is generally used in a loop. A break statement is used in a loop in such a way, that
when a particular condition becomes true, the break statement is executed and we come
out of the loop immediately at that moment.
Syntax:
Loop{
Condition:
break
}
Example:
Python3
# for loop traversing from 1 to 4
for i in range(1, 5):
# If this condition becomes true break will execute
if(i == 3):
# Break statement will terminate the entire loop
break
print(i)
Output

1
2
Continue
 The continue statement is somewhat similar to the break statement but there is one
significant difference between them. A break statement terminates the entire loop but
the continue statement skips only the current iteration and continues with the rest steps.
So, if we use the continue statement in a loop, it will only skip one iteration when the
associated condition is true and then continue the rest of the loop unlike the break
statement.
Syntax:
while True:
...
if x == 100:
continue
print(x)
Example:
Python3
# for loop traversing from 1 to 4
for i in range(1, 5):
# If this condition becomes true continue will execute
if(i == 2):
# Continue statement will skip the iteration when i=2 and continue the rest of the
loop
continue
print(i)
Output
1
3
4
Pass
 The pass statement is an interesting statement, as when it gets executed nothing
happens. It plays the role of a placeholder. This means that, if we want to write a piece of
code over there in the near future but we cannot keep that space empty, then we can use
the pass statement. In simple words, it is used to avoid getting an error from keeping an
empty space.
Syntax:
def function:
pass
Example:
Python3
# Traversing through every character of the string
for alphabet in 'Legends':
# If alphabet='g' program will do nothing and won't print the letter
if(alphabet == 'g'):
pass
else:
print(alphabet)
Output

L
e
e
n
d
s
return
 A return statement is also one type of jump statement. “return” statement terminates a
function and returns a value to the calling function. That means the return statement is
overall used to invoke a function so that the passed statements can be executed.
Syntax:
def fun():
statements
.
.
return [expression]
Python3
# Python program to demonstrate the
# return statement

# Function to multiply the two numbers


# x and y
def multiply(x, y):

# returning the multiplication


# of x and y
return x * y

# Driver Code
result = multiply(3, 5)

print(result)
Output

15

You might also like