Python - If...Else

01-Feb-2024

Understand the basics of conditional statements in Python. Learn how to use if and else statements to control the flow of your program based on specific conditions.

Introduction


Python's if-else statement is a flexible tool for deciding what to do in your code. The if-else statement is covered in this documentation in both its standard and simplified forms, with examples involving logical operators.



Standard Form

Syntax :


 
# Standard if...else Syntax
if condition :
# code to executed if the condition is True else :
# code to executed if the condition is False

Example :


x = 10
if x > 0: print('Positive Number') # This will execute else:
print('Negatice Number')



Multiple Conditions and Logical Operators

Logical operators (and, or) can be used to combine conditions. Here's an example checking if a number is both positive and even:


Syntax :


# Syntax for Multiple Conditions and Logical Operators

if condition1 and condition2 :
# code to executed if both conditions are True elif condition3 or condition4 :
# code to executed if either condition3 or condition4 is True else :
# code to executed if none of the conditions are True

Example :


x = 10
y = 5

if x > 0 and y > 0: print('Both numbers are positive.') # This will execute elif x < 0 or y < 0: print('At least one number is negative.') else:
print('Both numbers are non-negative.')



Shorthand Form

You can place a single statement on the same line as the if statement if that's all you have to do.

Syntax :



# Shorthand if-Else (Ternary Operator) Syntax
result = true_value if condition false_value

Example :


x = 10

result = 'Even' if x % 2==0 else 'Odd' # This will set 'result' to 'Even'
print(result)


Conclusion

The if-else statement is still an effective tool for managing the flow of your Python scripts, even when you use the standard or shorter version and include logical operators. Try these out to develop a better knowledge of how to use these constructs in practical ways.


Comments