EN
Python - if statement
0 points
In this article, we would like to show you if statement example in Python.
Quick solution:
xxxxxxxxxx
1
x = -1
2
3
if x > 0:
4
print("x > 0")
5
elif x == 0:
6
print("x = 0")
7
else:
8
print("x < 0")
In this example, we create a simple if
statement that checks if the number we specified is greater than 0
.
xxxxxxxxxx
1
x = 1
2
3
if x > 0:
4
print("x > 0")
Output:
xxxxxxxxxx
1
x > 0
In this example, we add elif
keyword that checks the next condition if the previous conditions were not true.
xxxxxxxxxx
1
x = 0
2
3
if x > 0:
4
print("x > 0")
5
elif x <= 0:
6
print("x <= 0")
Output:
xxxxxxxxxx
1
x <= 0
In this example, we add the else
condition that catches anything which isn't caught by the previous conditions
xxxxxxxxxx
1
x = -1
2
3
if x > 0:
4
print("x > 0")
5
elif x == 0:
6
print("x = 0")
7
else:
8
print("x < 0")
Output:
xxxxxxxxxx
1
x < 0
You can use operators such as and
& or
to combine conditions inside if
statement.
xxxxxxxxxx
1
x = 1
2
y = 2
3
4
if x > 0 and y > 0:
5
print("Both x and y are positive numbers.")
Output:
xxxxxxxxxx
1
Both x and y are positive numbers.
xxxxxxxxxx
1
x = 1
2
y = -5
3
4
if x < 0 or y < 0:
5
print("One of the numbers is negative.")
Output:
xxxxxxxxxx
1
One of the numbers is negative.