Introduction to Conditional Statements
Conditional statements allow us to execute different blocks of code based on certain conditions. In Python, the primary conditional statements are:
1. if statement
2. elif statement
3. else statement
These statements work together to check for conditions and execute code accordingly.
👍1
The if Statement
Syntax
Example
The if statement is used to test a condition. If the condition is True, the block of code under the if statement is executed. Otherwise, the block of code is skipped.
Syntax
if condition:
# Code to execute if condition is True
Example
age = 18
if age >= 18:
print("You are eligible to vote.")
The else Statement
Syntax
Example
The else statement is used to execute a block of code if the if condition is False.
Syntax
if condition:
# Code to execute if condition is True
else:
# Code to execute if condition is False
Example
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
The elif Statement
Syntax
Example
The elif (short for "else if") statement allows you to check multiple conditions. If the first if condition is False, it checks the elif condition. If the elif condition is True, the code block under elif is executed. You can have multiple elif statements.
Syntax
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition2 is True
else:
# Code to execute if all conditions are False
Example
marks = 75
if marks >= 90:
print("Grade: A")
elif marks >= 80:
print("Grade: B")
elif marks >= 70:
print("Grade: C")
else:
print("Grade: D")
Nested if Statements
Syntax
Example
You can have if statements inside other if statements. This is called nesting. Nested if statements are useful when you need to check multiple conditions at different levels
Syntax
if condition1:
# Code to execute if condition1 is True
if condition2:
# Code to execute if condition2 is True
else:
# Code to execute if condition2 is False
else:
# Code to execute if condition1 is False
Example
number = 15
if number > 10:
print("Number is greater than 10.")
if number % 2 == 0:
print("Number is even.")
else:
print("Number is odd.")
else:
print("Number is 10 or less.")
Combining Conditions with Logical Operators
Example
You can combine multiple conditions using logical operators like and, or, and not to form complex conditions.
- and Operator: Returns True if both conditions are True.
- or Operator: Returns True if at least one of the conditions is True.
- not Operator: Reverses the result of the condition.
Example
age = 20
has_voter_id = True
if age >= 18 and has_voter_id:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
Conditional Expressions (Ternary Operator)
Syntax
Example
Python supports a shorter syntax for writing if...else statements using conditional expressions, also known as the ternary operator.
Syntax
value_if_true if condition else value_if_false
Example
age = 18
status = "Eligible" if age >= 18 else "Not eligible"
print(status) # Output: Eligible
Practice Exercises for Day 4
Exercise 1: Voting Eligibility
Exercise 2: Grading System
Exercise 3: Leap Year Checker
Exercise 4: Odd or Even
Exercise 5: Calculator Using if-elif-else
Exercise 1: Voting Eligibility
Write a Python program that takes the age of a person as input and checks whether the person is eligible to vote or not. (Age should be 18 or above to be eligible.)
Exercise 2: Grading System
Write a Python program that takes the marks of a student as input and prints the grade based on the following criteria:
Marks >= 90: Grade A
Marks >= 80: Grade B
Marks >= 70: Grade C
Marks >= 60: Grade D
Marks < 60: Grade F
Exercise 3: Leap Year Checker
Write a Python program to check if a given year is a leap year or not. A leap year is exactly divisible by 4, except for years that are exactly divisible by 100. However, years divisible by 400 are leap years.
Exercise 4: Odd or Even
Write a Python program that takes a number as input and checks whether the number is odd or even.
Exercise 5: Calculator Using if-elif-else
Create a simple calculator that takes two numbers and an operator (+, -, *, /) as input and performs the corresponding operation using if-elif-else statements.
👍1
Homework for Day 4
BMI Calculator:
Number Classification:
Password Strength Checker:
Nested if Example:
BMI Calculator:
Write a Python program that takes the weight (in kg) and height (in meters) of a person as input and calculates their Body Mass Index (BMI). The program should then categorize the BMI as:
BMI < 18.5: Underweight
18.5 <= BMI < 24.9: Normal weight
25 <= BMI < 29.9: Overweight
BMI >= 30: Obesity
Number Classification:
Write a Python program that takes an integer as input and checks if it is positive, negative, or zero
Password Strength Checker:
Create a Python program that takes a password as input and checks its strength based on the following criteria:
At least 8 characters long
Contains both uppercase and lowercase characters
Contains at least one digit
Contains at least one special character (e.g., @, #, !)
Nested if Example:
Write a Python program that takes a person's age and income as input and prints whether the person has to pay taxes. The tax rules are:
If the age is less than 18, they do not need to pay taxes.
If the age is between 18 and 60, they need to pay taxes if their income is more than 5 lakh.
If the age is above 60, they need to pay taxes if their income is more than 3 lakh.
👍3
Summary
Today, we covered conditional statements in Python, which are crucial for controlling the flow of a program. We learned about:
if, elif, and else statements: Used for decision-making in Python.
Nested if statements: Allow for more complex decision-making processes.
Combining conditions using logical operators (and, or, not) to create complex expressions.
Conditional expressions (ternary operators): A concise way to write if...else statements.
Understanding and mastering these concepts will help you write programs that can make decisions based on user input or other factors, making your code more dynamic and responsive.
Today, we covered conditional statements in Python, which are crucial for controlling the flow of a program. We learned about:
if, elif, and else statements: Used for decision-making in Python.
Nested if statements: Allow for more complex decision-making processes.
Combining conditions using logical operators (and, or, not) to create complex expressions.
Conditional expressions (ternary operators): A concise way to write if...else statements.
Understanding and mastering these concepts will help you write programs that can make decisions based on user input or other factors, making your code more dynamic and responsive.
👍4
Which keyword is used to check a condition in Python?
Anonymous Quiz
8%
for
77%
if
8%
while
6%
switch
Which of the following operators can be used to combine multiple conditions in Python?
Anonymous Quiz
31%
&& and ||
26%
AND and OR
40%
and and or
2%
AND and ||
Introduction to Loops
Loops allow you to execute a block of code multiple times. Python provides two types of loops:
while loopfor loopBoth loops are used to perform repetitive tasks but have different use cases and syntax.
👍2
The while Loop
Syntax
Example
In this example, the loop runs until the value of
The while loop executes a block of code as long as the given condition is True. It is primarily used when the number of iterations is not known beforehand.
Syntax
while condition:
# Code to execute repeatedly as long as the condition is True
Example
count = 0
while count < 5:
print("Count is:", count)
count += 1 # Increment count by 1
In this example, the loop runs until the value of
count becomes 5. The count += 1 statement increments the value of count by 1 in each iteration.Infinite while Loop
Example of an Infinite Loop:
You can stop an infinite loop by using
A while loop can become an infinite loop if the condition never becomes False. You need to be careful to include a condition that will eventually break the loop.
Example of an Infinite Loop:
while True:
print("This will run forever if not stopped!")
You can stop an infinite loop by using
break or by manually interrupting the program (e.g., pressing Ctrl + C).The for Loop
Syntax
Example
Here, the
The for loop is used to iterate over a sequence (like a list, tuple, string, or range). It is most commonly used when the number of iterations is known beforehand.
Syntax
for variable in sequence:
# Code to execute for each element in the sequence
Example
for i in range(5):
print("Value of i:", i)
Here, the
range(5) function generates a sequence of numbers from 0 to 4, and the loop runs 5 times.The
The range() function is widely used in
Example:
range() FunctionThe range() function is widely used in
for loops to generate a sequence of numbers. It has three parameters:range(stop) - Generates numbers from 0 to stop - 1.range(start, stop) - Generates numbers from start to stop - 1.range(start, stop, step) - Generates numbers from start to stop - 1 with a step size of step.Example:
print(list(range(5))) # Output: [0, 1, 2, 3, 4]
print(list(range(2, 7))) # Output: [2, 3, 4, 5, 6]
print(list(range(1, 10, 2))) # Output: [1, 3, 5, 7, 9]
Nested Loops
Example:
Output:
A loop inside another loop is called a nested loop. The inner loop runs completely whenever the outer loop runs once.
Example:
for i in range(1, 4):
for j in range(1, 4):
print(f"i={i}, j={j}")
Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
...
Loop Control Statements
Python provides loop control statements to change the execution flow of loops:
Python provides loop control statements to change the execution flow of loops:
break statement: Terminates the loop prematurely.continue statement: Skips the current iteration and continues with the next iteration.pass statement: Does nothing and can be used as a placeholder.break Example:for i in range(5):
if i == 3:
break
print(i)
# Output: 0 1 2
continue Example:for i in range(5):
if i == 3:
continue
print(i)
# Output: 0 1 2 4
pass Example: for i in range(5):
if i == 3:
pass # Placeholder, does nothing
print(i)
# Output: 0 1 2 3 4
Using
In Python, you can use an
Example with
Example with
else with LoopsIn Python, you can use an
else block with both while and for loops. The else block is executed when the loop terminates normally (i.e., not terminated by a break statement).Example with
for loop: for i in range(5):
print(i)
else:
print("Loop completed successfully.")
Example with
while loop:count = 0
while count < 5:
print(count)
count += 1
else:
print("Loop completed successfully.")