【Update】Python Basic Tutorial: Chapter 4_ Loop Statements

Original: Official Account Data Talk [Words Update] Python Basic Tutorial: Chapter 4_ Loop Statements

foreword

Circulation is ubiquitous in daily life, and similarly, in programs, the circulation function is also a crucial basic function.

The process of a cycle is very simple. Based on the conditional judgment, as long as the condition is met, the corresponding operation can be performed. After the operation is completed, the judgment will be made again. If the condition continues to be met, then the corresponding operation will continue. Then the cycle continues like this. Until the condition is not met, our loop ends.

Why Learn Loop Statements

Loops, like judgments, exist widely in programs and are the basis for the realization of many functions. If there is no such thing, many common functions in daily life will be difficult to realize.

In daily life, the basic functions realized by looping billboards, batch retouching, video carousel, music carousel, picture carousel, loudspeaker shouting, live wallpaper, video surveillance, etc. are what we call looping.

So we need to understand that looping, like judgment, is the most basic and core logic function of the program. Next, let's learn in detail.

Basic syntax of while loop

learning target

  • Master the basic application of using while loop

while loop statement

In Python, we provide a loop statement called while. In order to understand it, let's review the basic flow of the loop. There are two basic elements for the loop:

The first one is called condition, and the second is called operation. As long as the condition is satisfied, the corresponding operation will be performed. After the operation is completed, the condition will be judged. If it continues to be satisfied, the corresponding operation will continue until the condition is not satisfied. Our loop is over. , so the cycle has two elements: condition and operation, and the cycle in our daily life actually meets the requirements of these two elements.

  • cycle of life

Go to confess to Xiaomei every day until you succeed:

This is a typical cycle, what is the condition? The condition is until it succeeds, that is, if it fails, I will continue to confess.

Then you can see the cases of loops in life, in fact, they all meet these two key elements, so based on these two key elements, how to use loops in the program?

  • The loop in the program:

For the while loop, the syntax is very simple. We first need to use a keyword called while, and then we give the condition after the keyword. What type of data should the condition be? For this condition, in fact, comparison operations can be used, or the Boolean type can be used directly.

The final result must be Boolean, that is, True means to continue to run the loop, then add a colon after the condition, and then we write below the operation that the loop should do if the condition is met.

 
 
 
 

while condition:
When the condition is met, do thing 1.
When the condition is met, do thing 2.
When the condition is met, do thing 3
(omitted).

In this grammar, does it also satisfy the setting of the two key element conditions and the setting of the operation we said?

Then through this grammar, we can perform the corresponding operation when the condition is met, and then judge if the condition is satisfied after completion, continue to do the operation, and then judge if the condition is still satisfied, continue to do the operation until the condition is not satisfied Our loop is over, so this is its grammar, let's take a look again, let's find a specific case, and see how to write the loop.

First of all, suppose that Xiaomei is relatively soft-hearted. As long as I confess 100 times, I will succeed. If we don’t use loops, then we may have to write 100 times, and the print statement will say Xiaomei, I like you. Tired, very low-level:

 
 
 
 

print("Xiaomei, I like you")
print("Xiaomei, I like you")
print("Xiaomei, I like you")
...(97 more times)...

For this case, we will find it super simple once we transform this kind of loop. In the while loop, there are conditions and corresponding operations.

First of all, let's see that the condition is that the variable i is less than 100. As long as this condition is met, our loop will continue to execute.

The condition is met, and the operation is when the condition is met, we output: Xiaomei, I like you. At the same time, the variable i is incremented by 1.

We can see that the variable i has been defined before the loop, and its initial value is 0, which means that the loop is executed once, and the output of "Xiaomei, I like you" will add i + 1, which will become 1. For the second time, i will become 2, and for the third time, i will become 3. Then you can see that when i becomes 100, whether this condition is not satisfied, and the cycle ends. So, from the beginning of execution to the end of the loop, will our operation be executed exactly 100 times, that is, we confessed to Xiaomei 100 times, this is the simple application of the loop statement, and it is still very simple.

 
 
 
 

i = 0
while i < 100:
print("Xiaomei, I like you")
i += 1

Notes on while loop

  1. 1. The condition of while needs to be of Boolean type, True means to continue the loop, False means to end the loop

  2. 2. It is necessary to set the conditions for loop termination, such as i += 1 and i < 100, to ensure that it will stop after 100 times, otherwise it will loop infinitely

  3. 3. Space indentation is the same as if judgment, both need to be set

practise

Practice case: Find the sum of 1-100 Requirements: Through the while loop, calculate the sum from 1 to 100 Tips:

  1. 1. Don't forget the termination condition, set it to ensure the while loop 100 times

  2. 2. Make sure that the accumulated numbers start from 1 and end at 100

There are two tips to pay attention to. Don’t forget to set the first termination condition. We need to ensure that the while loop loops 100 times. Second, we need to ensure that the number starts from 1 and ends at 100. OK, then we analyze the basic requirements after we finish Well, just write the code yourself! The reference code is as follows:

 
 
 
 

sum = 0
i = 1
while i<=100:
sum += i
i += 1

print(f"The cumulative sum of 1-100 is: {sum}")

Basic case of while loop

learning target

  • Able to use the while loop to complete the case of guessing numbers

Guess the number case

In one section, we learned the basic grammar of the while loop, and explained to the students the basic exercises for finding the sum of 1-100. Then in this section, we will learn a basic case of the while loop to consolidate our For the mastery of the while loop, our learning goal is very simple. We use the while loop to complete the study of a case called, splitting numbers. First, let's look at the requirements of the case:

  • · Set a random integer variable in the range of 1-100, and use the while loop to cooperate with the input statement to determine whether the input number is equal to the random number

  • · Unlimited chances until you guess right

  • · Every time you fail to guess correctly, it will prompt whether it is too big or too small

  • · After guessing the number, prompt how many times to guess

hint:

  • · Unlimited opportunities, the termination condition is not suitable for judging by the accumulation of numbers

  • Can consider Boolean type itself (True or False)

  • · If you need to prompt several times to guess correctly, you need to provide the function of number accumulation

Random numbers can be used:

 
 
 
 

import random
num = random.randint(1,100)

Tip: First of all, if there are infinite chances, then our termination condition is no longer suitable for judging by the accumulation of numbers used earlier, for example, the condition of being less than 100, because our infinite chances cannot be determined by fixed numbers. To lock his number of times, so we can consider using the Boolean type, which itself is True or False. 

Secondly, we need to remind several rounds of guessing. The realization of this function requires us to provide a function of adding numbers during the guessing process. In this way, we can record it when the guess is finally completed.

Third, if we want to generate random numbers, we can use the random module in python. We will explain its specific use in detail in the follow-up. Now we don’t care what it means, we can use it as written, It is enough to get a suitable random number. After analyzing the basic case requirements for the students, let us open Pycharm and write the code:

 
 
 
 

# Obtain a random number in the range of 1-100
import random
num = random.randint(1, 100)
# Define a variable to record how many guesses have been made in total
count = 0

# Use a Boolean variable to mark whether the loop continues
flag = True
while flag:
guess_num = int(input("Please enter the number you guessed:"))
count += 1
if guess_num == num:
print("Guessed")
# Setting it to False is the condition to terminate the loop
flag = False
else:
if guess_num > num:
print("You guessed too big")
else:
print("You guessed too small")

print(f"You guessed {count} times in total")

Nested application of while loop

learning target

  • Master the basic format of while nested loop

  • Complete the application of while nested loop

Nesting of while loops

Nested loops in life 

Let's take a look at the nested loops we will encounter in life. Still take confessing love to Xiaomei as an example, we will confess to Xiaomei every day until we succeed, but in this process, we still have a specific detail, that is, I will send 10 roses every day during the confession process, Then confess, then you will find that there are actually two layers of cycles in this cycle.

The outer loop is to confess my love every day until I succeed. The inner loop means that when I confess my love every day, I will send 10 roses, that is, we can send 10 roses through an inner loop. Yes, so this is what you may encounter in life, nested loops. 

loop inside loop 

Then let's take a look again, if this kind of nested loop is to be completed in the program, how is its syntax done? In fact, it is also very simple. Just like in our learning judgment statement, our while can also be nested. At the same time, its nesting is also indented based on spaces. We only need to write another in the outer while loop. The inner while loop is fine, use spaces to indent to ensure the hierarchical relationship between them, so that they can be nested successfully!

 
 
 
 

while condition 1:
when condition 1 is met, do thing 1
when condition 1 is met, do thing 2
when condition 1 is met, do thing 3
· (omit). ·
while condition 2:
when condition 2 is satisfied, do thing 1
When condition 2 is met, do thing 2
When condition 2 is met, do thing 3
(omitted).

For the case of just confessing to Xiaomei, let's see if you use while nested loops, then in the code you will find that there are two layers of loops, the first layer of loops is, i<=100, which means I want to Express the control of 100 days, then the inner loop writes j<=10, then this is the control of sending 10 roses every day.

It can be seen that after the outer loop came in, he said that today is the second day, for example, the first day and the second day are ready to confess, and then enter the inner loop, we send 10 roses to Xiaomei through this loop , After sending it, I will say Xiaomei, I like you. You can see that through the two layers of the outer layer and the inner layer, we have completed the confession every day, and we will send 10 roses every day for the confession. Completely over, the confession is successful:

Confession 100 days will send 10 roses every day

 
 
 
 

# Outer layer: control of 100 days of confession
# Inner layer: control of giving 10 roses every day for confession

i = 1
while i <= 100:
print(f"Today is the {i} day, ready to confess... ..")

# The control variable of the inner loop
j = 1
while j <= 10:
print(f"Send the {j}th rose to Xiaomei")
j += 1

print("Xiaomei, I like you ")
i += 1

print(f"Persist until the {i - 1} day, the confession is successful")

After the completion, let's analyze our inner and outer layers again. This is the control of the outer layer, which controls the number of days, and this is the control of the inner layer. The control is how many roses we send each day. i is the control variable of the outer layer, j is the control variable of the inner layer, and our control variable j+=1, which acts on the inner loop, our i+=1 acts on the outer loop, so the inner and outer layers have their own Each of the control variables has its own scope of action.

Nesting of while loops - attention points

  • Like the nesting of the judgment statement, the nesting of the loop statement should pay attention to the indentation of spaces.

  • Determining Hierarchy Based on Space Indentation

  • Pay attention to the setting of conditions to avoid infinite loops (unless infinite loops are really needed)

Nested case of while loop

learning target

  • Master the use of while nested loops to print the ninety-nine multiplication table

Supplementary knowledge - print output does not wrap

By default, the output of the print statement will automatically wrap, as follows:

 
 
 
 

print("Hello")
print("World")

Output result:

 
 
 
 

Hello
World

In the case that is about to be completed, we need to use the print statement to output the function of not wrapping. It is very simple, and the implementation method is as follows:

 
 
 
 

print("Hello",end="")
print("World",end="")

 
 

HelloWorld

As above, in the print statement, add end="" to output without line breaks ps: end="" is the function of method parameter passing, which we will explain in detail later.

Supplementary knowledge-tab \t

In the string, there is a special symbol: \t, which is equivalent to pressing the tab key on the keyboard. It allows our multi-line strings to be aligned. for example:

 
 
 
 

print("Hello World")
print("itheima itcast")

 
 

Hello World
itheima itcast

Using \t, you can align

 
 
 
 

print("Hello\tWorld")
print("itheima\titcast")

Output result:

 
 
 
 

Hello World
itheima itcast

So this is a special small symbol called a tab, and the application of the tab is still very extensive.

Two knowledge points to supplement the students, one is to use ordinary sentences, the output does not wrap new lines, and the second is to make words output in multiple lines, and they can be aligned. It is better to use the character \t. With these two After laying the foundation and supplementing the content knowledge, we can now complete the code development of our case.

Practice case - printing ninety-nine multiplication table

Through the while loop, output the contents of the ninety-nine multiplication table as follows

hint:

  • 2-layer loop, the outer layer controls the row, the inner layer controls the column,

  • The accumulative number variable of the outer loop and the memory loop is used to assist in outputting the value of the multiplication table

Reference Code:

 
 
 
 

# Define the control variable
i of the outer loop = 1
while i <= 9:

# Define the control variable
j of the inner loop = 1
while j <= i:
# The print statement of the inner loop, do not break the line, use \t to tabulate print
(f"{j} * {i} = {j * i}\t", end='')
j += 1

i += 1
print() # print empty content, that is, output a newline

This is a print of the nine-nine multiplication table done with nested while loops. As for the nine-nine multiplication table, when we learn many languages, especially when we learn nested loops, we will use a case. Its difficulty is not very difficult, but it still requires you to think carefully. It, so students must do this case again after class, which is very helpful for us to master double-layer loops, or multi-layer nested loops, and exercise logical thinking. of help.

Basic syntax of for loop

In this section, we will learn a new loop mechanism called for loop. Our for loop is mainly divided into three parts to explain, the first part is the basic grammar, the second part is the range statement, and the third part is the scope of variables. Let us learn first. The first part, the basic syntax of the for loop.

learning target:

  • for loop basic syntax

for loop

In addition to the while loop statement, Python also provides a for loop statement. The functions that can be completed by the two are basically the same, but there are still some differences:

• The loop condition of the while loop is user-defined, control the loop condition by yourself 

• The for loop is a "polling" mechanism, which is to "process" a batch of content one by one. Let's take a look at the difference between them through the following figure:

  • while loop

 

For the while loop, it has a condition, you can do the operation as long as the condition is met, then there is no limit, as long as the condition is met, you can do the operation, when the condition is not met, I will end the loop, so say It's very simple, you can control this condition by yourself.

  • for loop

 

The for loop is a loop mechanism that completes the "to-do items" one by one. However, our for loop, you will find that it is a bit different. As you can see from the figure, the for loop processes a batch of content one by one, such as Say I process 1 first, it will judge whether there is a next one one by one, fetch 1 and process 1, then fetch 2, then process 2, fetch 3, process 3, when I After fetching 4, 5, 6, 7, etc., you will find that there is no next one. If there is no next one, the for loop will end.

So, this is what we call a for loop, a round robin mechanism that processes content one by one, but in layman's terms, you can think of a for loop as a loop mechanism that completes to-do items one by one.

for loop statement

In fact, the for loop can also be compared to some things in our life. For example, if you want to wash the dishes in our life, you will wash them one by one, and you will peel off the garlic one by one. You need to eat melon seeds one by one, and do some other things, you have to complete them one by one, then you will find that these things in our life are actually the same as the for loop, that is, to do things one by one deal with.

Let's take a look at what the syntax of the for loop looks like in our program. First, it will have a for keyword, then we define a temporary variable, then an in keyword, and then call the last one to be processed The data set, and then give a colon, which means that the data to be processed and the data in it are taken out one by one, and the current data is assigned to this temporary variable every time the loop is passed, and then you can write your in the loop body. code, then of course you can also use this temporary variable:

 
 
 
 

for temporary variable in data set to be processed:
the code executed when the loop meets the conditions

From the data set to be processed: take out the data one by one and assign them to temporary variables. Let's actually look at an example:

 
 
 
 

# Define the string name
name = "itheima"
# for loop processing string
for x in name:
print(x)

It can be seen that the for loop is to take out the contents of the string: sequentially. Therefore, the for loop is also called: traversal loop

 
 
 
 

i
t
h
e
i
m
a

So the for loop can actually be called a traversal loop, because this behavior is actually equivalent to traversing and processing the characters in our string one by one, or you can also think that traversal means sequentially.

for loop attention

 
 
 
 

# Define the string name name = "itheima"
# for loop processing string
for x in name:
print(x)

Unlike the while loop, the for loop cannot define loop conditions.

The content can only be taken out sequentially from the processed data set for processing.

Therefore, in theory, Python's for loop cannot build an infinite loop (the data set being processed cannot be infinitely large) The syntax format of the for loop is:

 
 
 
 

for temporary variable in data set to be processed:
the code executed when the loop meets the conditions

Notes on for loop

  1. Unable to define loop conditions, only passive data processing

  2. It should be noted that the statements in the loop need to be indented with spaces

Practice case: count how many a

Define the string variable name, the content is: "iheima is a brand of itcast" Through the for loop, traverse this string, count how many English letters: "a", and output the following characters:

 
 
 
 

itheima is a brand of itcast contains: 4 letters a

hint:

  1. Counting can define an integer type variable outside the loop for cumulative counting

  2. Judging whether it is the letter "a" can be done by combining the if statement with the comparison operator

 
 
 
 

# Count the number of letters a in the following string
name = "iheima is a brand of itcast"

# Define a variable to count how many a
count = 0

# for loop statistics
# for temporary variable in the counted data :
for x in name:
if x == "a":
count += 1

print(f"There are {count} a's in the counted string")

In fact, the core lies in two points. The first one is to set a variable outside the loop to count how many letters a there are. Then inside the loop, we take out the contents of the string one by one and assign it to a temporary The variable is called x. We need to use if to judge whether x is equal to this a. If the content is equal, it means that the content of x is a. Then we can let the count variable of the calculator Just add 1, okay, so in the end we will count it out.

range statement

 
 
 
 

for temporary variable in data set to be processed (iterable object):
the code executed when the loop meets the condition

The above code is the basic grammar of the for loop. In the grammar, after the in keyword, we need to fill in the data set with processing. Strictly speaking, the data set to be processed is called: iterable type, iterable Type refers to a type whose contents can be taken out one by one, including:

  • string

  • the list

  • tuple

  • wait

So far we have only studied the string type, and the rest of the types will be studied in detail in subsequent chapters.

The for loop statement is essentially traversing: iterable objects.

Although other iterable types are not currently learned except strings, it does not prevent us from obtaining a simple sequence of numbers (a type of iterable type) by learning the range statement. Then he has three grammars:

  • Syntax 1:

range(num) obtains a sequence of numbers starting from 0 and ending with num (excluding num itself). For example, the data obtained by range(5) is: [0, 1, 2, 3, 4]

  • Grammar 2:

range(num1, num2) Get a sequence of numbers starting from num1 and ending with num2 (excluding num2 itself)

For example, the data obtained by range(5, 10) is: [5, 6, 7, 8, 9]

  • Syntax 3:

range(num1, num2, step) Get a step size between numbers starting from num1 and ending with num2 (excluding num2 itself), subject to step (step defaults to 1)

For example, the data obtained by range(5, 10, 2) is: [5, 7, 9]

The for loop traverses the range sequence

 
 
 
 

# for loop processing string
for i in range(5):
print(i)

The output is:

 
 
 
 

0
1
2
3
4

  • The function of the range statement is:

Get a sequence of numbers (a type of iterable)

  • Notes on the range statement:

  • Syntax 1 starts from 0 and ends with num (excluding num itself)    

  • Grammar 2 starts from num1 and ends with num2 (excluding num2 itself)

  • Grammar 3 starts from num1 and ends with num2 (excluding num2 itself)

The step size is based on the step value. Range has many uses, most of which are used in for loop scenarios

variable scope

As shown in the code, think about it:

 
 
 
 

for i in range(5):
print(i)

print(i)

Thinking about the second print statement, can the variable i be accessed? Specification: Not allowed Practically: Yes

variable scope in for loop

 
 
 
 

for temporary variable in data set to be processed:
the code executed when the loop meets the conditions

Looking back at the syntax of the for loop, we will find that the data taken from the data set (sequence) is assigned to: Why are temporary variables temporary? Temporary variables, in terms of programming specifications, scope (scope), are only limited to inside the for loop if temporary variables are accessed outside the for loop:

  • actually accessible

  • In terms of programming specifications, it is not allowed or recommended to do so.

variable scope in for loop

If you really need to access the temporary variables in the loop outside the loop, you can pre-define them outside the loop

 
 
 
 

i = 0
for i in range(5):
print(i)

print(i)

As shown in the figure, every time the loop is performed, the value taken out will be assigned to the i variable.

  • Since the i variable is defined before (outside) the loop

  • It is reasonable and permissible to access the i variable outside the loop

  • Temporary variables in the for loop, its scope is limited to: within the loop

This limitation:

  • It is a limitation of programming specifications, not a mandatory limitation

  • It will work without compliance, but it is not recommended

  • To access a temporary variable, it can be pre-defined outside the loop

Nested application of for loop

learning target

  • Master the nested use of for loops

Nested loops in life

In fact, it is the same as the example we gave in the while loop. For example, we confess to Xiaomei every day until we succeed, and then the process of each confession is to send 10 roses and then confess.

Well, the same case, so let’s take a look again. If we want to use loop nesting, what is its syntax? In fact, it is similar to our while loop, that is, inside the for loop, you Just write another for loop.

Nested loops in the program:

Like while, for loops also support nested use

 
 
 
 

for temporary variable in data set (sequence) to be processed:
what should be done when the loop meets the condition 1
what should be done when the loop meets the condition 2
what should be done if the loop meets the conditionN
for temporary variable in data set (sequence) to be processed:
the loop is satisfied The thing to do if the condition is
met 1 The thing to be done if the condition is
met by the loop 2 The thing to be done when the condition is met by the loop N

In fact, the key to this paragraph is to control the correct indentation. If you pay attention to the inner and outer for loops, you will notice that they are indented differently. The outer loop is indented with 4 spaces, and the inner loop is indented with 8 spaces. Therefore, we can simply realize the nesting of loops through indentation. Taking Xiaomei being confessed as an example, we can use the inner and outer loops to realize the operation process of confessing to Xiaomei and sending her 10 bouquets of roses every day.

 
 
 
 

i = 1
for i in range(1,101):
print(f"Today is the {i} day of confessing to Xiaomei, stick to it.")
for j in range(1,11):
print(f"For Xiaomei The {j}th rose")
print(f"Xiaomei, I like you (the confession on the {i} day is over)")

print(f"The confession is successful on the {i} day")

Because through indentation, the hierarchical relationship is determined

Notes on nesting of for loops

We have learned 2 loops so far, the while loop and the for loop.

These two types of loop statements can be nested with each other, as follows, the case of Xiaomei’s confession can be changed to:

 
 
 
 

i = 1
for i in range(1,101):
print(f"Today is the {i} day of confessing to Xiaomei, stick to it.")
j = 1
while j <= 10:
print(f"The first day of sending to Xiaomei {j} roses")
j+=1
print(f"Xiaomei, I like you (the confession on the {i} day is over)")
print(f"The confession is on the {i} day, the confession is successful")

You can type the code yourself to experience:

 
 
 
 

i = 1
while i <= 100:
print(f"Today is the {i} day of confessing to Xiaomei, stick to it.")
for j in range(1,11):
print(f"The {i} day of sending to Xiaomei j} roses")
print(f"Xiaomei, I like you (the confession on the {i} day is over)")
i += 1

print(f"The confession is on the {i-1} day, the confession is successful")

Practice case-for loop printing ninety-nine multiplication table

Through the for loop, output the contents of the ninety-nine multiplication table as follows, prompting:

  • 2 layers of loops, the outer layer controls the rows, and the inner layer controls the columns

  • You can use the range statement to get a sequence of numbers for a for loop

  • The maximum range of the inner for loop depends on the number of the current outer loop

Reference Code:

 
 
 
 

"""
Demonstration for loop printing ninety-nine multiplication table
"""

# Control the number of rows through the outer loop
for i in range(1, 10):
# Control the data of each row through the inner loop
for j in range(1, i + 1):
# Output the content of each line in the inner loop
print(f"{j} * {i} = {j * i}\t", end='')

# The outer loop can output a carriage return
print()

Loop interruption: break and continue

learning target

  • Master the use of continue and break keywords to control loops

Whether it is a while loop or a for loop, specific operations are performed repeatedly.

In the process of this repetition, there will be some other situations that make us have to:

  • Temporarily skip a cycle and go directly to the next cycle

  • Exit the loop early, do not continue

For this scenario, Python provides continue and break keywords to temporarily skip and directly end the loop.

continue

First of all, let us learn the first continue keyword. The function of the continue keyword is to interrupt this loop and go directly to the next one. At the same time, it can be used in for and while loops, and the effect is the same.

We simulate a scenario:

Every day to confess to Xiaomei 

Send three meals a day until success 

Look at Xiaomei's face when delivering dinner every day, if you are not happy today, you will not deliver, and continue tomorrow 

Okay, let's first look at a piece of code briefly. In the PPT, there is a simple code placed in a loop. There are statement 1 and statement 2. There is a continue between them. The effect of continue is to interrupt this loop, so in the code During the running process, after we execute statement 1, when we execute to continue, we will skip this cycle directly, and then proceed to the next time, that is our statement 2, it will not execute Okay, so for the keyword continue, its application scenario is also very simple, that is, in the loop, we will temporarily end this loop for some reason, and go directly to the next scenario.

 
 
 
 

for i in range(1,101):
print(f"Pursue Xiaomei on the {i} day, insist on...")
print("Send Xiaomei breakfast, love it")
print("Send Xiaomei Lunch, compare your heart")
if input(f"Xiaomei's mood today seems to be (0 good mood, 1 bad mood)")=='1':
print("Xiaomei is in a bad mood, no dinner, retreat.. ....")
print()
continue
print("Send Xiaomei dinner, send Xiaomei home and confess her love")
print()

Output results, when inputting 0 or 1, there will be different conclusions

 
 
 
 

The first day of chasing Xiaomei, insist...
Send Xiaomei breakfast, compare your heart
Send Xiaomei lunch, compare your heart
Today Xiaomei’s mood is like (0 good mood, 1 bad mood) 1
Xiaomei is in a bad mood , No more dinner, retreat...

the second day of pursuing Xiaomei, insist...
give Xiaomei breakfast, Bixin
send Xiaomei lunch, Bixin
Today Xiaomei's mood seems to be (0 Good mood, 1 bad mood) 0
Send Xiaomei dinner, send Xiaomei home and confess her love

The third day of chasing Xiaomei, insist...
Send Xiaomei breakfast, Bixin
send Xiaomei lunch, compare Heart
Xiaomei’s mood today seems to be (0 good mood, 1 bad mood)

Application of continue in nested loop

The continue keyword can only control: the loop it is in is temporarily interrupted 

As shown in the figure below: continue can only control the for loop numbered 1 on the left and has no effect on the for loop numbered 2

break

The break keyword is used to: end the loop directly 

break can be used in: for loop and while loop, the effect is the same

Every day to confess to Xiaomei 

Send three meals a day until success 

One day Xiaomei said, don't bother me anymore, and I won't pester her anymore 

Let's simulate the process of pursuing Xiaomei through code. (Take the for loop as an example, the effect of the while loop is the same) Use the input statement to determine Xiaomei's mood today (0 means a good mood, 1 means a bad mood)

 
 
 
 

for i in range(1,101):
print(f"Pursue Xiaomei on the {i} day, insist on...")
print("Send Xiaomei breakfast, love it")
print("Send Xiaomei Lunch, compare your heart")
if input("If you are Xiaomei, please tell me whether you clearly refused (0 to observe and observe, 1 is not appropriate to reject)") == '1': print("Xiaomei rejected
me , I will not pursue Xiaomei in the future. TT")
break
print("Send Xiaomei dinner, send Xiaomei home and confess her love")
print()

Output result:

 
 
 
 

The first day of chasing Xiaomei, insist...
Send Xiaomei breakfast, compare your heart
Send Xiaomei lunch, compare your heart
If you are Xiaomei, please tell me whether you clearly refuse (0 observe again, 1 Inappropriate to refuse) 0
Send Xiaomei dinner, send Xiaomei home and confess her

love The second day of pursuing Xiaomei, insist...
Send Xiaomei breakfast, compare your heart
Send Xiaomei lunch, compare your heart
if you It's Xiaomei, please tell me whether you clearly refuse (0 to observe again, 1 not appropriate to refuse) 1
Xiaomei rejected me, and I will not pursue Xiaomei in the future. TT

process ended with exit code 0

Application of break in nested loop

The break keyword can also only control: the loop it is in is permanently broken 

break can only control the loop numbered 1 in the figure below to the loop numbered 2, and has no effect

Comprehensive case

learning target

  • Based on the learned cycle knowledge, complete the salary payment case

A certain company has an account balance of 1W yuan and pays wages to 20 employees.

  • Employees numbered from 1 to 20, starting from number 1, receive wages sequentially, and each person can receive 1,000 yuan

  • When receiving salary, the finance judges the employee's performance score (1-10) (randomly generated), if it is lower than 5, no salary will be paid, and the next one will be replaced

  • If the salary has been paid, stop paying the salary.

hint:

  • continue is used to skip employees, and break directly ends the salary payment

  • If judges the balance, don’t forget that after the salary is paid, the balance will be reduced by 1000

Output result:

 
 
 
 

Employee 12, performance score 3, less than 5, no salary, next.
Employee 13, performance score 1, less than 5, no salary, next.
Employee 14, performance score 4, less than 5, no salary, next.
Pay employee 15 a salary of 1,000 yuan, and the balance of the account is 2,000 yuan. Pay
employee 16 a salary of 1,000 yuan, and the balance of the account is 1,000 yuan.
Employee 17 has a performance score of 2. If it is lower than 5, no salary will be paid. Next.
Pay employee 18 a salary of 1,000 yuan, and the balance of the account is 0 yuan.
The salary has been paid, and he will receive it next month.

Reference Code:

 
 
 
 

money = 10000
for i in range(1,21):
import random
score = random.randint(1,10)
if score < 5:
print(f"employee {i}, performance score {score}, lower than 5, no Pay salary, next one.")
continue
else:
money -= 1000
print(f"Pay employee {i} a salary of 1000 yuan, and the account balance still has {money} yuan")
if money == 0:
print("Salary It's over, let's get it next month.")
break

Guess you like

Origin blog.csdn.net/Blue92120/article/details/130607187