عبارة if

تعرف على استخدام ووظيفة عبارة "if" في Python للتحكم في تدفق البرنامج استنادًا إلى التعبيرات الشرطية.

سنغطي ما يلي...

Structure

The simplest conditional statement that we can write is the if statement. It consists of two parts:

  1. The condition
  2. The code to be executed
Press + to interact

The : in the illustration above is necessary to specify the beginning of the if statement’s code to be executed. However, the parentheses, (), around the condition are optional. The code to be executed is indented at least one tab to the right.

The flow of an if Statement

An if statement runs like this:

if the condition holds True, execute the code to be executed. Otherwise, skip it and move on.

Let’s write a simple if statement that verifies the value of an integer variable:

Press + to interact
num = 5
if (num == 5):
print("The number is equal to 5")
if num > 5:
print("The number is greater than 5")

Our first condition simply checks whether the value of num is 5. Since this Boolean expression returns True, the compiler goes ahead and executes the print statement on line 4. Since num is not greater than 5, the second condition (line 6) returns False and line 7 is skipped. Also notice that the parentheses, (), around the conditions are optional.

As we can see, the print command inside the body of the if statement is indented to the right. If it wasn’t, there would be an error. Python puts a lot of emphasis on proper indentation.

Compound conditional statements

We can use logical operators to create more complex conditions in the if statement. For example, we may want to satisfy multiple clauses for the expression to be True.

Try it yourself

Let’s see if we can repair the following code and make it run successfully. Our AI Mentor can guide you as well.

Press + to interact
num = 12
if num % 2 == 0 and num % 3 == 0 and num % 4 == 0:
# Only works when num is a multiple of 2, 3, and 4
print("The number is a multiple of 2, 3, and 4")
if (num % 5 == 0 or num % 6 == 0)
# Only works when num is either a multiple of 5 or 6
print("The number is a multiple of 5 or 6")

In the first if statement, all the conditions have to be fulfilled since we’re using the and operator.

In the second if statement, the Boolean expression would be True if either or both of the clauses are satisfied because we are using the or operator.

Nested if Statements

A cool feature of conditional statements is ...