0% found this document useful (0 votes)
3 views12 pages

Python Unit 2notes

This document covers Python program flow control, focusing on conditional statements and loops. It explains the syntax and usage of if, elif, and else statements, as well as for and while loops, including nested loops and control flow statements like break and continue. Additionally, it provides examples and outputs for various loop structures and star patterns.

Uploaded by

Subodh Arts
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)
3 views12 pages

Python Unit 2notes

This document covers Python program flow control, focusing on conditional statements and loops. It explains the syntax and usage of if, elif, and else statements, as well as for and while loops, including nested loops and control flow statements like break and continue. Additionally, it provides examples and outputs for various loop structures and star patterns.

Uploaded by

Subodh Arts
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/ 12

Unit-2

Python Program Flow Control and Conditional Blocks

Conditional statement in Python: In Python, conditionals allow you to control the flow of your
program based on certain conditions. The main conditional statements in Python are if, elif (short for
"else if"), and else.

In Python, there are three forms of the if...else statement.


1. if statement
2. if...else statement
3. if...elif...else statement

1. Python if statement: The if statement evaluates condition. If the condition is evaluated to True,
the code inside the body of if is executed. If the condition is evaluated to False, the code inside the
body of if is skipped.

Syntax:
if condition:
# body of if statement

Example:
number = 10
# check if number is greater than 0
if number > 0:
print('Number is positive.')
print('The if statement is easy')

Output:
Number is positive.
The if statement is easy

2. Python if...else Statement: An if statement can have an optional else clause. The if...else
statement evaluates the given condition:

If the condition evaluates to True


● the code inside if is executed
● the code inside else is skipped

If the condition evaluates to False


● the code inside else is executed
● the code inside if is skipped

Syntax:
if condition:
# block of code if condition is True
else:
# block of code if condition is False
Example:
number = 10
if number > 0:
print('Positive number')
else:
print('Negative number')
print('This statement is always executed')

Output:
Positive number
This statement is always executed

3. Python if...elif...else Statement: The if...else statement is used to execute a block of code among
two alternatives. However, if we need to make a choice between more than two alternatives, then
we use the if...elif...else statement.

Here,
● If the condition1 evaluates to true, code block 1 is executed.
● If condition1 evaluates to false, then condition2 is evaluated.
● If condition2 is true, code block 2 is executed.
● If condition2 is false, code block 3 is executed.

Syntax:
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3
Example:
number = 0
if number > 0:
print("Positive number")
elif number == 0:
print('Zero')
else:
print('Negative number')
print('This statement is always executed')

Output:
Zero
This statement is always executed

4. Python Nested if statements: We can also use an if statement inside of an if statement. This is
known as a nested if statement.

Notes: We can add else and elif statements to the inner if statement as required. We can also insert
the inner if statement inside the outer else or elif statements(if they exist) We can nest multiple
layers of if statements.

Syntax:
# outer if statement
if condition1:
# statement(s)
# inner if statement
if condition2:
# statement(s)

Example:
number = 5
# outer if statement
if (number >= 0):
# inner if statement
if number == 0:
print('Number is 0')
# inner else statement
else:
print('Number is positive')
# outer else statement
else:
print('Number is negative')

Output:
Number is positive

Python Loops: In computer programming, loops are used to repeat a block of code. For example, if
we want to show a message 100 times, then we can use a loop. It's just a simple example; you can
achieve much more with loops.

There are 3 types of loops in Python:


1. For Loop
2. While Loop
3. Nested Loop

1. Python for Loop: In Python, a for loop is used to iterate over sequences such as lists, Tuples,
String, etc. For example,

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


# run a loop for each item of the list
for language in languages:
print(language)

Output:
Swift
Python
Go
JavaScript

In the above example, we have created a list called languages. Initially, the value of language is set to
the first element of the array,i.e. Swift, so the print statement inside the loop is executed. language is
updated with the next element of the list, and the print statement is executed again. This way, the
loop runs until the last element of the list is accessed

Syntax: The syntax of a for loop is:


for val insequence:
# statement(s)

Flowchart:
Python For Loop in Python String
This code uses a for loop to iterate over a string and print each character on a new line. The loop
assigns each character to the variable i and continues until all characters in the string have been
processed.

# Iterating over a String


print("String Iteration")
s = “Hello”
for i in s:
print(i)

Output:
String Iteration
H
e
l
l
o

Python For Loop with List


This code uses a for loop to iterate over a list of strings, printing each item in the list on a new line.
The loop assigns each item to the variable I and continues until all items in the list have been
processed.

# Python program to illustrate


# Iterating over a list
list = [“Hello”, “World”]
for i in list:
print(list)

Output:
Hello
World

Python For Loop in Python Dictionary


This code uses a for loop to iterate over a dictionary and print each key-value pair on a new line. The
loop assigns each key to the variable I and uses string formatting to print the key and its
corresponding value.

my_dict = {"a": 1, "b": 2, "c": 3}


for key in my_dict:
print(key)

Output:
a
b
c

If you want to iterate over the key-value pairs, you can use the items() method:

my_dict = {"a": 1, "b": 2, "c": 3}


for key, value in my_dict.items():
print(key, value)

Output:
a1
b2
c3

Python for Loop with Python range()


A range is a series of values between two numeric intervals. We use Python's built-in function range()
to define a range of values.

Example:
# use of range() to define a range of values
values = range(4)
# iterate from i = 0 to i = 3
for i in values:
print(i)

Output:
0
1
2
3
Using a for Loop Without Accessing Items: It is not mandatory to use items of a sequence within a
for loop.

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


for language in languages:
print('Hello')
print('Hi')

Output:
Hello
Hi
Hello
Hi
Hello
Hi

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

digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")

Output:
0
1
5
No items left.

2. Python while Loop: Python while loop is used to run a block code until a certain condition is met.

Syntax: The syntax of while loop is:


while condition:
# body of while loop

Here,
1. A while loop evaluates the condition
2. If the condition evaluates to True, the code inside the while loop is executed.
3. condition is evaluated again.
4. This process continues until the condition is False.
5. When the condition evaluates to False, the loop stops.
Flowchart:

Example: Python while Loop


# program to display numbers from 1 to 5
# initialise the variable
i=1
n=5
# while loop from i = 1 to 5
while i <= n:
print(i)
i=i+1

Output:
1
2
3
4
5

Infinite while Loop in Python: If the condition of a loop is always True the loop runs for infinite times
(until the memory is full). For example:

age = 32
# the test condition is always True
while age > 18:
print('You can vote')

Python While loop with else: In Python, a while loop may have an optional else block. Here, the else
part is executed after the condition of the loop evaluates to False.
counter = 0
while counter < 3:
print('Inside loop')
counter = counter + 1
else:
print('Inside else')

Output:
Inside loop
Inside loop
Inside loop
Inside else

3. Nested Loop: Nested loops in Python refer to the concept of having one loop inside another loop.
This allows you to iterate over elements in a hierarchical or multidimensional structure, such as
nested lists or matrices.

Syntax: The general syntax of nested loops in Python is as follows

for outer_item in outer_sequence:


# outer loop code
for inner_item in inner_sequence:
# inner loop code

Example:
fruits = ["apple", "banana", "cherry"]
colors = ["red", "yellow", "blue"]
for fruit in fruits:
for color in colors:
print(fruit, color)

Output:
apple red
apple yellow
apple blue
banana red
banana yellow
banana blue
cherry red
cherry yellow
cherry blue

Here are some examples of different star patterns you can create using loops in Python:

1. Square Star Pattern:

size = 5
for i in range(size):
for j in range(size):
print("*", end=" ")
print()
Output:
*****
*****
*****
*****
*****

2. Right Triangle Star Pattern:

size = 5
for i in range(size):
for j in range(i + 1):
print("*", end=" ")
print()

Output:
*
**
***
****
*****

3. Inverted Right Triangle Star Pattern:

size = 5
for i in range(size, 0, -1):
for j in range(i):
print("*", end=" ")
print()

Output:
*****
****
***
**
*

4. Pyramid Star Pattern:

size = 5
for i in range(size):
for j in range(size - i - 1):
print(" ", end="")
for k in range(2 * i + 1):
print("*", end="")
print()

Output:
*
***
*****
*******
*********
5. Diamond Star Pattern:

size = 5
for i in range(size):
for j in range(size - i - 1):
print(" ", end="")
for k in range(2 * i + 1):
print("*", end="")
print()

for i in range(size - 2, -1, -1):


for j in range(size - i - 1):
print(" ", end="")
for k in range(2 * i + 1):
print("*", end="")
print()

Output:
*
***
*****
*******
*********
*******
*****
***
*
Control flow Statement: In Python, break and continue are control flow statements that allow you to
alter the behaviour of loops.

1. Break statement: The break statement is used to exit or break out of a loop prematurely. When
the break statement is encountered within a loop, the loop is terminated, and the program execution
continues with the next statement after the loop.

Here's an example that uses break in a for loop to find a specific number in a list and stop the loop
once it is found:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


target = 7
for num in numbers:
if num == target:
print("Number found!")
break
print(num)
print("Loop finished")

Output:
1
2
3
4
5
6
Number found!
Loop finished

2. Continue statement: The continue statement is used to skip the rest of the current iteration of a
loop and move to the next iteration. When the continue statement is encountered within a loop, the
remaining statements in the loop body are skipped, and the loop proceeds with the next iteration.

Here's an example that uses continue in a for loop to skip printing even numbers:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


for num in numbers:
if num % 2 == 0:
continue
print(num)
print("Loop finished")

Output:
1
3
5
7
9
Loop finished

You might also like