Python Conditional Statements
Conditional Statements
In Python, conditional statements allow you to execute specific code based on whether a certain condition is true or false. The most common conditional statements in Python are if
, if-else
, if-elif-else
, and the ternary operator. Here is an explanation of each of these:
if
statement: This statement is used to execute a block of code only if a condition is true. The syntax for an if
statement is as follows:
Python Code:
x = 10
if x > 5:
print(“x is greater than 5”)
a = 10 if a == 10 : print("Hi")
if-else
statement: This statement is used to execute one block of code if a condition is true, and another block of code if the state is false. The syntax for an if-else
statement is as follows:
Python Code:
a = 10 if a == 11: print("Hi") else: print("Bye")![]()
if-elif-else
statement: This statement is used to execute different blocks of code based on multiple conditions. The syntax for anif-elif-else
statement is as follows:
Python Code: a = 8 if a < 5: print(1) elif a == 10: print(2) elif a > 7: print(3) else: print(4) Python Code:
x = 3
if x > 5:
print(“x is greater than 5”)
elif x > 0:
print(“x is greater than 0 but less than or equal to 5”)
else:
print(“x is less than or equal to 0”)
Nested if else:
Python Code:
a = 5 if a == 5: print(1) if a > 3: print(2) else: print(3) elif a == 7: print(4) if a > 5: print(5) else: print("Finish")
Ternary operator: This is a shorthand way of writing an if-else
statement. The syntax for a ternary operator is as follows:
Python Code:
a = 5 b = 10 if a > 2 else 45 print(b) Python Code:
x = 3
print(“x is greater than 5” if x > 5 else “x is less than or equal to 5”)
Questions
- WAP to enter a number from the user and check if it is even or odd
if n%2 == 0:
print("Even")
else:
print("Odd")
- WAP to enter a number from the user and print its character format.
1 -> “One”
2 -> “Two”
n = int(input("Enter a number: ")) if n == 1: print("One") elif n == 2: print("Two") elif n == 0: print("Zero") else: print("Invalid Input")
- WAP to enter a number from the user and print its absolute value
n = int(input("Enter a number: ")) if n < 0: print(n * (-1) ) else: print(n)
- WAP to enter a character from the user and check if it is a vowel or consonant
- WAP to enter a character from the user and check if it is a vowel or consonant
- WAP to enter length and width and check it it is a square or rectangle
a = int(input("Enter length: "))
b = int(input("Enter width: "))
if a == b:
print("Square")
else:
print("Rectangle")
Leave a Reply