Python Day 2
Python Day 2
Notes
Topic 3: Control Structures
Control structures in Python are used to control the flow of execution in a program. These
structures include conditional statements and loops.
Conditional Statements
if Statement
The if statement evaluates a condition and executes a block of code if the condition is true.
python
age = 18
if-else Statement
The if-else statement provides an alternative block of code to execute if the condition is false.
python
age = 17
else:
if-elif-else Statement
python
score = 85
print("Grade: A")
print("Grade: B")
print("Grade: C")
else:
print("Grade: F")
Loops
The for loop iterates over a sequence (such as a list, tuple, or string) and executes a block of
code for each element.
python
print(fruit)
while Loop
python
count = 0
print(count)
count += 1
break Statement
The break statement is used to exit a loop prematurely when a certain condition is met.
python
for i in range(10):
if i == 5:
break
print(i)
continue Statement
The continue statement skips the current iteration of a loop and proceeds to the next iteration.
python
for i in range(10):
if i % 2 == 0:
continue
print(i)
Topic 4: Functions
Functions in Python are reusable blocks of code designed to perform a specific task. They
help in organizing code and avoiding redundancy.
Defining Functions
Functions are defined using the def keyword followed by the function name and parentheses
().
python
def greet():
print("Hello, world!")
Calling Functions
python
greet()
Function Arguments
python
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Default Arguments
Functions can have default argument values which are used if no argument is provided.
python
def greet(name="Guest"):
print(f"Hello, {name}!")
greet()
greet("Bob")
Return Values
python
return a + b
result = add(3, 5)
print(result)
Lambda Functions
Lambda functions are small anonymous functions defined using the lambda keyword. They
are often used for short, throwaway functions.
python
add = lambda x, y: x + y
print(add(2, 3))
Lambda functions can also be used as arguments to higher-order functions like map(), filter(),
and sorted().
python
numbers = [1, 2, 3, 4, 5]
print(squared)
Summary
- Conditional Statements: Control the flow of execution based on conditions (if, if-else, if-elif-
else).
- Loops: Repeat a block of code (for, while), can be controlled using break and continue.
- Functions: Reusable blocks of code defined with def, can accept arguments and return
values. Lambda functions offer a compact way to define simple functions.
Task 3
1. Conditional Statements
c. Write a Python program that assigns grades to a student based on their score (use if-elif-
else statements for different ranges).
```python
temperature = 25
```
```python
num = 10
if num % 2 == 0:
print("Even")
else:
print("Odd")
```
2. Loops
c. Write a Python program to calculate the sum of all numbers from 1 to 100 using a `while`
loop.
d. Write a Python program that prints the numbers from 1 to 10 but skips the number 5
using a `for` loop and `continue` statement.
```python
for i in range(5):
if i == 3:
break
print(i)
```
a. Write a Python program to find the first occurrence of the number 7 in a list and break the
loop once it's found.
b. Write a Python program to print all numbers from 1 to 10, but skip numbers that are
divisible by 3 using the `continue` statement.
a. Write a function `greet` that prints "Hello, world!" and call it.
b. Define a function `add` that takes two numbers as parameters and returns their sum. Call
the function with different sets of numbers.
c. Define a function `is_even` that takes a number as a parameter and returns `True` if the
number is even and `False` otherwise. Test the function with different numbers.
2. Function Arguments
a. Write a function `greet_person` that takes a person's name as an argument and prints
"Hello, [name]!".
b. Define a function `calculate_area` that takes the radius of a circle as an argument and
returns the area. Use the formula `area = π r^2`.
c. Write a function `introduce` that has a default argument for the person's name as "Guest"
and prints "Hello, [name]!". Call the function with and without passing an argument.
3. Return Values
a. Write a function `square` that takes a number as an argument and returns its square.
b. Define a function `max_of_two` that takes two numbers as arguments and returns the
larger number.
c. Write a function `is_palindrome` that takes a string as an argument and returns `True` if
the string is a palindrome and `False` otherwise. Test the function with different strings.
4. Lambda Functions
a. Write a lambda function that adds two numbers and call it with different sets of numbers.
b. Use a lambda function with the `map` function to square each element in a list of
numbers.
c. Write a lambda function that checks if a number is even and use it with the `filter` function
to filter out odd numbers from a list.
Summary Questions
2. What are the different types of conditional statements in Python? Give examples.
4. Describe how the `break` and `continue` statements alter the flow of a loop.
7. Explain the concept of lambda functions and provide a scenario where they are useful.