Conditional Statements and Loops in Python
Conditional Statements
Conditional statements are used to perform different actions based on different conditions.
1. if statement:
Syntax:
if condition:
# code to execute if condition is true
Example:
x = 10
if x > 5:
print("x is greater than 5")
2. if-else statement:
Syntax:
if condition:
# code if condition is true
else:
# code if condition is false
Example:
x=3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
3. if-elif-else statement:
Syntax:
if condition1:
# code if condition1 is true
elif condition2:
# code if condition2 is true
else:
# code if none of the above conditions are true
Example:
x=7
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but less than or equal to 10")
else:
print("x is 5 or less")
Logical Operators:
- and: Returns True if both statements are true
- or: Returns True if one of the statements is true
- not: Reverses the result
Example:
x = 10
y=5
if x > 5 and y < 10:
print("Both conditions are true")
Loops
Loops are used to execute a block of code repeatedly.
1. for loop:
Syntax:
for variable in iterable:
# code to execute
Example:
for i in range(5):
print(i)
2. while loop:
Syntax:
while condition:
# code to execute
Example:
x=0
while x < 5:
print(x)
x += 1
Practice Questions
Conditional Statements (10 Questions)
1. Write a program to check if a number is positive.
2. Write a program to check if a number is even or odd.
3. Write a program to find the largest of two numbers.
4. Write a program to check if a number is divisible by 5 and 10.
5. Write a program to check if a year is a leap year.
6. Write a program to check if a character is a vowel.
7. Write a program to assign grades based on marks.
8. Write a program to check if a number is in a given range.
9. Write a program to check if a string is empty.
10. Write a program to check if a number is a multiple of 3 or 7.
Loops (10 Questions)
1. Write a program to print numbers from 1 to 10 using a for loop.
2. Write a program to print even numbers from 1 to 20.
3. Write a program to print the multiplication table of a number.
4. Write a program to find the sum of numbers from 1 to 100.
5. Write a program to print the factorial of a number.
6. Write a program to print the Fibonacci series up to n terms.
7. Write a program to reverse a number using a while loop.
8. Write a program to count the number of digits in a number.
9. Write a program to print all characters in a string using a for loop.
10. Write a program to find the largest number in a list using a loop.