Conditional Statements In Python :
if statement :
An if statement in python is used to run a block of code only when a specific condition is true. if the condition is true then the block of code will execute, if it is false it is not executed will skip to another step.
syntax : if condition :
# block code run when the condition is true
example :
x = 10
if x > 5:
print("x is greater than 5")
output :
x is greater than 5
executes the block only if the condition is True.
- if...else statement
an if else statement is a condition in python that means one block of code run if the condition is true and the other block of code run if the code is false.
syntax :
if condition:
#code run if it is true
else:
#code run if condition is false
example :
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is 5 or less")
output :
x is 5 or less
Runs one block if True, another if False
code :
product = 2
if product<=0:
print("Out of Stock")
else:
print("Add to Cart")
Output :
Out of Stock
- if..elif..else statement
an if elseif else statement is a condition in python that means one block of code run if the condition is true and the other condition adding at the else block that is else if , if the condition is true the second block code run otherwise else block code will run. we see in below example
example :
x = 5
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is a equal to 5")
else:
print("x is less than 5")
output :
x is a equal to 5
- nested if statements
A nested if statements is when you place one if statement inside another. This allows you to check a second condition only if the first one is true
syntax :
if condition 1:
if condition 2:
#code runs only if both condition 1 and condition 2 are True
example :
x = 10
if x > 5:
if x < 15:
print("x is between 5 and 15")
output :
x is between 5 and 15
- ternary conditional (One linear if else )
a ternary conditional operator in python is a shorthand way to write an if else statements in one line
its mostly used when you need to assign a value based on a condition
syntax : <value_if_true> if <condition> else <value_if_false>
example 1 :
x = 10
result = "Even" if x % 2 == 0 else "Odd"
print(result)
output : Even
example 2 : age checker
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
output : Adult
- You have to must try in your python compiler use idle avoid online compilers to Errors
0 Comments