In this tutorial, we are going to learn about Python if
and else
statements, which allow you to execute a block of code only if a certain condition is true, or to execute one block of code if the condition is true and another block of code if the condition is false.
We also learn how to use elif
to include additional conditions in our code. By the end of the tutorial, you should have a good understanding of how to use if
and else
statements in Python, and be able to apply them in your own programs.
if and else conditions
In Python, if
and else
statements are used to execute a block of code only if a certain condition is true or to execute one block of code if the condition is true and another block of code if the condition is false.
Here is the general syntax for a if
statement:
if condition:
# code to be executed if condition is true
To include an else
statement, you can use the following syntax:
if condition:
# code to be executed if condition is true
else:
# code to be executed if condition is false
You can also use elif
(short for “else if”) to include additional conditions:
if condition1:
# code to be executed if condition1 is true
elif condition2:
# code to be executed if condition1 is false and condition2 is true
else:
# code to be executed if condition1 and condition2 are both false
Example one:
Here are some examples to illustrate the usage of if
and else
statements:
x = 5
if x > 0:
print("x is positive")
else:
print("x is not positive")
This code will output "x is positive"
, because the condition x > 0
is true.
Example two:
y = 10
if y % 2 == 0:
print("y is even")
else:
print("y is odd")
This code will output "y is even"
, because the condition y % 2 == 0
is true (y
is evenly divisible by 2).
Example three:
z = 7
if z > 0:
print("z is positive")
elif z == 0:
print("z is zero")
else:
print("z is negative")
This code will output "z is positive"
, because the condition z > 0
is true. If z
were equal to 0, the code would output "z is zero"
. Otherwise, if z
were negative, the code would output "z is negative"
.
- pybase64 encode and decode Messages using Python - June 6, 2023
- Different Data Types in Dart - June 6, 2023
- What is flutter and dart and the difference - June 4, 2023