"Learning Python with You Hand in Hand" 19-Summary of the first stage

In the last article "Learning Python with You Hand in Hand" 18-loop statement for , we learned the last control flow statement, and at the same time ended a stage of learning task.

In this article, we will make a summary of the content of the previous 18 articles, so that everyone can understand its knowledge framework and grasp the key content. Finally, a more complicated example will be used to apply and practice what we have learned before.

1. Introduction to Python

In the first article, we introduced the language of Python through several advantages and features of Python. Believe that these characteristics, you will have more or less experience in later learning. Those who haven't studied yet can reach it directly by clicking the link below.

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

2. Software installation and configuration

After that, we used 3 articles to introduce to you Python, integrated development environment (IDE)-PyCharm, and the installation, configuration and use of Jupyter Notebook, which we use most later. After a period of study and the writing of the "rock, paper, scissors" game, the use of the software should no longer be an obstacle for everyone to learn. However, please continue to learn about and explore the various functions of the software in the following study.

"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" 5-Jupyter Notebook

3. Open the door of Python

By learning the print() function, we printed the first sentence of learning Python "Hello World!". Because the print() function is the most basic output method of Python, including flexible adjustment of its parameters, it will help us to achieve diversified output in the future.

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

4. String

In this stage, the content that takes up the most space is the introduction of the string. From this, everyone not only learned the various methods of string identification, retrieval, slicing, operations, functions, and formatted output, but also felt the power of Python. Just a small string can derive such powerful functions. It can be said that there are only things we can't think of, nothing Python can't do!

"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

5. Numbers and operations

Both numbers and strings belong to Python's scalar type, and they are essential application objects in writing programs. Through the learning of arithmetic operations, assignment operations, comparison operations, logical operations, member operations, identity operations, bit operations, etc., it also lays the foundation for us to learn control flow statements later.

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

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

6. Interactive input

In addition to the output learned in the fourth article, the most widely used method we use is input. Only through a complete cycle of input, execution, and output, can we interact with the computer.

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

7. Control flow

Before learning control flow statements, all our programs are executed in the order from top to bottom, and each statement is executed only once, so this cannot be called control, but can only be called "pipeline". And when we learn the control flow statement, we can really control the statement, through conditions to control whether it is executed, looped or terminated. The improvement of language control ability will inevitably make our programs richer, more flexible and simplified.

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

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

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

"Learning Python with You Hand in Hand" 18-loop statement for

In addition to the above content, we also used PyCharm to write a fun Python game program-rock, paper, scissors in several articles on control flow statements. At present, the version of the game has been updated to V3.1. You can download the latest version of the PyCharm program file of the game for free by following the "Yishuo Python" official account and replying to the keyword "Hand 17".

Finally, we use a slightly more complicated program as our application case at this stage to help everyone review the knowledge points learned in the past and apply them to practice.

The program we are going to write this time is also a game program called "Guess the Number". This game is a feature of Wenquxing that I used when I was in school. I don’t know if you have played it before (Is it exposed to age...). Because its rules are simple, easy to understand, and can be implemented without particularly complex functions and methods, it is especially suitable for our stage summary case.

Next, first introduce the rules of this game.

The computer randomly generates 4 non-repeated numbers from 0 to 9, and the player also enters the 4 non-repeated numbers from 0 to 9 as the guessing numbers, and compares them with the numbers generated by the computer one by one:

If the number is the same and the position is the same, record 1 A;

If the number is the same but the position is different, record 1 B;

If the numbers are different, it is not recorded.

After the player enters the numbers in each round, the computer judges each number according to the above rules and outputs the result in the form of 1A0B, 2A2B. If the number and position entered by the player are exactly the same as the number and position generated by the computer, the result of 4A0B is output and the victory is won.

According to the rules of the game, we have the following key steps when writing programs:

1. The computer generates 4-digit non-repeating numbers, and the difficulty lies in "not repeating". If it is repeatable, we can directly generate a four-digit number. If it cannot be repeated, it is necessary to use a random function to not repeat selection in a set. Here we will use a random function that we haven't touched before, but it is recommended that you first use the Internet to search to see if you can find a function that implements this function.

2. The player enters 4 unique numbers. If you don't consider the player's input error, this step is very simple, as long as the input () prompts for input. But for the integrity of the game, we have designed three detection conditions for the input content in the program. If the input rules are not met, the input must be repeated. It is easy for everyone to re-enter what sentence to use, but you can first think about what these three rules are and how should they be implemented?

3. Compare the numbers bit by bit and output the result. To complete this step, everyone has to consider how to compare numbers and their positions. The final program statement is very concise, and I can remind you to use the function of strings. String? Isn't it compared to numbers, why use strings? Because you want to compare "bit by bit" instead of comparing entire numbers, strings are a better way to deal with them. Therefore, if you have been thinking about comparing numbers with numbers in the first few steps, you may have to adjust it slightly.

4. In order to increase the gameplay and to allow us to practice using loops more, a counting function has been added to the game. This should not be difficult.

The above are some ideas and key points of writing this game program. I hope that you can think about and try how to write this program based on these key points. It doesn't matter if there are errors at the beginning, just modify and adjust a few times. If it doesn't work, look at the following code example and compare it with your own program.

In order to facilitate everyone's reading and understanding, in the following example, each piece of code is explained in the form of comments. The final PyCharm file can also be downloaded for free by following the "Yishuo Python" official account and replying to the keyword "Hand 19".

# 因为要使用随机函数,需要先导入随机函数库
import random
​
# 使用sample()函数,随机生成4位不重复数字字符串组成的列表
computer_lst = random.sample(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], 4)
​
# 使用join()函数,将列表元素连接成字符串
computer_num = str.join('', computer_lst)
​
# 为进入循环,设定的初始条件
result = '0A0B'
​
# 竞猜次数初始值
times = 0
​
# 如果答案不正确,通过循环连续竞猜
while result not in '4A0B':
​
    # 记录竞猜次数
    times += 1
​
    # 为进入循环,设定的初始条件
    user_input_isdigit, user_input_is4, user_input_isnotduplicate = False, False, False
​
    # 如果游戏者的输入不符合要求,提示重新输入
    while not (user_input_isdigit and user_input_is4 and user_input_isnotduplicate):
​
        # 游戏者输入四位数字,并将其转换成字符串
        user_input = str(input("请连续输入0~9中的4位不同数字:"))
​
        # 1、检测游戏者输入内容是否都是数字
        user_input_isdigit = user_input.isdigit()
​
        # 2、检测游戏者输入内容是否是4位
        user_input_is4 = len(user_input) == 4
​
        # 3、检测游戏者输入内容是否不包含重复数字
        user_input_isnotduplicate = True
​
        # 如果存在任意一个重复的情况,user_input_isnotduplicate的值就为False
        for i in range(3):
            for j in range(i - 3, 0, 1):
                if user_input[i] == user_input[j]:
                    user_input_isnotduplicate = False
​
        # 如果存在输入不符合要求的情况,提示重新输入
        if not (user_input_isdigit and user_input_is4 and user_input_isnotduplicate):
            print("不符合输入规则,请重新输入。")
​
    # 将A、B个数归零
    A, B = 0, 0
​
    # 逐位进行对比
    for i in range(4):
​
        # 如果位置和数字都一致,A的数量加1
        if user_input[i] == computer_num[i]:
            A += 1
​
        # 如果输入的数字包括在内,B的数量加1
        if user_input[i] in computer_num:
            B += 1
​
    # B - A得到数字正确但位置错误的数量,同时组合成结果字符串
    result = str(A) + 'A' + str(B - A) + 'B'
​
    # 如果判断正确,输出结果,循环结束,否则提示继续竞猜,使用else可以避免最后还输出继续竞猜的提示
    if result == '4A0B':
        print("这是您第{}次竞猜。您竞猜的数字是:{},竞猜结果为:{}。恭喜您!猜对了。".format(times, user_input, result))
        print('\n', '*' * 65, '\n', sep='')
        break
    else:
        print("这是您第{}次竞猜。您竞猜的数字是:{},竞猜结果为:{}。很遗憾,请继续竞猜。".format(times, user_input, result))
        print('\n', '*' * 65, '\n', sep='')

How is it, have you already played this game? This game is different from the "Rock, Paper, Scissors" game. It requires a test of IQ, and it may be addictive.^^

While playing, don’t forget everyone, our goal is to learn Python, and we are not playing Wenquxing, we are the designers of the program! So, here is another question for everyone to think about. How can we modify the program so that we can see the answer directly and guess the right one at a time? The answer will also be announced in the next article.

At this point, we have completed the first stage of learning Python. Do you feel that you have made a small difference? If you think you have gained something, I hope you can share it more and share it so that more friends can see the articles in the series of "Learning Python with You Hand in Hand", so that more people can join the team of Python learning, which is a little bit for me. Little support.

Thank you all in advance!

Starting from the next article, we will learn Python data structures, including lists, tuples, dictionaries and sets, 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

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

"Learning Python with You Hand in Hand" 18-loop statement for

For Fans: Follow the "Also Say Python" official account and reply "Hand 19" to 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/98851911