0% found this document useful (0 votes)
13 views21 pages

Control Flow

Uploaded by

ajoantony2021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views21 pages

Control Flow

Uploaded by

ajoantony2021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Control Flow

Control flow statements in Python allow the program to execute


different code blocks based on certain conditions. Let’s look at the key
control flow statements in Python.
if
Statemen
tThe if statement in Python is similar to other languages. It checks a condition and executes a
block of code if the condition is True. Additional options for else and elif (else if) provide
flexibility for handling multiple conditions.

# Basic if-else example


x = 25
if x > 10:
print("More") # Output: More
else:
print("Less")
Example with elif for multiple conditions:
# Example with elif
y = 10000
if y > 5000:
print("Large") # Output: Large
elif y > 1000:
print("Medium")
else:
print("Small")

In this case, "Large" will be printed because y is greater than 5000. If y were between 1001
and 5000, "Medium" would print, and if y were 1000 or less, "Small" would print.
for
Loop
The for statement in Python iterates over items in a sequence, such as a
list, string, or dictionary, in the order they appear. Unlike for loops in
languages like C, Python's for loop does not require initialization,
incrementing, or stopping criteria—it simply goes through each item in the
sequence.
Example 1: Looping Over Characters in a String

• # Define a string H
e
• hello_string = "Hello World" l
l
o
• # Loop through each character W
o
• for char in hello_string: r
• print(char) l
d
Example 2: Looping Over Items in a
List
• # Define a list of fruits
• fruits = ["apple", "orange", "banana", "mango"]
OUTPUT

• # Loop through each fruit Fruit: apple


Fruit: orange
• for fruit in fruits: Fruit: banana
Fruit: mango
• print("Fruit:", fruit)
Example 3: Looping Over Keys in a
Dictionary
• # Define a dictionary
• student = {
• "name": "Mary",
Key: name Value: Mary
• "id": "8776", Key: id Value: 8776
Key: major Value: CS
• "major": "CS"
•}

• # Loop through each key in the dictionary


• for key in student:
• print("Key:", key, "Value:", student[key])
while
Loop
The while statement in Python repeatedly executes the statements within the
loop as long as the condition is True.

0
# Initialize a variable 2
i=0 4
6
# Loop while i is less than or equal to 100 ...
while i <= 100: 96
print(i) 98
i += 2 # Increment by 2 to get the next even number 100
range
Function
The range function in Python generates a sequence of
numbers in arithmetic progression. It is commonly used in
loops to generate numbers in a specific range.
range Function Examples
Example 1: Generate a List of Numbers from 0 to 9
python

# Using range to generate numbers from 0 to 9


numbers = range(10)
print(list(numbers))

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Break /
continue
The break and continue statements in Python allow for control over loop
execution:
•break: Exits the for or while loop entirely when a specified condition is
met.
•continue: Skips the current iteration and moves to the next iteration in
the loop.
break Statement
Example
This example demonstrates using break to stop the
loop if y equals 512.

# Loop through values generated by range 4


for y in range(4, 256, 4): 8
12
if y == 512: ...
break # Exit the loop when y equals 512 252

print(y)
continue Statement
Example

This example demonstrates using continue to skip over an item in the list
("banana") and continue with the next iteration.
# Define a list of fruits
fruits = ["apple", "orange", "banana", "mango"]

# Loop through each fruit


for item in fruits:
if item == "banana": Output
apple
continue # Skip printing "banana"
orange
print(item) mango
pass
Statement
this example, the pass statement is used in a loop to do nothing when the item is "banana"
# Define a list of fruits
fruits = ["apple", "orange", "banana", "mango"]

# Loop through each fruit


for item in fruits: Output
apple
if item == "banana": orange
pass # Do nothing when item is "banana" mango
else:
print(item)
In this example:
•When the loop encounters "banana", the pass statement is executed, which
does nothing and allows the loop to continue to the next item.
•"banana" is effectively ignored in the output
Functions

A function in Python is a block of reusable code that takes information as input (in
the form of parameters), performs a computation, and returns a result based on the
input information. Functions in Python begin with the def keyword, followed by the
function name and parentheses, which enclose any parameters. The code block within a
function starts after a colon and may include an optional documentation string (docstring)
to describe the function.
Example of a Function in Python
• # Dictionary of students with grades
• students = {
• "1": {"name": "Bob", "grade": 2.5},
• "2": {"name": "Mary", "grade": 3.5},
• "3": {"name": "David", "grade": 4.2},
• "4": {"name": "John", "grade": 4.1},
• "5": {"name": "Alice", "grade": 3.8}
•}
• # Function to calculate average grade
• def averageGrade(students):
• """This function computes the average grade."""
• total = 0
• for key in students:
• total += students[key]["grade"]
• average = total / len(students)
• return average

• # Calculate and print the average grade


• avg = averageGrade(students)
• print("The average grade is:", avg)

The average grade is: 3.62


Functions with Default Arguments
Functions can have default values for parameters. If a function is called with fewer
arguments than defined, the default values are used for the missing parameters.
: Example of Function with Default Arguments
# Function to display fruits with default values
def displayFruits(fruit1="apple", fruit2="orange"):
print("Fruit 1:", fruit1)
print("Fruit 2:", fruit2)
# Calling function without parameters
displayFruits() Fruit 1: apple
Fruit 2: orange

# Calling function with one parameter Fruit 1: banana


Fruit 2: orange
displayFruits("banana")
Fruit 1: grape
Fruit 2: kiwi
# Calling function with both parameters
displayFruits("grape", "kiwi")
Example of Variable-Length
Arguments
In Python, variable-length arguments allow a function to
accept any number of additional arguments. This is done
by prefixing the parameter name with an asterisk (*),
which collects extra positional arguments into a tuple.
# Function with variable-length arguments
def student(name, *varargs): Student Name: Nav
print("Student Name:", name)
for item in varargs: Student Name: Amy
print(item) Age: 14

# Calling the function with different numbers of arguments Student Name: Bob
student("Nav") Age: 30
student("Amy", "Age: 14") Major: CS
student("Bob", "Age: 30", "Major: CS")
Modules in Python
A module in Python is a file that contains Python definitions and statements.
These definitions and statements can include functions, classes, and variables
that can be used across different Python scripts. Organizing code into modules
enhances readability and reusability, and it is also easier to maintain large
projects.
To use a module in another Python script, you can import it using the import
keyword. Python comes with many built-in modules, but you can also create your
own.
Importing the Student Module

• # main.py (using the student module)


• import student # Importing the student module

• # Example student records


• students = {
• "Bob": {"grade": 3.5},
• "Mary": {"grade": 4.0},
• "David": {"grade": 3.8}
• }

You might also like