Python Conditional statement
The If statement is the most fundamental decision-making statement, in which the code is executed based on whether it meets the specified condition. It has a code body that only executes if the condition in the if statement is true. The statement can be a single line or a block of code.
The if statement in Python has the subsequent syntax:
if expression Statement
num = 5 if num > 0: print(num, "is a positive number.") print("This statement is true.") #When we run the program, the output will be: 5 is a positive number. This statement is true.
If and else Statement
num = 5 if num >= 0: print("Positive or Zero") else: print("Negative number") output : Positive or Zero
If , elif and else condition
num = 7 if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number") output: Positive number
Nested If Statement
A Nested IF statement is one in which an If statement is nestled inside another If statement. This is used when a variable must be processed more than once. If, If-else, and If…elif…else statements can be used in the program. In Nested If statements, the indentation (whitespace at the beginning) to determine the scope of each statement should take precedence.
The Nested if statement in Python has the following syntax:
price=100 quantity=10 amount = price*quantity if amount > 200: if amount >1000: print("The amount is greater than 1000") else: if amount 800: print("The amount is between 800 and 1000") elif amount 600: print("The amount is between 600 and 1000") else: print("The amount is between 400 and 1000") elif amount == 200: print("Amount is 200") else: print("Amount is less than 200") The output : “The amount is between 400 and 1000.”
Leave a Comment