Control flow is the heart of any programming language, allowing you to make decisions and repeat tasks. In Python, control flow is handled using if-else statements for decision-making and loops for repetitive tasks.
1. If-Else Statements
What are If-Else Statements?
If-Else statements let a program make decisions based on conditions. They evaluate whether a condition is True or False and execute specific blocks of code accordingly.
Structure:
if condition:
# Code block if the condition is True
elif another_condition:
# Code block if the `elif` condition is True
else:
# Code block if none of the conditions are True
Example 1: Basic If-Else
age = 18
if age >= 18:
print("You are an adult!") # Executes if age is 18 or more
else:
print("You are not an adult!") # Executes if age is less than 18
Explanation:
- Condition: age >= 18 is checked.
- If True, the code inside the if block runs.
If False, the code inside the else block runs.
Example 2: If-Elif-Else
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
else:
print("Grade: C")
Explanation:
- The program first checks marks >= 90. If True, it prints "Grade: A."
- If False, it checks marks >= 75. If True, it prints "Grade: B."
- If neither condition is True, it executes the else block and prints "Grade: C."
2. Loops in Python
Loops help repeat tasks efficiently. Python supports two main types of loops:
2.1 For Loop
What is a For Loop?
A for loop iterates over a sequence (like a list, range, or string) and executes a block of code for each item in the sequence.
Structure:
for variable in sequence:
# Code block to execute for each item
Example: Iterating Over a Range
for i in range(5):
print("Iteration:", i)
Output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Explanation:
- range(5) generates a sequence of numbers from 0 to 4.
- Each number is assigned to i, and the print() statement runs for each value.
2.2 While Loop
What is a While Loop?
A while loop runs as long as a condition is True. It checks the condition before each iteration.
Structure:
while condition:
# Code block to execute as long as the condition is True
Example: Counting with a While Loop
count = 0
while count < 5:
print("Count:", count)
count += 1
Output:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
Explanation:
- count starts at 0.
- The loop runs as long as count < 5.
- count += 1 increments the value of count in each iteration.
3. Combining Loops and Conditions
Skipping Specific Iterations: continue
The continue statement skips the current iteration and moves to the next.
Example: Skipping Number 5
for i in range(1, 11):
if i == 5:
continue # Skip the rest of the loop when i is 5
print(i)
Output:
1
2
3
4
6
7
8
9
10
Explanation:
- The loop iterates over numbers 1 to 10.
- When i == 5, the continue statement skips the print() for that iteration.
Stopping the Loop Early: break
The break statement exits the loop entirely.
Example: Breaking at Number 5
for i in range(1, 11):
if i == 5:
break # Exit the loop when i is 5
print(i)
Output:
1
2
3
4
4. Fun Challenge: Print 1 to 10, Skipping 5
Here’s a program that skips the number 5:
for i in range(1, 11): # Loop through numbers 1 to 10
if i == 5: # Check if the current number is 5
continue # Skip the iteration
print(i) # Print the number
Explanation:
- The range(1, 11) generates numbers from 1 to 10.
- When i == 5, the continue skips the rest of the loop body.
- All other numbers are printed.
Key Takeaways:
- Use if-else for decision-making.
- Use for loops when working with sequences or ranges.
- Use while loops when repeating tasks based on a condition.
- Use break to exit a loop early and continue to skip specific iterations.
Practice with real-world examples like counting, printing patterns, or creating interactive programs!
Introduction to Python Functions
Functions are the building blocks of any programming language. In Python, functions allow you to organize your code into reusable pieces, making your programs easier to write, debug, and maintain.
1. What is a Function?
A function is a reusable block of code designed to perform a specific task. Think of a function as a small program within your program. Instead of writing the same code multiple times, you can write it once and call it whenever you need.
Why Use Functions?
- Code Reusability: Write once, use multiple times.
- Modularity: Break complex problems into manageable chunks.
- Readability: Make your code easier to read and understand.
- Maintainability: Fixing bugs in a function fixes them everywhere it's used.
2. Defining a Function
To create a function, you use the def keyword followed by the function name and parentheses. Inside the parentheses, you can specify parameters (optional inputs the function can use).
Syntax:
def function_name(parameters):
# Code block (body of the function)
return value (optional)
Example 1: Basic Function
def greet(name):
print("Hello, " + name + "!")
Explanation:
- def greet(name):: Defines a function named greet that takes one parameter, name.
print("Hello, " + name + "!"): Prints a greeting message using the provided name.
Calling the Function:
To use (or "call") the function, type its name followed by parentheses:
greet("Alice")
Output:
Hello, Alice!
3. Functions with Parameters
Parameters are variables you pass into a function to customize its behavior.
Example 2: Function with Two Parameters
def introduce(name, age):
print(f"My name is {name}, and I am {age} years old.")
Calling the Function:
introduce("Bob", 30)
Output:
My name is Bob, and I am 30 years old.
4. Functions with Return Values
Sometimes, a function needs to perform a calculation or process and send the result back to the code that called it. This is done using the return keyword.
Syntax:
def function_name(parameters):
# Perform operations
return result
Example 3: Adding Two Numbers
def add(a, b):
return a + b
Calling the Function:
result = add(5, 7)
print(result)
Output:
12
Explanation:
- add(5, 7): Calls the add function with 5 and 7 as arguments.
- return a + b: Adds 5 and 7 and returns 12.
- result = add(5, 7): Stores the result (12) in the variable result.
5. Functions Without Parameters
You can also define functions that don’t require any parameters.
Example 4: Simple Greeting
def greet():
print("Hello, World!")
Calling the Function:
greet()
Output:
Hello, World!
6. Function Parameters: Positional vs. Keyword
Positional Parameters
Arguments are matched to parameters in the order they’re given.
Example:
def greet(name, age):
print(f"{name} is {age} years old.")
greet("Alice", 25)
Output:
Alice is 25 years old.
Keyword Parameters
Arguments are specified by parameter names, making the order irrelevant.
Example:
greet(age=25, name="Alice")
Output:
Alice is 25 years old.
7. Default Parameters
You can set default values for parameters, which are used if no value is provided.
Example:
def greet(name="Guest"):
print(f"Hello, {name}!")
Calling the Function:
greet() # Uses the default value
greet("Charlie") # Overrides the default value
Output:
Hello, Guest!
Hello, Charlie!
8. Fun Challenge
Write a function to calculate the square of a number:
def square(num):
return num * num
Calling the Function:
print(square(4)) # Output: 16
print(square(7)) # Output: 49
9. Real-World Example
Here’s a real-world example of a function to calculate the area of a rectangle:
Example:
def calculate_area(length, width):
return length * width
Calling the Function:
area = calculate_area(5, 10)
print(f"The area is: {area}")
Output:
The area is: 50
Key Takeaways
- Functions save time and effort by reusing code.
- Use parameters to make functions flexible.
- Use return to send results back to the caller.
- Default parameters and keyword arguments add versatility to functions.
Functions are essential for any programming language. Start practicing with small tasks, and soon you'll find them indispensable!
Next Topic : Lists in Python