my_var = 20
# Check if 'my_var' is 20, else print something else,
# Notice the indentations
if my_var == 20:
print("Yes its 20")
else:
print("Its something else") # Its something else
my_var = 30
# same example with different value
if my_var == 20:
print("Yes its 20")
elif my_var == 30:
print("Yes its 30") # Yes its 30
elif my_var == 40:
print("Yes its 40")
else:
print("Ah, its something else")
my_value = 18
# Notice the indentations here
if my_value > 10:
if my_value < 20:
print("my_value is between 10 and 20") # my_value is \
# between 10 and 20
else:
print("my_value is greater than 20")
else:
print("my_value is smaller than 10")
## Ternary Operator: SYNTAX => [on_true] if [expression] else [on_false]
my_var = "Yes" if 20 % 2 == 0 else "No"
# here 'Yes' is the output when 'if' condition is satisfied,
# else 'No' is the output
print(my_var) # "Yes"
# Can also try nesting if..else conditions
a, b = 10, 20
my_var = None if not (a and b) else (b / a if b > a else a / b)
print(my_var) # 2.0
# which is similar to this
if not (a and b):
my_var = None
else:
if b > a:
my_var = b / a
else:
my_var = a / b
print(my_var) # 2.0
# Truthy(True values): non-zero numbers(including negative numbers),
# True, Non-empty sequences
# Falsy(False values): 0, 0.0, 0j, None, False,
# [], {}, (), "", range(0)
my_var = 10
my_var1 = None
## Some Examples
# 'my_var' is a non-zero number, which is Truthy, so 'if' is 'True'
if my_var:
print("printed") # printed
# 'my_var1' is 'None', which is Falsy, so 'if' will not execute
if my_var1:
print("not printed")
# Check for empty tuple
if ():
print("not printed")
# Check for non-empty list
if [23, 45, 34]:
print("printed") # printed
# By default user-defined object is also Truthy,
# you can manipulate using '__bool__()' special method
# you can also use 'bool()' built-in function to check the Truth value
print(bool(42)) # True
print(bool("This?")) # True
print(bool("")) # False
print(bool(None)) # False
# Explore the rest!