Thứ Tư, Tháng Hai 12, 2025
spot_img
HomeIf, if...else, if...elif...else statements in Python

If, if…else, if…elif…else statements in Python

If statement in Python How is it used? When to use if else in Python? Let's find out with Quantrimang.com!

Making decisions is the most important task in most programming languages. As the name suggests, decision making allows the programmer to run a specific block of code. Here, decisions are made based on the validity of each specific condition. Condition checking is the “core” of making accurate decisions.

In Python, decision making is done by the following commands:

  • The if statement is used to test a specific condition. If the condition is true, the code block (if-block) will be executed.
  • The if-else statement is similar to the if statement except for the fact that it also provides the code block for the false case of the condition being tested. If the condition provided in the if statement is false, the else statement will run.
  • Nested if statements allow users to use commands if ? else. else inside the outer if statement.

Now let's learn more about the if else structure in Python and other if statements in more detail.

If statement structure in Python

Conditions in Python and IF statements

Python supports common logical conditions from mathematics:

  • Equals: a == b
  • Not equal to: a != b
  • Smaller: a
  • Less than or equal to: a
  • Greater than: a > b
  • Greater than or equal to: a >= b

The above conditions can be used in many ways, most commonly in “if statements” and loops.

The if statement is written using keywords if.

if dieu_kien
    Khối lệnh

Here, the program reviews conditions and will carry out the command When conditions is True. If conditions False then command will not be performed.

In Python, the command block of a command if written indented. Command block of if starts with an indent and the first unindented line will be interpreted as the end of the command if.

Diagram of if statement in Python

Diagram of if statement in Python

Example 1:

# Nếu là số dương ta sẽ in một thông điệp thích hợp
num = 3
if num > 0:
    print(num, "là số dương.")
print("Thông điệp này luôn được in.")

num = -1
if num > 0:
    print(num, "là số dương.")
print("Thông điệp này cũng luôn được in.")

Output of the above program:

3 là số dương.
Thông điệp này luôn được in.
Thông điệp này cũng luôn được in.

In the above example, num > 0 is the condition, the command block of if is executed when the True condition is satisfied. When num equals 3, check the condition, see true, command block of if is executed. When num equal to -1, the condition is not satisfied, the command block of if is ignored and executes the command print() Final.

Paying a little closer attention, you will see that there are several commands print() not indented, which says: print() This is outside the command block ifso it will be done, regardless of the conditions.

if…else command

If…else statement structure

if dieu_kien:
   Khối lệnh của if
else:
   Khối lệnh của else

Command if...else Check the condition and execute the block of commands if if the condition is true. If the condition is false, the statement block of else will be performed. Indentation is used to separate blocks of commands.

Diagram of if…else command

Diagram of if...else command

Example 2:

# Chuong trinh kiem tra xem so am hay duong
# Va hien thi thong bao phu hop

num = 3

# Hay thu chuong trinh voi 2 gia tri sau: 
# num = -5
# num = 0

if num >= 0:
   print("So duong hoac bang 0")
else:
   print("So am")

In example 2, when variable num equals 3, the test expression is True and the following command if done, part else will be ignored.

If num equals -5, the test expression is False and the following block of commands else will be executed, the body of if ignored.

If num equals 0, the test expression is True and the following command if executed, section else will be ignored.

if…elif…else statement in Python

If…elif…else statement structure

if dieu_kien1:
   Khối lệnh của if
elif dieu_kien2:
   Khối lệnh của elif
else: 
   Khối lệnh của else

elif is an abbreviation of else ifit allows us to test many conditions.

If conditions1 is false, it will check conditions2 of block elif next and so on until the end. If all conditions are false it will execute the block of code else.

Just one block of commands in if...elif...else is followed if the condition is True.

There may be none or many elifpart else is optional.

Diagram of if…elif…else statement

Diagram of if...elif...else command

Example 3:

x = int(input("Nhap mot so: "))
if x 

Output:

Output of if statement on Python

  • If x is a negative number, print to the screen: “So am”.
  • If x = 0, it will print: “So 0”.
  • If x = 1, it will print: “So 1”.
  • If all three conditions above are false, print: “So equal”.

Command if...elif...elif... is a replacement for the command switch. switch nice case. case in other programming languages.

Nested if statements in Python

You can write commands if...elif...else in a block of commands if...elif...else other, and form a command if nested. There is no limit to the number of commands nested within another command. Indentation is the only way to identify the level of nesting, so it can cause confusion. You should limit use if possible.

Example 4:

# Trong code này, nhập vào một số
# Kiểm tra xem số âm hay dương
# hay bằng không và hiển thị
# thông báo thích hợp
# Sử dụng hàm if lồng nhau

num = float(input("Nhập một số: "))
if num >= 0:
   if num == 0:
       print("Số Không")
   else:
       print("Số dương")
else:
   print("Số âm")

Result 1:

Nhập một số: 10
Số dương

Result 2:

Nhập một số: -5
Số âm

Result 3:

Nhập một số: 0
Số Không

Example 5:

x = 41

if x > 10:
  print("Above ten,")
  if x > 20:
    print("and also above 20!")
  else:
    print("but not above 20.")

Pass command in Python

If statements cannot be empty, but if for some reason you have an if statement that contains no content, put it in a pass statement to avoid errors.

For example:

a = 33
b = 200

if b > a:
  pass

Frequently asked questions about conditional statements in Python

What happens when the If condition is not met?

If the conditional statement is true, the block of code included in the if statement will run. However, if the if condition is not met, the code inside the curly braces is ignored and the next if statement will run. It shows an error message because it does not match the specified if condition.

When does the else condition not work?

Sometimes, you don't get the desired result by using else condition. It was due to a logic error that occurred in the program. This problem usually appears when a program has more than two statements or conditions. If you are having trouble with the else statement, it may be because you have navigated the operator without the “;” marks the conclusion of the if statement. So when it discovers else after a few steps, it starts reporting.

What do Else and While Else mean in Python?

Python provides useful features like for-else and while-else. The else block can be used immediately after for and while loops. If the break statement does not end the loop, the else block will be implemented.

The syntax for the Python for-else statement is:

Given i in range(n):

#code

Else:

#code

The syntax for while-else in Python is:

While condition:

#code

Else:

#code

What does the == sign mean in Python?

The balance of two objects is compared using the '= =' operator. In Python, one equal sign '=' allocates a value to a variable, while two equal signs '==' checks whether two expressions give the same value. In general, you are comparing the value of two items. If you want to evaluate whether two objects share the same characteristics and don't mind where they are stored in memory, this is all you need.

Above are the things you need to know about using if statements and other conditional functions in Python. Hope the article is useful to you.

Now you have grasped the basics of using if statements in Python. Try taking the following easy test to see if you really understand the lesson!

Next we will learn about loops for. Please remember to follow.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments