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

Python Day 2

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Python Day 2

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Python

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 age >= 18:

print("You are an adult.")

if-else Statement

The if-else statement provides an alternative block of code to execute if the condition is false.
python

age = 17

if age >= 18:

print("You are an adult.")

else:

print("You are a minor.")

if-elif-else Statement

The if-elif-else statement allows for multiple conditions to be checked in sequence.

python

score = 85

if score >= 90:

print("Grade: A")

elif score >= 80:

print("Grade: B")

elif score >= 70:

print("Grade: C")

else:

print("Grade: F")

Loops

Loops are used to execute a block of code repeatedly.


for Loop

The for loop iterates over a sequence (such as a list, tuple, or string) and executes a block of
code for each element.

python

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:

print(fruit)

while Loop

The while loop executes a block of code as long as a condition is true.

python

count = 0

while count < 5:

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

Functions are called by using their name followed by parentheses ().

python

greet()

Function Arguments

Functions can accept arguments (parameters) to make them more flexible.

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

Functions can return values using the return statement.

python

def add(a, b):

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]

squared = list(map(lambda x: x 2, numbers))

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

Here are some questions related to the notes on Python

Topic 3: Control Structures - Questions

1. Conditional Statements

a. Write a Python program to check if a given number is positive, negative, or zero.


b. Write a Python program to determine if a person is eligible to vote based on their age.

c. Write a Python program that assigns grades to a student based on their score (use if-elif-
else statements for different ranges).

d. Modify the following code to add an `else` block:

```python

temperature = 25

if temperature > 30:

print("It's hot outside.")

```

e. What will be the output of the following code?

```python

num = 10

if num % 2 == 0:

print("Even")

else:

print("Odd")

```

2. Loops

a. Write a Python program to print numbers from 1 to 10 using a `for` loop.


b. Write a Python program to print all the elements of a list using a `for` loop.

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.

e. What will be the output of the following code?

```python

for i in range(5):

if i == 3:

break

print(i)

```

3. Break and Continue

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.

c. Explain what the `break` and `continue` statements do in loops.

Topic 4: Functions - Questions


1. Defining Functions

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

1. Explain the purpose of control structures in programming.

2. What are the different types of conditional statements in Python? Give examples.

3. How does a `for` loop differ from a `while` loop?

4. Describe how the `break` and `continue` statements alter the flow of a loop.

5. What are functions in Python and why are they used?

6. How can default arguments be useful in function definitions? Provide an example.

7. Explain the concept of lambda functions and provide a scenario where they are useful.

You might also like