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

Unit-2 Detailed notes

This document provides class notes on Python programming focusing on control flow and conditional blocks. It covers various control flow statements including if, else, and nested if statements, as well as loop structures such as for and while loops. Additionally, it discusses loop manipulation techniques and provides examples for practical understanding.

Uploaded by

mrimpatient04
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)
8 views

Unit-2 Detailed notes

This document provides class notes on Python programming focusing on control flow and conditional blocks. It covers various control flow statements including if, else, and nested if statements, as well as loop structures such as for and while loops. Additionally, it discusses loop manipulation techniques and provides examples for practical understanding.

Uploaded by

mrimpatient04
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/ 29

Ajay Kumar Garg Engineering College, Ghaziabad

Information Technology Department

Class Notes: Python Programming [BCC-302]


Unit -2
Python Program Flow Control Conditional Blocks

if, else and else if, Simple for loops in python


For loop using ranges, string, list and dictionaries
Use of while loops in python, Loop manipulation using pass, continue, break and else

Programming using Python conditional and loop blocks


programming using conditional and loop blocks

Conditional execution:

Normal flow of execution is sequential means they execute one statement after another in the order in
which they appear and stop when they sun out of statement. But a there may be a situation where the
execution of a statement or block of statement is based on some conditions.

Decision-making statements in programming languages decide the direction (Control Flow) of the flow of
program execution.

Types of Control Flow in Python:

In Python programming language, the type of control flow statements is as follows:

1. The if statement
2. The if-else statement
3. The nested-if statement
4. The if-elif-else ladder

Python if statement:
The if statement is the simplest decision-making statement. It is used to decide whether a certain
statement or block of statements will be executed or not .

Syntax:
if condition:

1
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

# Statements to execute if

# condition is true

Here, the condition after evaluation will be either true or false. if the statement accepts boolean values – if
the value is true then it will execute the block of statements below it otherwise not.

The Boolean expression after if is called the condition. If it is true, then the indented statement gets
executed. If not, nothing happens.

Ex:
a = 33
b = 200
if b > a:
print("b is greater than a")

Note:
A few important things to note about if statements:

1. The colon (:) is significant and required. It separates the header of the compound statement from
the body.
2. The line after the colon must be indented. It is standard in Python to use four spaces for indenting.
3. All lines indented the same amount after the colon will be executed whenever
BOOLEAN_EXPRESSION is true

Short Hand If:

If we have only one statement to execute, we can put it on the same line as the if statement.

2
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

if a > b: print("a is greater than b")

The pass Statement

if statements cannot be empty, but if you for some reason have an if statement with no content, put in
the pass statement to avoid getting an error.

a = 33
b = 200

if b > a:
pass

Python if –else statement: (Alternative execution):

A second form of the if statement is alternative execution, in which there are two possibilities and the
condition determines which one gets executed.

There are two possibilities and the condition determines which one gets executed.

The if statement alone tells us that if a condition is true, it will execute a block of statements and if the
condition is false, it won’t. But if we want to do something else if the condition is false, we can use
the else statement with if statement to execute a block of code when the if condition is false

The syntax looks like this:

Syntax:
if condition:

# Executes this block if

# condition is true

else:

# Executes this block if

# condition is false

3
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Ex:

a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Short Hand If ... Else

If we have only one statement to execute, one for if, and one for else, we can put it all on the same line:

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

Python Nested if statements:

We can also use an if statement inside of an if statement. This is known as a nested if statement.

The syntax of nested if statement is:

Syntax:
If condition 1 is true, we are heading towards condition 2, if not, we are heading towards condition 3
4
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

If condition 2 is true, the statement A will be executed, if not, the statement B will be executed.

If condition 1 is not true, the statement C will be executed.

After the end of the nested if else blocks, the rest of the code, i.e., the statement X will be executed

statement_X...

Syntax:
if condition_1:

if condition_2:

statement_A...

else:

statement_B...

else:

statement_ C...

Statement_X

# Python Program to display the greatest among three

# distinct numbers using nested if statement

# Inputting the three numbers


a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

# If a is greater than b
if a > b:
# If b is greater than c
if a > c:
print("The greatest number among the three is",a)
# If b is greater than c
if b > c:
# If b is greater than a
if b > a:
print("The greatest number among the three is",a)

5
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

# If c is greater than a
if c > a:
# If c is greater than b
if c > b:
print("The greatest number among the three is",a)

Python Program to Check if a Given Year is a Leap Year or Not

A leap year occurs in each year which is an integer multiple of 4 and if the year is also a multiple
of 100, it should also be a multiple of 400 to be a leap year.

# Python Program to check if the given year is a leap year or not

# Inputting the year


year = int(input("Enter any year: "))
if year % 4 == 0: # if the year is divisible by 4
if year % 100 == 0: # if the year is divisible by 100
if year % 400 == 0: # if the year is divisible by 400
print(f"{year} is a leap year.")
else: # if the year is divisible by 100 but not 400
print(f"{year} is not a leap year.")
else: # if the year is divisible by 4 but not 100
print(f"{year} is a leap year.")
else: # if the year is not divisible by 4
print(f"{year} is not a leap year.")

if-elif Statement

The if-elif statement is shortcut of if..else chain. While using if-elif statement at the end else block
is added which is performed if none of the above if-elif statement is true.

If elif else ladder:

It is also called as multi way selection statement.

When there is more than just two if conditions in if elif else statements, then it is referred to as if elif else
ladder, as it resembles the structure of a ladder in terms of if statements. If one of the if conditions turn out

6
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

to be true, then the rest of the ladder is just bypassed and the body of that particular if block is executed. If
all the if conditions turn out to be false, then the body of the last else block is executed.

Syntax: -
if condition-1:

statement1

elif condition-2:

statement2

. elif condition-3:

Statement3

elif condition-n

Statement-n

.else:

default statement

next statement

Flow Chart:-

7
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

a= 50

if (a == 20):
print (“value of variable a is 20”)
elif (a == 30):
print (“value of variable a is 30”)
elif (a == 40):
print (“value of variable a is 40”)
else:
print (“value of variable a is greater than 40”)

Output:
value of variable a is greater than 40

The loop in Python:

In programming loops are structure that repeats a sequence of instruction until a specific condition is met

8
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

A loop statement allows us to execute a statement or group of statements multiple times.

There are mainly two types of loops are available in Python.

Python for loop:

In Python, the for loop is often used to iterate over iterable objects such as lists, tuples, or strings.

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

If we have a section of code that we would like to repeat a certain number of times, we employ for loops.

The for-loop is usually used on an iterable object such as a list or the in-built range function.

Syntax of for Loop

for iterating_variable in sequence:

Statement(s)

The first item (at 0th index) in the sequence is assigned to the iterating variable iterating_var.

Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the
statement(s) block is executed until the entire sequence is exhausted.

As in flowchart, the loop will continue to execute until the last item in the sequence is reached.
9
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]

sum = 0

for num in numbers:

sum= sum + num ** 2

print("The sum of squares is: ", sum_)

Output:

The sum of squares is: 774

The range() Function:

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and stops before a specified number.

Syntax

range(start, stop, step)

Parameter Values

Parameter Description
Start Optional. An integer number specifying at which position to
start. Default is 0
Stop Required. An integer number specifying at which position to stop
(not included). Goes till stop-1
Step Optional. An integer number specifying the incrementation.
Default is 1

x = range (3, 11, 2)

for n in x:

print(n)

Output

10
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

5
7
9

The range() Function In Python For Loop

We can specify a particular range using an inbuilt Python function, named range(), to iterate the loop a
specified number of times through that range.

for i in range(2,10):

print(i)

Output:

By default, the increment in the range() function when used with loops is set to 1;

However, we can change or specify a particular increment by including a third parameter in the range()
function, as illustrated in the following example:

for i in range(2,10,2)

print(i)

Output:

4
11
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Looping Through a String:

Even strings are iterable objects, they contain a sequence of characters:

for x in "banana":

print(x)

Output:

b
a
n
a
n
a

Python for loop with else

A for loop can have an optional else block. The else part is executed when the loop is
exhausted (after the loop iterates through every item of a sequence).

For example:

digits = [0, 1, 5]

for i in digits:

print(i)

else:

print("No items left.")


Output

No items left.

12
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Here, the for loop prints all the items of the digits list. When the loop finishes, it executes the else block
and prints No items left.

Using a for Loop Without Accessing Items:

It is not mandatory to use items of a sequence within a for loop.

For example,

languages = ['Swift', 'Python', 'Go']

for language in languages:

print('Hello')

print('Hi')

Hello

Hi

Hello

Hi

Hello

Hi

Here, the loop runs three times because our list has three items. In each iteration, the loop body
prints 'Hello' and 'Hi' . The items of the list are not used within the loop.

While Loop in Python

While loop statements in Python are used to repeatedly execute a certain statement as long as the
condition provided in the while loop statement stays true. While loops let the program control to iterate
over a block of code.

Syntax of While Loop in Python:

while test_expression:

body of while

13
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

The program first evaluates the while loop condition. If it’s true, then the program enters the loop and
executes the body of the while loop. It continues to execute the body of the while loop as long as the
condition is true. When it is false, the program comes out of the loop and stops repeating the body of the
while loop.

a=1

while a<10:

print(” loop entered”, a, “times”)

a = a+1

print(“loop ends here”)

Output:

loop entered 1 times

loop entered 2 times

loop entered 3 times

loop entered 4 times

loop entered 5 times

loop entered 6 times

14
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

loop entered 7 times

loop entered 8 times

loop entered 9 times

loop ends here

Infinite While Loop in Python

Infinite while loop refers to a while loop where the while condition never becomes false. When a
condition never becomes false, the program enters the loop and keeps repeating that same block of code
over and over again, and the loop never ends.

The following example shows an infinite loop:

a=1

while a==1:

b = input(“what’s your name?”)

print(“Hi”, b, “, Welcome to IMSEC!”)

If we run the above code block, it will execute an infinite loop that will ask for our names again and again.
The loop won’t break until we press ‘Ctrl+C’.

Using else Statement with while Loops:

In Python, we can also use the else statement with loops. When the else statement is used with the while
loop, it is executed only if the condition becomes false.

a=1

while a<5:

print(“condition is true”)

a=a+1

else:

print(“condition is false now”)

15
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Output:

condition is true

condition is true

condition is true

condition is true

condition is false now

Single statement while Block:


while block consists of a single statement we can declare the entire loop in a single line. If there are
multiple statements in the block that makes up the loop body, they can be separated by semicolons (;).

Code

# Python program to show how to write a single statement while loop

# Python program to illustrate

# Single statement while block

count = 0

while (count < 5): count += 1; print("Hello")

Loop Control Statements:


Python offers the following two keywords which we can use to prematurely terminate a loop iteration.

Break statements in While loop


1. Break: The break keyword terminates the loop and transfers the control to the end of the loop.

Example:

a=1

16
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

while a <5:

a += 1

if a = = 3:

break

print(a)

Output:

Continue statements in While loop


Continue: The continue keyword terminates the ongoing iteration and transfers the control to the top of
the loop and the loop condition is evaluated again. If the condition is true, then the next iteration takes
place.

Example:

a=1

while a <5:

a += 1

if a = = 3:

continue

print(a)

Output:

17
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Number Pattern Program in Python using While Loop

n = int(input(“Enter the number of rows: ”))

i=1

while i <= n:

j=1

while j <= i:

print(“*”, end = “ ”)

j += 1

print()

i += 1

The output will be

Enter the number of rows: 4

**

***

****

18
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Factorial Program in Python using While Loop

num = int(input("Enter a number: "))

fac = 1

i=1

while i <= num:

fac = fac * i

i=i+1

print("Factorial of ", num, " is ", fac)

The output will be

Enter a number: 4

Factorial of 4 is 24

Pass Statement
Pass statements are used to create empty loops. Pass statement is also employed for classes, functions, and
empty control statements.

Code

# Python program to show how the pass statement works

for a string in "Python Loops":

pass

print( 'Last Letter:', string)

Output:

Last Letter:

Loop Interruptions in Python For Loop


19
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

1. break Statement

Just as in while loops, for loops can also be prematurely terminated using the break statement. The break
statement will immediately terminate the execution of the loop and transfer the control of the program to
the end of the loop.
Example:

# creating a list of numbers

number_list = [2,3,4,5,6,7,8]

for i in number_list:

print(i)

if i == 5:

break

Output:

2. Continue Statement

Just as with while loops, the continue statement can also be used in Python for loops to terminate the
ongoing iteration and transfer the control to the beginning of the loop to continue the next iteration.

number_list = [2,3,4,5,6,7,8]

for i in number_list:

if i = = 5:

continue

print(i)

Output:

20
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Else in Python for Loop:

For loop in Python can have an optional else block. The else block will be executed only when all
iterations are completed. When break is used in for loop to terminate the loop before all the iterations are
completed, the else block is ignored.
Example:

for i in range(1,6):

print(i)

else:

print(” All iterations completed”)

Output:

All iterations completed

Nested For Loop in Python

21
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

As the name suggests, nested loops are the loops that are nested inside an existing loop, that is, nested
loops are the body of another loop.

Example:
for i in range(1,9,2):

for j in range(i):

print( i, end = " ")

print()

Output:

333

55555

7777777

Reverse for loop in Python

We can reverse for loop in python in two ways. The first method is to use the reversed() function.

list = ['Mon', 'Tue', 'Wed', 'Thu']

for i in reversed(list) :

print(i)

The second method is using range(n,-1,-1)

list = ['Mon', 'Tue', 'Wed', 'Thu']

for i in range( len(list) - 1, -1, -1) :

print(list[i])

The output will be

Thu

Wed

Tue

22
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

Mon

Python program to count the total number of digits in a number.

# if the given number is 129475

given_number = 129475

# since we cannot iterate over an integer

# in python, we need to convert the

# integer into string first using the

# str() function

given_number = str(given_number)

# declare a variable to store

# the count of digits in the

# given number with value 0

count=0

for i in given_number:

count += 1

# print the total count at the end

print(count)

Python program to check if the given string is a palindrome.

# given string

given_string = "madam"

# an empty string variable to store

23
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

# the given string in reverse

reverse_string = ""

# iterate through the given string

# and append each element of the given string

# to the reverse_string variable

for i in given_string:

reverse_string = i + reverse_string

# if given_string matches the reverse_srting exactly

# the given string is a palindrome

if(given_string = = reverse_string):

print("The string", given_string,"is a Palindrome.")

# else the given string is not a palindrome

else:

print("The string",given_string,"is NOT a Palindrome.")

Python program to check if a given number is an Armstrong number

# the given number

given_number = 153

# convert given number to string

# so that we can iterate through it

given_number = str(given_number)

# store the lenght of the string for future use

string_length = len(given_number)

# initialize a sum variable with


24
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

# 0 value to store the sum of the product of

# each digit

sum = 0

# iterate through the given string

for i in given_number:

sum += int(i)**string_length

# if the sum matches the given string

# its an amstrong number

if sum == int(given_number):

print("The given number",given_number,"is an Amstrong number.")

# if the sum do not match with the given string

# its an amstrong number

else:

print("The given number",given_number,"is Not an Amstrong number.")

Python Loop through a Dictionary:


When looping through a dictionary, the return value are the keys of the dictionary, but there are methods
to return the values as well.

Print all key names in the dictionary, one by one:

dict = {

"one": "1",

"two": "2",

25
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

"three": 3

for x in dict:

print(x)

Output:

one

two

three

Print all values in the dictionary, one by one:

dict = {

"one": "1",

"two": "2",

"three": 3

for x in dict:

print(dict[x])

Output:

You can also use the values() function to return values of a dictionary:

dict = {

"one": "1",

"two": "2",

26
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

"three": 3

for x in dict.values():

print(x)

Output:

Loop through both keys and values, by using the items() function:

dict = {

"one": "1",

"two": "2",

"three": 3

for x,y in dict.items():

print(x,y)

Output:

one 1

two 2

three 3

27
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

1. Write a Python program to check whether the entered character is an Alphabet


or not.

# taking user input

ch = input("Enter a character: ")

if((ch>='a' and ch<= 'z') or (ch>='A' and ch<='Z')):

print(ch, "is an Alphabet")

else:

print(ch, "is not an Alphabet")

2. Python Program to Check If a number is Prime or not

# taking input from user

number = int(input("Enter any number: "))

# prime number is always greater than 1

if number > 1:

for i in range(2, number):

if (number % i) = = 0:

print(number, "is not a prime number")

break

else:

print(number, "is a prime number")

# if the entered number is less than or equal to 1

# then it is not prime number

28
Ajay Kumar Garg Engineering College, Ghaziabad
Information Technology Department

else:

print(number, "is not a prime number")

3. Python Program to display following pattern:


1,5

2,6

3,7

i=1

j=5

while i < 4:

while j < 8:

print(i, ",", j)

j=j+1

i=i+1

29

You might also like