SoFunction
Updated on 2025-03-01

Analysis of the basic conditions and loop control instances of Python3

This article explains the conditions and loop control statements and their usage in Python3 in an example form. It is an important knowledge point that must be mastered when learning Python. We are now sharing it for your reference. The details are as follows:

Generally speaking, Python's process control statements include: if conditional statements, while loop statements, for loop statements, range functions, and break, continue, and pass control statements. The semantics of these statements in Python are basically the same as those in other languages, so here we will only talk about their usage.

1. If statement

If statement is the most commonly used conditional control statement, the general form in Python is:

if Condition 1:
 statements
elif Condition 2:
 statements
else:
 statements


Example

if condition_1:
  statement_block_1
elif condition_2:
  statement_block_2
else:
  statement_block_3

If "condition_1" is True, the "statement_block_1" block statement will be executed
If "condition_1" is False, "condition_2" will be judged
If "condition_2" is True, the "statement_block_2" block statement will be executed
If "condition_2" is False, the "statement_block_3" block statement will be executed

Used in PythonelifInstead of else if, so the keywords of the if statement are: if - elif - else.

Notice:

1. A colon (:) should be used after each condition to indicate that the next statement block to be executed after the condition is met.
2. Use indentation to divide statement blocks, and statements with the same indentation number form a statement block together.
3. There is no switch - case statement in Python.

The sample code is as follows:

x = int(input("Please enter an integer: "))
if x < 0:
 print('Negative.')
elif x == 0:
 print('Zero.')
else:
 print('Positive.')

Example

Here is a simple if instance:

#!/usr/bin/python3
 
var1 = 100
if var1:
  print ("1 - if expression condition is true")
  print (var1)
 
var2 = 0
if var2:
  print ("2 - if expression condition is true")
  print (var2)
print ("Good bye!")

Execute the above code and the output is:

1 - if expression condition is true
100
Good bye!

From the result, we can see that since the variable var2 is 0, the corresponding statement in if is not executed.

The following example demonstrates the age calculation of a dog:

#!/usr/bin/python3
 
age = int(input("Please enter the age of your dog: "))
print("")
if age &lt; 0:
  print("You are teasing me!")
elif age == 1:
  print("The equivalent of 14 years old.")
elif age == 2:
  print("The equivalent of 22 years old.")
elif age &gt; 2:
  human = 22 + (age -2)*5
  print("Responding to human age: ", human)
 
### Exit promptinput("Click enter key to exit")

Save the above script in a file and execute the script:

$ python3
Please enter the age of your dog: 1

The equivalent of 14 years old.
Click enter key to exit

The following are commonly used operation operators in if:

Operator describe
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to compare whether the objects are equal
!= Not equal to

Example

#!/usr/bin/python3
 
# The program demonstrates the == operator# Use numbersprint(5 == 6)
# Use variablesx = 5
y = 8
print(x == y)

The above example output results:

False
False

The high_low.py file demonstrates the comparison operation of numbers:

Example

#!/usr/bin/python3 
 
# This example demonstrates the number guessing gamenumber = 7
guess = -1
print("Digital guessing game!")
while guess != number:
  guess = int(input("Please enter the number you guessed:"))
 
  if guess == number:
    print("Congratulations, you guessed it right!")
  elif guess &lt; number:
    print("The guessed number is smaller...")
  elif guess &gt; number:
    print("The number you guessed is too big...")

Execute the above script, the output result of the example is as follows:

$ python3 high_low.py
Number guessing game!
Please enter the number you guessed: 1
The number you guessed is small...
Please enter the number you guessed: 9
The guessed number is big...
Please enter the number you guessed: 7
Congratulations, you guessed it right!

if nesting

In nested if statements, you can place the if...elif...else structure in another if...elif...else structure.

if expression1:
  Statement
  if expression2:
    Statement
  elif expression3:
    Statement
  else:
    Statement
elif expression4:
  Statement
else:
  Statement

Example

# !/usr/bin/python3
 
num=int(input("Enter a number:"))
if num%2==0:
  if num%3==0:
    print ("The numbers you enter can be divisible by 2 and 3")
  else:
    print ("The number you enter can be divisible by 2, but not by 3")
else:
  if num%3==0:
    print ("The number you enter can be divisible by 3, but not by 2")
  else:
    print ("The numbers you enter cannot be divided into 2 and 3")

Save the above program to the test_if.py file, and the output result after execution is:

$ python3
Enter a number: 6
The numbers you enter can be divisible 2 and 3

2. While statement

The general form of while statement in Python:

while Judgment conditions:
 statements

Also, attention should be paid to colons and indents. Also, there is no do..while loop in Python.

The sample code is as follows:

a, b = 0, 1
while b &lt; 10: # Loop output Fibonacci sequence print(b)
 a, b = b, a+b

3. For statement

The for statement in Python is a bit different from the for statement in C: the for statement in C allows users to customize iteration steps and termination conditions; while the for statement in Python can traverse any sequence and iterate in sequence according to the order in which elements appear in the sequence. The general form is:

for variable in sequence:
 statements
else:
 statements

The sample code is as follows:

words = ['cat','love','apple','python','friends']
for item in words:
 print(item, len(item))

If you need to modify the sequence you are iterating in the loop body, you'd better make a copy, and the slice marking is very useful:

words = ['cat','love','apple','python','friends']
for item in words[:]: # Make a slice copy of the entire list if len(item) &gt;= 6:
 (0, item)
print(words)

We noticed that else clause can also be used in loop statements, as mentioned in the fifth point below.

4. Range function

If you are going to iterate through a sequence of numbers, the built-in range() function can come in handy. The function range() is often used in for loops to generate an arithmetic sequence:

&gt;&gt;&gt; list(range(10)) # The default starts from 0[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
&gt;&gt;&gt; list(range(1, 11)) # From 1 to 11, close front and open back[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
&gt;&gt;&gt; list(range(0, 30, 5)) #5 represents step size, take a number every 5[0, 5, 10, 15, 20, 25]

The sample code is as follows:

for i in range(2, 11):
 print(i)

5. Break, continue, pass and else clauses

①.break

The break statement is the same as in C language, breaking out of the most recent for or while loop.

②.continue

The continue statement is also borrowed from C language, which terminates the current iteration and performs the next iteration of the loop.

③.pass

The pass statement does nothing, it only uses when a syntax requires a statement but the program does not require any operations. The pass statement is to maintain the integrity of the program structure.

④.else clause

You can also use the else clause in a loop statement. The else clause is executed when the sequence traversal ends (for statements) or the loop condition is false (while statements), but the loop is not executed when the loop is terminated by break. As shown below:

# End the loop to execute the else clausefor i in range(2, 11):
 print(i)
else:
 print('for statement is over.')

# The else clause will not be executed when terminated by breakfor i in range(5):
 if(i == 4):
 break;
 else:
 print(i)
else:
 print('for statement is over') #No output