Python - If Condition
In Python, the if statement is used for conditional branching. It is used to execute a block of code only when a particular condition is true. If the condition is false, then the code block is not executed. The syntax of the if statement is:
if condition:
# code block
The condition is a Boolean expression that evaluates to either True or False. If the condition is true, then the code block following the if statement will be executed, and if the condition is false, then the code block is skipped.
Example 1: Checking if a number is positive, negative, or zero
num = (input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Example 2: Checking if a string is empty or not
string = input("Enter a string: ")
if string:
print("String is not empty")
else:
print("String is empty")
Example 3: Checking if a number is even or odd
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
Example 4: Checking if a number is a multiple of 3 and 5
num = int(input("Enter a number: "))
if num % 3 == 0 and num % 5 == 0:
print("Number is a multiple of 3 and 5")
else:
print("Number is not a multiple of 3 and 5")
Example 5: Checking if a number is within a certain range
num = int(input("Enter a number: "))
if num in range(1, 11):
print("Number is within the range of 1 and 10")
else:
print("Number is not within the range of 1 and 10")