Conditional loop statements form the skeleton of Python code

Conditional control

We all know that the flowchart has multiple branches, and the same is true in the program. In Python, the if statement is used to determine which branch the program should take. Its execution process is as follows:

The code execution process is as follows:

if

The general form of an if statement is as follows:

if condition_1:
    statement_block_1
  • If condition_1 is True, execute statement_block_1.

condition_1 is a conditional expression composed of various operators and data types. The result of the conditional expression can be a Boolean value of True/False or a non-boolean value. In Python, 0, None, empty list, empty dictionary, etc. will be considered False, and vice versa will be considered True.

else

The else statement is executed when the condition is False:

if condition_1:
    statement_block_1
else:
    statement_block_2
  • If condition_1 is True, execute statement_block_1.
  • If condition_1 is False, execute statement_block_2.

elif

if...else implements "if the conditions are met, then xxx, otherwise xxx", in addition, you can also use elif to implement multiple continuous judgments and execute different statements respectively:

if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3
  • If condition_1 is True, execute statement_block_1.
  • If condition_1 is False, then judge, if condition_2 is True, execute statement_block_2.
  • Otherwise, execute statement_block_3.

elif can write multiple. The execution order of this writing method is from top to bottom. As long as a certain if or elif condition is met, it will jump out after the current branch is executed, and the subsequent judgment will not be executed. If the condition of each if or elif is False, the else will be executed at the end.

if nested

If you want to continue to make judgments after satisfying the conditions of if or elif, then you need to nest if statements, so that code blocks such as statement_block_1 also contain if statements:

if expression 1:
    statement
    if expression 2:
        statement
    elif expression 3:
        statement
    else:
        statement
elif expression 4:
    statement
else:
    statement

Example:

num=int(input("Enter a number:"))
if num%2==0:
    if num%3==0:
        print("The number you enter is divisible by 2 and 3")
    else:
        print("The number you entered is divisible by 2, but not divisible by 3")
else:
    if num%3==0:
        print("The number you entered is divisible by 3, but not divisible by 2")
    else:
        print  ("The number you entered is not divisible by 2 and 3")

loop statement

Conditional statements are executed in a single pipeline from top to bottom. The difference between a loop statement and a conditional statement is that the loop can return to the starting point and execute it repeatedly. Its execution process is as follows:

while

One form of a loop statement is the while statement:

while Analyzing conditions(condition): 
    execute statement(statements)......

Its execution flow chart is as follows:

Example:

n = 100
 
sum = 0
counter = 1
while counter <= n:
    sum = sum + counter
    counter += 1
 
print("1 arrive %d The sum is: %d" % (n,sum))  # 5050

for

Another form of the loop statement is the for statement:

for <variable> in <sequence>:
    <statements>
else:
    <statements>

Its execution flow chart is as follows:

Example:

languages = ["C", "C++", "Perl", "Python"]
for x in languages:
    print(x)

break

break is used to jump out of the entire loop, and its execution flow chart is as follows:

Example:

for letter in 'Runoob':     # first instance
   if letter == 'b':
      break
   print ('The current letter is :', letter)
  
var = 10                    # second instance
while var > 0:              
   print ('The current variable value is :', var)
   var = var -1
   if var == 5:
      break
 
print ("Good bye!")

continue

break is used to jump out of the entire loop, and continue is used to skip the current loop, return to the starting point, and continue the next loop. Its execution flow chart is as follows:

Example:

for letter in 'Runoob':     # first instance
   if letter == 'o':        # Skip output when letter is o
      continue
   print ('current letter :', letter)
 
var = 10                    # second instance
while var > 0:              
   var = var -1
   if var == 5:             # Skip output when variable is 5
      continue
   print ('current variable value :', var)
print ("Good bye!")

The code execution process of break and continue in while loop and for loop is as follows:


loop else

The loop can be followed by an else statement, while...else, for...else. At first glance, else doesn't seem to be useful, because the while loop condition is False or after the for loop ends, the next statement will be executed. But if a break occurs in the loop, the else statement will not be executed when the loop jumps out of the break. E.g:

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, 'equal', x, '*', n//x)
            break
    else:
        # Element not found in loop
        print(n, ' is a prime number')

The range() function can generate sequences of numbers.

Infinite loop

By setting the while loop condition to always be True, you can keep the loop going forever, for example:

while True:
    pass

pass is a placeholder statement that does nothing.

Infinite loops are useful, such as timed tasks that receive emails every 5 minutes:

import time

while True:
    receive_email()
    time.sleep(300)
    

There are also heartbeat mechanisms such as the client and the server to keep connected.

summary

This article introduces conditional control and looping statements, that is, if, while, and for statements commonly used in Python, and also explains the use of the accompanying statements elif, else, break, continue, and pass. It also includes the knowledge points of if nesting, loop else, and infinite loop. This part of the knowledge is very important and is the skeleton of the code. Besides reading articles, the best way to learn code is to actually type the code. We have set up a "Python mutual aid discussion group". Every Sunday, there will be an algorithm to punch in the question (it is ok to tap the answer again), and the public account background can reply "Add group" to join, and interested students can come together. learn from each other.

References:

https://www.runoob.com/python3/python3-conditional-statements.html

https://www.runoob.com/python3/python3-loop.html

Tags: Python

Posted by alexislalas on Mon, 02 May 2022 21:26:39 +0300