[Python foundation -- program control statements and structures] overview and summary

Posted by NeilB on Tue, 25 Jan 2022 12:55:13 +0100

1, Normal statement (sequential structure)

As the name suggests, sequential structure means that sentences are executed from top to bottom without control. It is not only the structure we use frequently, but also the basis for us to learn other structures.

#Sequential structure:
#Create int variable
x = 3
#Print the variable
print(x)	#Result: 3
#View the variable type
type(x)		#Result: < class' Int '>

The above statement is a sequential structure.

2, Conditional judgment statement (selection structure)

Conditional judgment statement, that is, judge whether it is true according to Boolean logic, which affects the selection of subsequent code block execution.

1. if statement & single branch selection

if expression:
	Statement block

Single branch selection: judging whether the condition is true or not is related to the execution / skipping of this part of the code block.

#Create an int variable
x = 3
#Execute judgment operation
if x == 4:
	print('A')
print('Z')

Execute the above code. Obviously, the letter A will not be printed out by the console because the judgment conditions are not satisfied, and the letter Z will be output normally.

#Create an int variable
y = 4
#Execute judgment operation (pay attention to indentation during writing. Python is a language that needs to strictly control indentation)
if y == 4:
	print('A')
print('Z')

When the above code is executed, the console outputs the letter A first and then the letter Z.

2. If else statement & double branch selection

if expression:
	Code block
else :
	Code block

Double branch selection: it provides us with two paths. If the judgment conditions are not met, we will no longer skip the control area, but enter the code block governed by else statement. After its line is completed, we can continue to execute the subsequent code.

Take this statement as an example and change the above code:

#Create an int variable
x = 4
#Execute judgment operation (pay attention to indentation during writing. Python is a language that needs to strictly control indentation)
if x == 3:
	print('A')
else :
	print('B')
print('Z')

At this time, since the variable x is not equal to 4, the console will output the letter B first and then the letter Z.

3. If elif else statement & multi branch selection

if Expression 1:
	Code block
elif Expression 2:
	Code block
elif Expression 3:
	Code block
......
elif expression n:
	Code block
else :
	Code block

Multi branch selection can enter different code blocks according to different conditions, so as to complete the judgment of various situations. Else if represents the code block to be executed when all the above conditions are not true, but the else if control condition is true. Because else if is not easy to write, Python supports its abbreviation elif.

#Create an int variable
x = 12
#Execute judgment operation (pay attention to indentation during writing. Python is a language that needs to strictly control indentation)
if x < 5: 
	print("x Less than 5")
elif x < 10: 
	print("x Less than 10 but not less than 5")
elif x < 15: 
	print("x Less than 15 but not less than 10")
else :
	print("x Not less than 10")

Obviously, the console performs output: x is less than 15, but not less than 10.

3, Loop execution statement (loop structure)

1. for loop (count loop)

for Value in sequence / Iteration object:
	Code block
[else:
	Code block]

Counting cycle, that is, when the counting value does not meet the conditions, it will continue until the counting is completed.

Python's for needs to be assisted by sequence / iteration objects. The commonly used iteration object is the range object. It also supports the execution of code blocks in else when the loop ends.

Add the first 100 positive integers and output:

#Define an int variable to represent the result variable
int s = 0
for i in range(1,101): 
	s += i
print(s)

Use the for else structure to execute the print statement. Else means that whether the loop can be carried out or not, it will always execute its internal code block when exiting the loop (the count size no longer meets the condition):

#Define an int variable to represent the result variable
int s = 0
#Execution cycle
for i in range(1,101): 
	s += i
else:
	print(s)		#5050

When the above two codes are executed, the console will output the final result: 5050.

2. while loop (conditional loop)

while expression:
	Code block
[else:
	Code block]

Python's while loop is a conditional loop, that is, when the conditions are met, it will be executed until the conditions are no longer met. While also supports the execution of code blocks in else when the loop ends.

We can also complete the task of "adding and outputting the first 100 positive integers" through the while loop, but the judgment and counting methods are different here:

#count
int i = 0;
#Store results
int s = 0;
#Execution cycle
while i <= 100:
	s+=i;
	i+=1;
else
	print(s)		#5050

Execute the above code, and the console will eventually output the result: 5050.

3. break statement, continue statement

break statement and continue statement are also very commonly used in the process of programming, which are responsible for controlling the jump out of the loop.

  • break statement: end the loop of this layer and no longer execute the code block.
  • continue statement: skip the execution of this cycle, ignore all subsequent codes, and enter the next cycle.

Find the maximum prime number (prime number) within 100:

#External circulation: starting from 100, each time - 1
for n in range(100,1,-1):
	#Determine whether it can be divided by 2
	if n % 2 == 0:
		#If it can be divided by 2, it must not be a prime, and 2 itself is known to be not the largest prime within 100
		continue
	#Start from 3 until n ^ 0.5 (rounded) + 1 ends the cycle, increasing by 2 each time
	for i in range(3,int(n**0.5)+1,2):
		#When n is divisible by i
		if n % i == 0:
		#End internal circulation
		break;
else:
	#Print n at this time
	print(n)
	#End external circulation
	break

In this way, we find the minimum prime 97 within 100.

4, Exercise exercise

Exercise 1: judge the score according to the input

while True:
    score =  int(input('Please enter your grade:\n'))
    if score == -1:
        print('sign out!')
        #Exit total cycle
        break
    elif score < 60 :
        print('Failed!')
    elif score < 75:
        print('Average results!')
    elif score < 85:
        print('Good grades!')
    elif score < 100:
        print('Excellent results!')
    elif score == 100:
        print('Full score!')
    else:
        print('Incorrect input result!')

Exercise 2: output diamond pattern

n = int(input('Please enter the number of diamond rows:\n'))

for i in range(n):
	print(('* ' * i).center(n * 3))
for i in range(n,0,-1):
	print(('* ' * i).center(n * 3))


Topics: Python