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

Presentation 3

Uploaded by

bnhatm216
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)
5 views

Presentation 3

Uploaded by

bnhatm216
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

Python Introduction

Python Control Flow Statements and Loops

In Python programming, flow control is the order in which statements or blocks of code are executed at runtime
based on a condition.

Control Flow Statements

The flow control statements are divided into three categories

1. Conditional statements

2. Iterative statements.

3. Transfer statements
Python Introduction
Python Control Flow Statements and Loops

2. Iterative statements. What is for loop in Python


Python Introduction
Python Control Flow Statements and Loops

2. Iterative statements.
for
Syntax of for loop

for i in range/sequencee:
i is the iterating variable,
statement 1
statement 2 range specifies how many times the loop should run.
statement n

• In each iteration of the loop, the variable i get the current value
Example
for num in range(10):
print(num)
Python Introduction
Python Control Flow Statements and Loops

2. Iterative statements.
for
for loop with range()
The range() function returns a
sequence of numbers starting
from 0 (by default) if the
initial limit is not specified
and it increments by 1 (by
default) until a final limit is
reached

sum = 0
for i in range(2, 22, 2):
sum = sum + i
print(sum)
Python Introduction
Python Control Flow Statements and Loops
Python for loop
2. Iterative statements.
for loop with Tuple

A tuple is similar to a list but is immutable. You can loop through it in the same way as a list.
my_tuple = (10, 20, 30, 40, 50) ; for item in my_tuple: ;print(item)

for loop with Dictionary


dictionary stores key-value pairs. You can loop through keys, values, or both.
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Looping through keys
for key in my_dict:
print(key)
# Looping through values
for value in my_dict.values():
print(value)
# Looping through keys and values
for key, value in my_dict.items():
print(key, value)
Python Introduction
Python Control Flow Statements and Loops
Python for loop
2. Iterative statements.
for loop with Set

A set is an unordered collection of unique items. You can loop through a set just like a list or tuple.
my_set = {100, 200, 300, 400, 500} ;for item in my_set: ;print(item)

for loop with String


A string is a sequence of characters. You can loop through the characters of a string using a for loop.

my_string = "hello" for char in my_string: print(char)


Python Introduction
Python Control Flow Statements and Loops

2. Iterative statements. Python for loop


Example :Calculate the square of each number of list
numbers = [1, 2, 3, 4, 5] # iterate over each element
in list num
for i in numbers: # ** exponent operator
square = i ** 2
print("Square of:", i, "is:", square)

Note:
The loop runs till it reaches the last element in the
sequence. If it reaches the last element in the
sequence, it exits the loop. otherwise, it keeps on
executing the statements present under the loop’s
body
Python Introduction
Python Control Flow Statements and Loops

2. Iterative statements. Python for loop


Why use for loop?

• Definite Iteration: When we know how many times we wanted to run a loop, then we use count-controlled
loops such as for loops. It is also known as definite iteration. For example, Calculate the percentage of 50
students. here we know we need to iterate a loop 50 times (1 iteration for each student).
• Reduces the code’s complexity: Loop repeats a specific block of code a fixed number of times. It reduces
the repetition of lines of code, thus reducing the complexity of the code. Using for loops and while loops
we can automate and repeat tasks in an efficient manner.
• Loop through sequences: used for iterating over lists, strings, tuples, dictionaries, etc., and perform
various operations on it, based on the conditions specified by the user.
Python Introduction
Python Control Flow Statements and Loops

2. Iterative statements. Python for loop


If-else in for loop
• If-else is used when conditional iteration is needed. For example, print
student names who got more than 80 percent.
• The if-else statement checks the condition and if the condition is True it
executes the block of code present inside the if block and if the
condition is False, it will execute the block of code present inside the
else block.

for i in range(1, 11):


if i % 2 == 0:
print('Even Number:', i)
else:
print('Odd Number:', i)
Python Introduction
Python Control Flow Statements and Loops

2. Iterative statements. Python for loop


Loop Control Statements in for loop
Loop control statements change the normal flow of execution. It is used when you
want to exit a loop or skip a part of the loop based on the given condition. It
also knows as transfer statements

Break for loop


The break statement is used to terminate the loop. You can use the break
statement whenever you want to stop the loop. Just you need to type the break
inside the loop after the statement, after which you want to break the loop.
Python Introduction
Python Control Flow Statements and Loops

2. Iterative statements. Python for loop


Loop Control Statements in for loop
Break for loop

Example: break the loop if number a number is greater than 15


numbers = [1, 4, 7, 8, 15, 20, 35, 45, 55]
for i in numbers:
if i > 15:
# break the loop
break
else:
print(i)

# Nested loop with a break statement


for i in range(1, 4): # Outer loop
Note: If the break statement is used for j in range(1, 4): # Inner loop
inside a nested loop (loop inside print(f"i = {i}, j = {j}")
another loop), it will terminate the if j == 2:
innermost loop. break # Breaks the inner loop only when j is 2
Python Introduction
Python Control Flow Statements and Loops

2. Iterative statements. Python for loop


Loop Control Statements in for loop
Continue Statement in for loop
• The continue statement skips the current iteration
of a loop and immediately jumps to the next
iteration

• Use the continue statement when you want to jump


to the next iteration of the loop immediately.
Example: Count the total number of ‘m’ in a given string. name = "mariya mennen"
count = 0
for char in name:
if char != 'm':
continue
else:
count = count + 1

print('Total number of m is:', count)


Python Introduction
Python Control Flow Statements and Loops

2. Iterative statements. Python for loop


Loop Control Statements in for loop
Pass Statement in for loop
The pass statement is a null statement, i.e., nothing
happens when the statement is executed.

num = [1, 4, 5, 3, 7, 8]
for i in num:
# calculate multiplication in future if required
pass
Python Introduction
Python Control Flow Statements and Loops

2. Iterative statements. Python for loop


Else block in for loop

In Python, for-loop can have the else block, which


will be executed when the loop terminates normally.
Defining the else part with for loop is optional.

Else block will be skipped when


1. for loop terminate abruptly
2. the break statement is used to break the loop

Example : Else block in for loop

In this example, we are printing the first 5 numbers, and for i in range(1, 6):
after successful execution of a loop, the interpreter will print(i)
execute the else block. else:
print("Done")
Python Introduction
Python Control Flow Statements and Loops

2. Iterative statements. Python for loop


Reverse for loop backward iteration of a loop
There are three ways to iterating the for loop backward
• Reverse for loop using range()
• Reverse for loop using the reversed() function

Backward Iteration using the reversed() function


# Reversed numbers using reversed() function
list1 = [10, 20, 30, 40]
for num in reversed(list1): Reverse a list using a loop
print(num)
print("Reverse numbers using for loop") numbers = [1, 2, 3, 4]
Reverse for loop using range()
num = 5 for i in numbers[::-1]:
# start = 5 print(i)
# stop = -1
# step = -1
for num in (range(num, -1, -1)):
print(num)
Python Introduction
Python Control Flow Statements and Loops

2. Iterative statements. Python for loop


Nested for loops
• Nested for loop is a for loop inside another for a loop

• It is mainly used with two-dimensional arrays.

• In nested loops, the inner loop finishes all of its iteration for each iteration of the outer loop

Syntax of nested for loops:


# outer for loop
for element in sequence
# inner for loop
for element in sequence:
body of inner for loop
body of outer for loop
other statements
Python Introduction
Python Control Flow Statements and Loops

2. Iterative statements. Python for loop


Nested for loops
Example: Nested for loop to print the following pattern

rows = 6
# outer loop
for i in range(0, rows ):
*
# inner loop
* *
* * * for j in range(1, i + 1):
* * * *
print("*", end=" ")
* * * * *
print('')
Python Introduction
Python Control Flow Statements and Loops

2. Iterative statements. Python for loop


While loop inside for loop
The while loop is an entry-controlled loop, and a for loop is a count-controlled loop.

# outer loop
for i in range(1, 6):
print('Multiplication table of:', i)
count = 1
# inner loop to print multiplication table of current number
while count < 11:
print(i * count, end=' ')
count = count + 1
print('\n')
Python Introduction
Python Control Flow Statements and Loops

2. Iterative statements. Python for loop


for loop in one line
formulate the for loop statement in one line to reduce the number of lines of code.

Example: Print the even numbers by adding 1 to the odd numbers in the list

odd = [1, 5, 7, 9]
even = [i + 1 for i in odd if i % 2 == 1]
print(even)
Python Introduction
Python Control Flow Statements and Loops

2. Iterative statements. Python for loop


Accessing the index in for loop
• he enumerate() function is useful when we wanted to access both value and its index number
or any sequence such as list or string.
• The enumerate() adds a counter to iteration and returns it in the form of an enumerable
object.
numbers = [4, 2, 5, 7, 8]
for i, v in enumerate(numbers):
print(i,v)

dialogue = "Remember, Red, hope is a good


thing, maybe the best of things, and no good
thing ever dies" # split on whitespace for word
in dialogue.split(): print(word)
Python Introduction
Python Input: Take Input from User

In Python, Using the input() function, we take input from a user, and using the print() function,
we display output on the screen. Using the input() function, users can give any information to
the application in the strings or numbers format.

• The input is a value provided by the system or user

• There are different types of input devices we can use to provide data to application.
For example: –
• Stems from the keyboard: User entered some value using a keyboard.
• Using mouse click or movement: The user clicked on the radio button or some drop-down
list and chosen an option from it using mouse.
Python Introduction
Python Input: Take Input from User

How input() Function Works


syntax
input([prompt])

• The prompt argument is optional. The prompt argument is used to display a message to the user.
For example, the prompt is, “Please enter your name.”
• When the input() function executes, the program waits until a user enters some value.
• Next, the user enters some value on the screen using a keyboard.
• Finally, The input() function reads a value from the screen, converts it into a string, and returns it
to the calling program.

Note: If you enter an integer or float number, still, it will convert it into a string.
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements. Python while loop

• The while loop statement repeatedly executes a code block while a particular condition is true.
count = 1
# condition: Run loop till count is less than 3
while count < 3:
print(count)
count = count + 1

• We use a while loop when the number of iteration is not known beforehand. For example, if you want to ask
a user to guess your luck number between 1 and 10, we don’t know how many attempts the user may need
to guess the correct number. In such cases, use a while loop.

• when number of iteration is not fixed always use the while loop.
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements. Python while loop
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements. Python while loop
Syntax for while loop
while condition:
# Block of statement(s)

• The while statement checks the condition. The condition must return a boolean value. Either True or False.
• Next, If the condition evaluates to true, the while statement executes the statements present inside its block.
• The while statement continues checking the condition in each iteration and keeps executing its block until the
condition becomes false.

count = 1
# run loop till count is less than 5
while count < 5:
print(count)
count = count + 1

Note: The loop with continuing forever if you forgot to increment counter in the above example
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements. Python while loop
Syntax for while loop
while condition:
# Block of statement(s)

• The while statement checks the condition. The condition must return a boolean value. Either True or False.
• Next, If the condition evaluates to true, the while statement executes the statements present inside its block.
• The while statement continues checking the condition in each iteration and keeps executing its block until the
condition becomes false.

count = 1
# run loop till count is less than 5
while count < 5:
print(count)
count = count + 1

Note: The loop with continuing forever if you forgot to increment counter in the above example
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements. Python while loop
Example:
count = 0
number = 180
while number > 10:
# divide number by 3
number = number / 3
# increase count
count = count + 1
print('Total iteration required', count)

Flowchart of while loop


Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements. Python while loop
Why and When to Use while Loop in Python

• Automate and repeat tasks.: As we know, while loops execute blocks of code over and over again
until the condition is met it allows us to automate and repeat tasks in an efficient manner.

number = int(input('Enter any number between 100 and 500 '))


# number greater than 100 and less than 500
while number < 100 or number > 500:
print('Incorrect number, Please enter correct number:')
number = int(input('Enter a Number between 100 and 500 '))
else:
print("Given Number is correct", number)
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements. Python while loop
Why and When to Use while Loop in Python

• Indefinite Iteration: The while loop will run as often as necessary to complete a particular task.
When the user doesn’t know the number of iterations before execution, while loop is used
instead of a for loop
count = 0
number = 180
while number > 10:
# divide number by 3
number = number / 3
# increase count
count = count + 1
print('Total iteration required', count)
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements. Python while loop
Why and When to Use while Loop in Python

• Reduce complexity: while loop is easy to write. using the loop, we don’t need to write the
statements again and again. Instead, we can write statements we wanted to execute again and
again inside the body of the loop thus, reducing the complexity of the code
• Infinite loop: If the code inside the while loop doesn’t modify the variables being tested in the
loop condition, the loop will run forever.

# Infinite while loop


while True:
print('Hello')
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements. Python while loop
Transfer statements in while loop
It is used when you want to exit a loop or skip a
part of the loop based on the given condition. It
also knows as transfer statements.

• Break Statement

• Continue Statement

• Pass Statement
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements. Python while loop
Nested while loops while loop inside a while loop
while expression:
while expression:
statemen(s) of inner loop
statemen(s) of outer loop
for loop inside a while loop We can also use for loop inside a while loop as a nested loop.
i = 1
# outer while loop
while i < 5:
# nested for loop
for j in range(1, i + 1):
print("*", end=" ")
print('')
i = i + 1
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements. Python while loop
Else statement in while loop

In Python, we can use the else block in the while loop, which will be executed when the loop
terminates normally. Defining the else block with a while loop is optional.

The else block will not execute in the following conditions:


• while loop terminates abruptly
• The break statement is used to break the loop
i = 1
while i <= 5:
print(i)
i = i + 1
else:
print("Done. while loop executed normally")
Python Introduction
Python Control Flow Statements and Loops
2. Iterative statements. Python while loop
Reverse while loop

A reverse loop means an iterating loop in the backward direction. A simple example includes:
• Display numbers from 10 to 1.
• Reverse a string or list

# reverse while loop name = "Jessa"


i = 10 i=0
while i >= 0: res = len(name) - 1
print(i, end=' ') while i <= res:
i=i-1 print(name[i])
i=i+1
Python Introduction
Python Functions
The function is a block of code defined with a name.

We use functions whenever we need to Python has a DRY principle like


perform the same task multiple times other programming languages. DRY
without writing the same code again. It can stands for Don’t Repeat Yourself.
take arguments and returns the value.

Function improves efficiency and reduces errors because


of the reusability of a code. Once we create a function, we
can call it anywhere and anytime. The benefit of using a
function is reusability and modularity.
Python Introduction
Python Functions
Types of Functions

Python support two types of functions


• Built-in function
• User-defined function

• Built-in function
The functions which are come along with Python itself are called a built-in
function or predefined function. Some of them are listed below.

range(), id(), type(), input(), eval() etc


Python Introduction
Python Functions
Types of Functions
• User-defined function

Functions which are created by programmer explicitly according to the


requirement are called a user-defined function.

Creating a Function

Use the following steps to to define a function in Python.


• Use the def keyword with the function name to define a function.
• Next, pass the number of parameters as per your requirement. (Optional).
• Next, define the function body with a block of code. This block of code is nothing but the action
you wanted to perform.
Python Introduction
Python Functions
Types of Functions
• User-defined function
Syntax of creating a function

def function_name(parameter1, parameter2):


# function body
# write some action
return value

• function_name: Function name is the name of the function. We can give any name to function.
• parameter: Parameter is the value passed to the function. We can pass any number of parameters. Function
body uses the parameter’s value to perform an action
• function_body: The function body is a block of code that performs some task. This block of code is nothing
but the action you wanted to accomplish.
• return value: Return value is the output of the function.

Note: While defining a function, we use two keywords, def (mandatory) and return (optional).
Python Introduction
Python Functions
Types of Functions
• User-defined function

 Creating a function without any parameters


# function
def message():
print("Welcome to PYnative")

# call function using its name


message()

 Creating a function with parameters # function


def course_func(name, course_name):
print("Hello", name, "Welcome to PYnative")
print("Your course name is", course_name)

# call function
course_func('John', 'Python')
Python Introduction
Python Functions

• User-defined function
 Creating a function with parameters and return value

# function
def calculator(a, b):
add = a + b
# return the addition
return add

# call function
# take return value in variable
res = calculator(20, 5)

print("Addition :", res)


# Output Addition : 25
Python Introduction
Python Functions

• User-defined function
 Calling a function

• Once we defined a function or finalized structure, we can call that function by using its name.

• We can also call that function from another function or program by importing it.
# function
def even_odd(n):
# check numne ris even or odd
if n % 2 == 0:
print('Even number')
else:
print('Odd Number')

# calling function by its name


even_odd(19)
# Output Odd Number
Python Introduction
Python Functions

• User-defined function
 Calling a function of a module

• You can take advantage of the built-in module and use the functions defined in it.

How to use functions defined in any module.


 First, we need to use the import statement to import a specific function from a module.
 Next, we can call that function by its name.

# import randint function


from random import randint

# call randint function to get random number


print(randint(10, 20))
# Output 14

You might also like