UNIT 2
Control Statements
Control statements are statements which control or change the flow of execution.
They are used to control the order of execution of the program based on the values and logic.
Python support the following control statements.
• if statement
• if…..else statement
• if….elif….else statement
• while loop
• for loop
• break statement
• continue statement
• pass statement
• return statement
The if statement
The “if statement” is used to test a particular condition and if the condition is true, it executes a block of code known
as if-block. The condition of “if statement” can be any valid logical expression which can be either evaluated to true
or false.
The syntax of the if-statement is CODE
given below. 1. num = int(input("enter the number?"))
if(expressions): 2. if (num%2 == 0):
---- statement1 3. print("Number is even")
---- statement2
. OUTPUT:
. enter the number?10
---- statementn Number is even
4.
Example 1: Program to check the even number
Example 2 : Program to print the largest of the three numbers.
CODE OUTPUT
1. a = int(input("Enter a? ")); enter the number?10
2. b = int(input("Enter b? ")); Number is even
3. c = int(input("Enter c? ")); Enter a? 100
4. if a>b and a>c: Enter b? 120
5. print("a is largest"); Enter c? 130
6. if b>a and b>c: c is largest
7. print("b is largest");
8. if c>a and c>b:
9. print("c is largest");
The if-else statement
The “if-else” statement provides an else block combined with the “if statement” which is executed in the false case
of the condition.
If the condition is true, then the “if-block” is executed. Otherwise, the else-block is executed.
The syntax of the if-else statement is given below.
1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)
Example: Program to check whether a number is even or not.
CODE OUTPUT
1. num = int(input("enter the number?")) enter the number?10
2. if num%2 == 0: Number is even
3. print("Number is even...")
4. else:
5. print("Number is odd...")
The elif statement
The “elif” statement enables us to check multiple conditions and execute the specific block of statements depending
upon the true condition among them. We can have any number of “elif” statements in our program depending upon
our need. However, using elif is optional.
The “elif” statement works like an if-else-if ladder statement in C. It must be succeeded by an “if statement”.
The syntax of the “elif” statement is given below.
1. if expression 1:
2. ….# block of statements
3. elif expression 2:
4. ….# block of statements
elif expression 3:
5. ….# block of statements
else:
….# block of statements
Note that the “else” block is optional
Example: Program to find the grade of students.
CODE OUTPUT
1. marks = int(input("Enter the marks? ")) Enter the marks?90
2. if marks > 85 and marks <= 100: Congrats! you scored grade A
3. print("Congrats ! you scored grade A.")
4. elif marks > 60 and marks <= 85: Enter the marks?60
5. print("You scored grade B + ...") You scored grade B…
6. elif marks > 40 and marks <= 60:
7. print("You scored grade B ...")
8. elif (marks > 30 and marks <= 40):
9. print("You scored grade C ...")
else:
print("Sorry you are fail ?")
Nested if statements
Python Nested If Statement means to place one If Statement inside another If Statement. Python If Else statement
allows us to print different statements depending upon the expression result (TRUE, FALSE). Sometimes we have to
check further even when the condition is TRUE. In these situations, we can use the Python Nested IF statements, but
be careful while using it.
The syntax of the “Nested if” statement is given below.
if (expression1):
if (expression2):
# if expression 1 and expression 2 both are evaluated to True
# Block of statement
else:
# if expression 1 is True and expression 2 is False
# Block of statement
else:
# if expression 1 is False
# Block of statement
Following is an example to show the nested if construct, where we input a number to check if the number is positive
or negative or zero and display an appropriate message
CODE OUTPUT
num=float(input("Enter a number: ")) Enter a number:5
if num>= 0: Positive Number
if num == 0:
print("Zero") Enter the marks?-60
else: Negative Number
print("Positive Number")
else:
print("Negative Number")
Functions in Python
A function in Python is a reusable block of code designed to perform a specific task. Functions help in
organizing code and make it easier to debug, maintain, and scale.
Why Use Functions?
• Reusability: Functions allow code to be used multiple times.
• Modularity: They break large programs into smaller, manageable parts.
• Readability: Well-written functions make code easier to understand.
• Maintainability: Makes it easier to update or change the logic without affecting the entire program.
Syntax of a Function in Python
def <function_name>(<parameters>):
"""
Optional: Function Docstring
"""
# Function body
return value #optional
def: Keyword used to define a function.
function_name: Name of the function. Should be descriptive of what the function does.
parameters: Optional inputs to the function.
return: Optional; the value the function sends back after execution.
Example of a Simple Function
def greet(name):
"""This function greets a person."""
return f"Hello, {name}!"
# Function call
print(greet("Atebar"))
Output:
Hello, Atebar!
Types of Functions
Built-in Functions
Python provides many built-in functions, such as print(), len(), max(), etc.
User-Defined Functions
These are functions defined by the user. Example:
def add_numbers(a, b):
return a + b
print(add_numbers(5, 3)) # Output: 8
Parameters and Arguments
• Parameters: Variables listed inside the function definition.
• Arguments: Values passed to the function when it is called.
Types of Arguments in Python Functions:
In Python, there are four types of arguments used in function definitions:
• Positional Arguments
• Keywords Arguments
• Default Arguments
• Variable Length Arguments
Positional Arguments:
These are the most common type of arguments, passed to a function in a specific order.
The position of the arguments matters, and they must be provided in the same order as the function
definition.
Example:
def greet(name, age):
print(f"Hello, my name is {name} and I am {age} years old.")
greet("Alice", 25)
# Output: Hello, my name is Alice and I am 25 years old.
Keyword Arguments:
Keyword arguments are passed to the function with the parameter name, allowing you to specify which
parameter should get which value.
The order of the arguments does not matter when using keyword arguments.
Example:
def greet(name, age):
print(f"Hello, my name is {name} and I am {age} years old.")
greet(name="Bob", age=30)
# Output: Hello, my name is Bob and I am 30 years old.
greet(age=40, name="Charlie")
# Output: Hello, my name is Charlie and I am 40 years old.
Default Arguments:
These are arguments that assume a default value if no value is provided during the function call.
Default arguments must be defined at the end of the function's parameter list.
Example:
def greet(name, age=20):
print(f"Hello, my name is {name} and I am {age} years old.")
greet("David") # Output: Hello, my name is David and I am 20 years old.
greet("Eva", 35) # Output: Hello, my name is Eva and I am 35 years old.
Variable-length arguments:
It allow a function to accept an arbitrary number of arguments. This is useful when you don't know
beforehand how many arguments might be passed to a function. Python provides two ways to handle
variable-length arguments:
1. *args: For non-keyworded, positional arguments.
2. **kwargs: For keyword arguments (key-value pairs).
Let's explore each in detail:
1. *args (Non-keyworded Variable-length Arguments)
• The *args syntax allows a function to accept any number of positional arguments.
• The function receives these arguments as a tuple.
• The name args is a convention, but you can use any name, like *numbers or *items.
How It Works:
When you use *args, Python collects all the extra positional arguments passed to the function and packs them
into a tuple.
Example:
def my_sum(*numbers):
total = sum(numbers)
print(f"Sum: {total}")
my_sum(1, 2, 3) # Output: Sum: 6
my_sum(4, 5, 6, 7) # Output: Sum: 22
In the above example:
• The function my_sum can take any number of positional arguments.
• These arguments are packed into a tuple numbers inside the function.
• You can iterate over the tuple or perform operations like summing.
Use Cases:
• When you need to pass an arbitrary number of inputs to a function (like a list of items or numbers).
• When you don't know the number of inputs in advance.
Example 2 (Working with *args):
def print_friends(*friends):
print("My friends are:")
for friend in friends:
print(friend)
print_friends("Alice", "Bob", "Charlie")
# Output:
# My friends are:
# Alice
# Bob
# Charlie
Here, the function print_friends accepts any number of friends' names and prints them.
**kwargs (Keyword Variable-length Arguments)
• The **kwargs syntax allows a function to accept any number of keyword arguments (key-value pairs).
• The function receives these arguments as a dictionary where keys are argument names, and values are
the argument values.
• The name kwargs is a convention, but you can use any name, like **data.
How It Works:
When you use **kwargs, Python collects all the extra keyword arguments passed to the function and packs
them into a dictionary.
Example:
def print_person_info(**info):
for key, value in [Link]():
print(f"{key}: {value}")
print_person_info(name="Alice", age=25, city="New York")
# Output:
# name: Alice
# age: 25
# city: New York
In the above example:
• The function print_person_info can accept any number of keyword arguments.
• These arguments are packed into a dictionary info.
• The function then iterates over the dictionary and prints each key-value pair.
Use Cases:
• When you want to accept dynamic sets of named arguments.
• When you need to handle optional or named parameters in a function.
•
Example 2 (Working with **kwargs):
def make_profile(**profile):
print("User Profile:")
for key, value in [Link]():
print(f"{key}: {value}")
make_profile(username="Atebar", occupation="Teacher", location="Lucknow")
Output:
User Profile:
username: Atebar
occupation: Teacher
location: Lucknow
Here, the function make_profile accepts multiple keyword arguments, allowing flexibility in the input data.
Combining *args and **kwargs
• You can combine both *args and **kwargs in a single function.
• This allows the function to accept both variable positional arguments and variable keyword arguments.
Example:
def greet_people(greeting, *people, **details):
print(f"{greeting}, {', '.join(people)}!")
if details:
print("Details:")
for key, value in [Link]():
print(f"{key}: {value}")
greet_people("Hello", "Vipin", "Shivam", city="Lucknow", age=30)
Output:
Hello, Vipin, Shivam!
Details:
city: Lucknow
age: 30
In this example:
• greeting is a normal positional argument.
• *people collects all the extra positional arguments (like "Vipin" and "Shivam").
• **details collects any keyword arguments (like city="Lucknow" and age=30).
Rules for Using *args and **kwargs Together:
1. Positional arguments (normal parameters) must come first.
2. *args must come before **kwargs.
3. You can use *args alone, **kwargs alone, or both together, but they must follow the correct order.
Example:
def complex_function(a, b, *args, **kwargs):
print(f"a: {a}, b: {b}")
print(f"args: {args}")
print(f"kwargs: {kwargs}")
complex_function(1, 2, 3, 4, 5, key1="value1", key2="value2")
Output:
a: 1, b: 2
args: (3, 4, 5)
kwargs: {'key1': 'value1', 'key2': 'value2'}
Here:
• a and b are normal positional arguments.
• *args collects additional positional arguments (3, 4, 5).
• **kwargs collects keyword arguments {'key1': 'value1', 'key2': 'value2'}.