"Learning Python with You Hand in Hand" 17-the end of the loop

In the previous article "Learning Python with You Hand in Hand" 16-loop statement while , we learned how to use the while loop and applied the while loop to realize the loop operation of the "rock, paper, scissors" game.

Although this version is much more convenient than the first version, it still lacks the feeling of a game. If we can achieve what we usually call "two wins in three games" or "three wins in five games", it would be great. So, today we will learn a new method to see if this method can be used to achieve the function of multiple games.

Today, we are going to learn a method called the termination of the cycle. The termination mentioned here is not an "abnormal" termination formed by clicking the suspend button after forming an infinite loop, but pre-setting the termination requirements in the program according to the needs of program design, when the program meets certain conditions , "Normal" termination.

There are two ways to terminate the loop, break and continue. They are not only applicable to while loop statements, but also in the for loop that we will talk about in the next article.

The function of break is to terminate the entire loop, but it only terminates the smallest loop structure where the break is located. If in a nested loop, break only exists in one of the sub-loops, then only this sub-loop is terminated. If the break exists in a higher-level loop, then the loop and the sub-loops nested within the loop will be terminated.

The role of continue is different from break, it only terminates the execution of the remaining statements in the current loop. That is, in the current loop, the statements after continue are no longer executed. But as long as the judgment condition is true, the remaining loop is still executed.

The above description may be more convoluted, but the flow chart will be used below. But before that, I need to add one more thing to draw the clearest flow chart.

Because both break and continue must be written in the execution statement, so theoretically each loop will run to these two termination statements. If this is the case, all the loops will not be able to break or continue. Therefore, when using these two termination statements, they will be nested in an if statement, that is, only when a certain condition is met, the break or continue will be triggered.

Based on this idea, I will show you the flow charts of break and continue respectively. In each flow chart, "a complete execution statement block" is an execution statement in the previous flow chart, but it is expanded because of the addition of if statements, so that everyone can see how break and continue work .

In the break flowchart , when the judgment condition 1 is true, it starts to enter the loop. In the execution statement block, when the judgment condition 2 is false, the statement Part 2 is executed, and then the loop continues. When the judgment condition 2 is true, break will be executed and the whole loop will end.

In the continue flowchart , also when the judgment condition 1 is true, it starts to enter the loop. In the execution statement block, when the judgment condition 2 is false, the statement Part 2 is executed, and then the loop continues. When the judgment condition 2 is true, continue will be executed, and then the loop will continue, only when the execution statement Part 2 in the second loop is not executed (equivalent to skip execution of statement 2).

Therefore, the function of continue is to delete the remaining statements in this loop, and the function of break is to delete the remaining loops in the entire loop. Comparing the two examples, everyone can understand the difference.

In [1]: a = 0
        while a <= 10:
            a += 1
            print("a={}时,".format(a), end='')   # 修改print()的end参数,可以实现不换行打印
            if a == 6 or a == 9:   # a==6或9的时候,循环终止
                print("即将运行break,循环终止。")
                break
            print("没有运行break,循环继续。")
        print("循环结束。")
Out[1]: a=1时,没有运行break,循环继续。
        a=2时,没有运行break,循环继续。
        a=3时,没有运行break,循环继续。
        a=4时,没有运行break,循环继续。
        a=5时,没有运行break,循环继续。
        a=6时,即将运行break,循环终止。
        循环结束。
​
In [2]: a = 0
        while a <= 9:
            a += 1
            print("a={}时,".format(a), end='')   # 修改print()的end参数,可以实现不换行打印
            if a == 6 or a == 9:   # a==6或9的时候,当次循环终止
                print("即将运行continue,当次循环终止,不会打印下面那句话,但循环继续。")
                continue
            print("没有运行continue,会打印这句话,循环继续。")
        print("循环结束。")
Out[2]: a=1时,没有运行continue,会打印这句话,循环继续。
        a=2时,没有运行continue,会打印这句话,循环继续。
        a=3时,没有运行continue,会打印这句话,循环继续。
        a=4时,没有运行continue,会打印这句话,循环继续。
        a=5时,没有运行continue,会打印这句话,循环继续。
        a=6时,即将运行continue,当次循环终止,不会打印下面那句话,但循环继续。
        a=7时,没有运行continue,会打印这句话,循环继续。
        a=8时,没有运行continue,会打印这句话,循环继续。
        a=9时,即将运行continue,当次循环终止,不会打印下面那句话,但循环继续。
        a=10时,没有运行continue,会打印这句话,循环继续。
        循环结束。

You can compare the above two examples. After executing break, the following loop will not run, and the whole program will end. After executing continue, the following loop will continue, but the two loops of continue (a==6 and a==9) will not be executed.

Below, I will explain a little bit that was not explained in depth in the previous article.

In the first instance in the previous article, did you think that else did not work? Because as long as it is not an infinite loop, the statement after the else will be executed. It is completely unnecessary to use it as a part of the loop structure. Putting the execution statement outside the loop structure is the same, and it must be executed.

In fact, in that instance, it is indeed possible to achieve the same effect without using else. But is else really useless at all? This is definitely not true. Since the else is designed, there must be a place for it to play a role.

For example, in the example we just demonstrated break, if the last sentence of print ("The loop ends.") is used as the execution statement after the else, it is not contingent or absent. Because the function of break is to terminate the entire while loop, and else is part of the while loop. If you put print("The end of the loop.") behind the else, that is, inside the entire loop structure, it will be terminated because of the operation of break, which is different from putting it outside the loop structure.

In [3]: a = 0
        while a <= 10:
            a += 1
            print("a={}时,".format(a), end='')   # 修改print()的end参数,可以实现不换行打印
            if a == 6 or a == 9:   # a==6或9的时候,循环终止
                print("即将运行break,循环终止。")
                break
            print("没有运行break,循环继续。")
        else:
            print("循环结束。")   # 整个while循环被终止,此行语句就不会被执行了
Out[3]: a=1时,没有运行break,循环继续。
        a=2时,没有运行break,循环继续。
        a=3时,没有运行break,循环继续。
        a=4时,没有运行break,循环继续。
        a=5时,没有运行break,循环继续。
        a=6时,即将运行break,循环终止。

At this point, we have finished the introduction to the termination of the loop. Let's see if we can apply what we have learned today to let our game achieve multiple games.

Let's analyze this problem first.

First of all, the purpose of the game is to achieve multi-game winning, that is, the person who reaches a certain number of wins first gets the final victory. So the total number of matches is not what we care about, that is, not only can it not be achieved by controlling the total number of cycles, but it is necessary to let the loop continue indefinitely (for example, it is always a tie), and use other methods to terminate the loop.

Since the person who reaches a certain number of victories first gets the final victory, then this number is what we should pay attention to. So what we need to record and set it as a judgment condition is the number of wins (the number of draws is not what we care about).

Finally, after reaching the specified number of victories, what the program has to do is terminate, not continue the loop, so we should use the break loop instead of the continue loop.

Now, according to this idea, we will perfect our game program.

In [4]: import random   # 因为要使用随机函数,需要先导入随机函数库
 
        # 设置游戏胜利的条件,使游戏在某一方胜利次数先达到该次数时,游戏结束
        # 当次数设置为2的时候就是我们平时说的“三局两胜”,因为我们平时也不统计平局次数
        times = 2
        
        # 比赛开始前,将游戏者胜利次数、电脑胜利次数、打平的次数都设置为零
        user_win, computer_win, draw = 0, 0, 0
        
        # 因为设置了break条件,所以可以将while的判断条件设置为永远为真
        while 1 == 1:
        
            # 交互式输入过程,使用input()函数
            user = input("请输入您要出的拳(石头、剪刀、布):")
            
            # 使用choice()函数,实现在序列中随机选取一个元素,做为电脑出的拳
            computer = random.choice(['石头', '剪刀', '布'])
            
            # 以下是程序处理过程,直接按照游戏规则进行判断,根据判断结果进行输出
            
            # 把所有游戏者赢的情况列举出来,任何一种情况出现,就输出游戏者胜利
            if (user == '石头' and computer == '剪刀') or (user == '剪刀' and computer == '布')\
                    or (user == '布' and computer == '石头'):
                user_win += 1   # 游戏者胜利次数累加
                print("您出的是:{},电脑出的是:{}。恭喜,您赢了!".format(user, computer))
                print("您总共赢了{}局,输了{}局,平了{}局。".format(user_win, computer_win, draw))   # 记录游戏胜负次数
                
            # 打平的情况最容易描述,所以作为一个判断条件
            elif user == computer:
                draw += 1   # 打平次数累加
                print("您出的是:{},电脑出的是:{}。打平了!".format(user, computer))
                print("您总共赢了{}局,输了{}局,平了{}局。".format(user_win, computer_win, draw))   # 记录游戏胜负次数
                
            # 其它情况就是游戏者输的情况,因为描述比较复杂,放在其它情况里,就不用写很复杂的判断条件了
            else:
                computer_win += 1   # 电脑胜利次数累加
                print("您出的是:{},电脑出的是:{}。很遗憾,您输了!".format(user, computer))
                print("您总共赢了{}局,输了{}局,平了{}局。".format(user_win, computer_win, draw))   # 记录游戏胜负次数
                
            # 为了使交互部分更加友好,对每次的输入输出内容进行分行
            print("=" * 40)
            
            # 判断是否达到游戏结束的条件,如果达到了,游戏终止,否则游戏继续
            if user_win == times or computer_win == times:
                break
                
        # 使用一个三元运算,判断游戏的最终结果的输出内容
        winner = "恭喜您,您取得了最终的胜利!" if user_win == times else "很遗憾,电脑取得了最终的胜利!"
        
        # 打印游戏的最终结果,因为在执行语句块中包括break,所以不能使用else
        print('\n', '*' * 28, sep='')   # 隔行输出结果,同时修改print的sep参数
        print('*', winner, '*')
        print('*' * 28)
​
Out[4]: 请输入您要出的拳(石头、剪刀、布):石头
您出的是:石头,电脑出的是:剪刀。恭喜,您赢了!
您总共赢了1局,输了0局,平了0局。
========================================
​
Out[5]: 请输入您要出的拳(石头、剪刀、布):剪刀
您出的是:剪刀,电脑出的是:剪刀。打平了!
您总共赢了1局,输了0局,平了1局。
========================================
​
Out[6]: 请输入您要出的拳(石头、剪刀、布):布
您出的是:布,电脑出的是:布。打平了!
您总共赢了1局,输了0局,平了2局。
========================================
​
Out[7]: 请输入您要出的拳(石头、剪刀、布):石头
您出的是:石头,电脑出的是:剪刀。恭喜,您赢了!
您总共赢了2局,输了0局,平了2局。
========================================
​
****************************
* 恭喜您,您取得了最终的胜利!*
****************************

In this 3.0 version, we have made the following improvements to the program:

1. Increase the statistical function of each game result and output it;

2. Set the conditions for the victory of the game. When a party reaches the specified number of wins, the game ends;

3. Output the final result of the game and use special symbols to modify it.

Finally, I will show you the screenshot of this update, hoping to help you learn.

 

After two versions of improvements, our "Rock, Paper, Scissors" game program has a certain "competitive value", but there are still some problems. For example, if we do not enter one of rock, scissors, or cloth, and enter other content, although the program will not report an error, it will be regarded as a situation other than a victory and a tie, so it will be judged as a computer victory.

So, how can this bug be corrected? In fact, as long as the while statement is used, it can be done with two lines of code. You can think about how to do it. This updated content has been shared on the network disk as the V3.1 version of the game. You can get the latest code of the "Rock, Paper, Scissors" game by following the official account and replying to keywords.

In addition, you can also try to replace the computer with another player to achieve a competition between the two. The more difficult thing is to challenge the "rock, paper, scissors" game played by three people. How should the result be determined?

In short, around this game, there are many functions that we can develop ourselves. It is through this continuous experimentation and improvement that we can consolidate what we have learned and improve our ability to think about algorithms.

The above is the introduction and application of the loop termination method. In the next article, we will introduce another loop statement—for loop, so stay tuned.

 

 


Thanks for reading this article! If you have any questions, please leave a message and discuss together ^_^

Welcome to scan the QR code below, follow the "Yesu Python" public account, read other articles in the "Learning Python with You Hand in Hand" series, or click the link below to go directly.

"Learning Python with You Hand in Hand" 1-Why learn Python?

"Learning Python with you hand in hand" 2-Python installation

"Learning Python with You Hand in Hand" 3-PyCharm installation and configuration

"Learning Python with You Hand in Hand" 4-Hello World!

"Learning Python with You Hand in Hand" 5-Jupyter Notebook

"Learning Python with You Hand in Hand" 6-String Identification

"Learning Python with You Hand in Hand" 7-Index of Strings

"Learning Python with You Hand in Hand" 8-String Slicing

"Learning Python with You Hand in Hand" 9-String Operations

"Learning Python with You Hand in Hand" 10-String Functions

"Learning Python with You Hand in Hand" 11-Formatted Output of Strings

"Learning Python with You Hand in Hand" 12-Numbers

"Learning Python with You Hand in Hand" 13-Operation

"Learning Python with You Hand in Hand" 14-Interactive Input

"Learning Python with You Hand in Hand" 15-judgment statement if

"Learning Python with You Hand in Hand" 16-loop statement while

For Fans: Follow the "also said Python" public account, reply to "hand 17", you can download the sample sentences used in this article for free.

Also talk about Python-a learning and sharing area for Python lovers

 

Guess you like

Origin blog.csdn.net/mnpy2019/article/details/98851057