[Basic knowledge of python] 3.input() function

Preface

In the previous study, we learned to use the print() function to issue simple commands to the computer, began to come into contact with different types of data in Python, and learned to use if conditional judgment statements to implement the primary logic of communicating with the computer.

After these studies, are you one step closer to understanding Python? Have you ever begun to feel that the cold computer in the past seems to have become friendly through communication with you?

However, just mastering Python coding is not enough. If we want to go further, we must master the code logic of Python, use correct [data] and reasonable [logic] to construct commands, and finally we need to [respond] to the computer and [enter] our own information.

And this [response] action of transmitting information is our focus today - the input() function, which will complete your first interactive communication with Python and produce incredible magic.

So, what are you waiting for? Let's start the magical journey quickly!

input() function

In today's course, you will receive an admission letter from Hogwarts School of Witchcraft and Wizardry. This admission letter will lead you to use the input() function to open a new chapter of "two-way communication" with the computer.

Now, it’s time for you to choose. Please run the [Run] button on the left side of the code block below. In the [Terminal], first [enter] the number you selected, and then press the Enter key.

import time

print('亲爱的同学:')
time.sleep(1)

print('我们愉快地通知您,您已获准在霍格沃茨魔法学校就读。')
time.sleep(2)

print('随信附上所需书籍及装备一览。')
time.sleep(1)

print('学期定于九月一日开始。')
time.sleep(1)

print('鉴于您对魔法世界的不熟悉,')
time.sleep(1)

print('我们将指派魔咒学老师——吴枫教授带您购买学习用品。')
time.sleep(2)

print('我们将于七月三十一日前静候您的猫头鹰带来的回信。')
time.sleep(2)

print('校长(女)米勒娃·麦格谨上')
time.sleep(1)

print('那么,您的选择是什么? 1 接受,还是 2 放弃呢?')
time.sleep(2)

choice=input('请输入您选择的数字:')

if choice =='1':
    print('霍格沃茨欢迎您的到来。')

else:
    print('您可是被梅林选中的孩子,我们不接受这个选项。')

operation result:

亲爱的同学:
我们愉快地通知您,您已获准在霍格沃茨魔法学校就读。
随信附上所需书籍及装备一览。
学期定于九月一日开始。
鉴于您对魔法世界的不熟悉,
我们将指派魔咒学老师——吴枫教授带您购买学习用品。
我们将于七月三十一日前静候您的猫头鹰带来的回信。
校长(女)米勒娃·麦格谨上
那么,您的选择是什么? 1 接受,还是 2 放弃呢?
请输入您选择的数字:1
霍格沃茨欢迎您的到来。

See, this is your first interactive communication with the computer using the input() function.

The key to achieving true human-machine interactive communication is: there is going and there is going. For example, if the principal asks you if you want to come to Hogwarts to learn magic, you need to enter a question command into the program: Do you want to come to Hogwarts?

After the program receives the order, it will immediately display the principal's question word-for-word on your computer screen, asking: Do you want to come to Hogwarts?

Then, the process of human beings using the keyboard to provide instructions to the computer, and then using the computer to display the questions on the monitor and waiting for the human's answer is implemented through the input() function.

Insert image description here

So, what is the specific usage of the input() function and the logic behind it? In this level, I will defeat the input() function one by one from four angles.

Use of input() function

First, let's take a look at how the input() function is used through a piece of code:


input('请在以下四个选项【格兰芬多;斯莱特林;拉文克劳;赫奇帕奇】中,输入你想去的学院名字:')

The input() function is the input function. For the above example, it requires you to enter the name of the house you want to go to in the following four options [Gryffindor; Slytherin; Ravenclaw; Hufflepuff] in the brackets: 's answer.

So, when you write a question within the brackets of the function, the input() function will display the question as it is on the screen and wait for your answer to this question in the terminal area.

But why do we enter the answer at the terminal? Is it okay not to enter it?

In fact, we can think of the input() function as a door connecting the real world and the code world.

When a question is passed to us from the code world, but we do not answer it, the input() door waiting for input will always be open, waiting for you to send your answer.

When we enter the information, the input() door will be closed and we will continue to execute the following commands.

Next, let’s summarize how to use the input() function:

Insert image description here
Next, let’s experience the magic of the input() function for ourselves:
1. Please add the code

input('请在以下四个选项【格兰芬多;斯莱特林;拉文克劳;赫奇帕奇】中,输入你想去的学院名字:')

Copy it into your own local code box;
2. After clicking Run, enter your choice in the terminal on the right;
3. Press the Enter key after entering the answer.

How about it? After entering the answer and pressing the Enter key, is there nothing else except the information you entered? But the program does not report an error. Why is this?

We have repeatedly emphasized that the code executes commands line by line, so even if the input() function passes and the door is closed, since there are no other commands under the input() function, there will naturally be no results.

However, the answers we entered are not lost, they are stored in the program by the computer.

So, what if I want to find the answer I just entered from the ocean of programs and use it to produce a result, such as expressing that the college welcomes me?

请在以下四个选项【格兰芬多;斯莱特林;拉文克劳;赫奇帕奇】中,输入你想去的学院名字: 拉文克劳
#提出的问题

拉文克劳学院欢迎你,小萌新!
#显示的结果

Let’s not rush into coding yet. According to the old rules, let’s sort out the thinking logic first. First, in order for colleges to be ready to welcome you, they need to know which college you have chosen, so they must first collect information about your favorite college.

Then, the first step in our thinking is to use the input() function to collect information:

input('请在以下四个选项【格兰芬多;斯莱特林;拉文克劳;赫奇帕奇】中,输入你想去的学院名字: ')
#运用input函数搜集信息

However, when I want to splice the collected data with ['Welcome to the college, little cute newbie!'] and print out the results, a problem arises. Although I collected a piece of information using the input() function, how do I retrieve this information from the ocean of programs and perform data splicing?

This involves the second knowledge point of the input() function-the assignment of function results.

Assignment of input() function result

First of all, we can assign values ​​to variables, so that when we want to extract data, we only need to print the variable name directly to wake up the program's memory of the data.

This assignment logic also works in the input() function. We can also achieve the purpose of extracting the input results at any time through assignment. But at a logical level, we need to turn a corner.

For example, take our following string of code as an example:

name = input('请输入你的名字:')
#函数赋值

Although it looks like assigning a value to the input() function, in fact, we assign the execution result of the input() function (the collected information) to the variable name.

In layman's terms, what we put into the name box is not the question asked in the input() function, but the answers of others we collected through the input() function.

This way, no matter what you type in the terminal, no matter how many times your answer changes. As long as it is an answer to the question asked by the input() function, it will be stored in the variable. While waiting for you to print the variable, the answer is extracted and displayed on the display.

In the code world, these information/answers/data displayed on the terminal can be called input values ​​- the content we input to the function.

Now, let’s try it ourselves:

Please assign the result of input('Please enter the name of the house you want to go to among the following four options [Gryffindor; Slytherin; Ravenclaw; Hufflepuff]: ') to name, Then print out the variable name to see if the answer you entered appears. [Key points: assignment, input() function, print() function]

name=input('请在以下四个选项【格兰芬多;斯莱特林;拉文克劳;赫奇帕奇】中,输入你想去的学院名字:')
print(name+'学院欢迎你!')

operation result:

请在以下四个选项【格兰芬多;斯莱特林;拉文克劳;赫奇帕奇】中,输入你想去的学院名字:格兰芬多哈
格兰芬多哈学院欢迎你!

Just now, the information we entered at the terminal - the name of the college (everyone enters different content), is the input value.

At the same time, in order to extract the input value at any time and conveniently, we need to assign the result of the input() function to the variable name.

When we have paved the way to collect information and assigned values ​​to the obtained information, we can proceed to the last step and print the final result.

Next, please show off another wave of operations: 1. To request input, please select the magic item you most want to own among the following options [Mirror of Erised; Time Turner; Flying Broomstick; Invisibility Cloak]:; 2. Add the results Assign the value to the variable magic; 3. Print the result magic+' is the magic I want to have most! '[Key points: assignment, input() function, variable splicing, print() function]

Reference answer:

magic=input('请在以下选项【厄里斯魔镜;时间转换器;飞天扫帚;隐形斗篷】中,选择出你最想拥有的魔法物品:')
print(magic+'是我最想拥有的魔法!')

operation result:

请在以下选项【厄里斯魔镜;时间转换器;飞天扫帚;隐形斗篷】中,选择出你最想拥有的魔法物品:隐形斗篷
隐形斗篷是我最想拥有的魔法!

There is an important point here. When we understand the code, the order of thinking in our brain is to collect information first, and then assign the result of the input() function to the variable.

However, in order to write specifications and prevent missing information, we need to follow the code writing format and assign values ​​to the results of the input() function first.

Insert image description here
Based on the knowledge we have learned previously, how to use the input() function?

First, we need to assign a value to the result of the input() function, then use the input() function to collect information, and finally use the print() function to output the result.

Let’s use another picture to summarize it intuitively.
Insert image description here

Now that we have mastered the comprehensive usage scenarios of the input() function, let’s take a look back at the code for the letter from Hogwarts at the beginning of this level.

print('那么,您的选择是什么? 1 接受,还是 2 放弃呢?')

choice = input('请输入您的选择:')
#变量赋值

if choice == '1':
#条件判断:条件1
    print('霍格沃茨欢迎您的到来。')
#条件1的结果

else:
#条件判断:其他条件
    print('您可是被梅林选中的孩子,我们不接受这个选项。')
#其他条件的结果

So, how was this set of code written?

From a thinking perspective, to put it simply: I give you two choices, you choose one, and then I show you the corresponding result.

Therefore, the first step in the code is to assign a value and ask questions through the input() function.

choice = input('请输入您的选择:')
#变量赋值

In the second step, we need to make a conditional judgment based on the answer: if the answer is 1, the result of condition 1 will be displayed; if other options are selected, the results of other conditions will be displayed.

choice = input('请输入您的选择:')
#变量赋值

if choice == '1':
#条件判断:条件1
    print('霍格沃茨欢迎您的到来。')
#条件1的结果

else:
#条件判断:其他条件
    print('您可是被梅林选中的孩子,我们不接受这个选项。')
#其他条件的结果

The code is finished, but the question arises: why is the variable choice under the if condition the string '1'? If it is not a string format, but an integer 1, what will be the result?

Next, please copy the above code and change the if condition from '1' in string format to 1 in integer format. After clicking Run, enter 1 at the terminal and observe the running results [Tip: Click Run → Enter 1]

choice=input('请输入你的选择:')
if choice==1:
    print('霍格沃茨欢迎您的到来')
else:
    print('您可是被梅林选中的孩子,我们不接受这个选项')

operation result:

请输入你的选择:1
您可是被梅林选中的孩子,我们不接受这个选项

How about it? You entered 1, and the displayed result is the result under the else condition: 'You are the child selected by Merlin, we do not accept this option. '?

Why is this? What we entered is the number 1 in the conditional option? Why can't the corresponding results appear?

Here, we come to the third knowledge point of the input() function:

Data type of input() function

Now, let us first break down this code group line by line from the logic of computer language:

choice = input('请输入您的选择:')
#变量赋值

if choice == 1:
#条件判断:条件1
    print('霍格沃茨欢迎您的到来。')
#条件1的结果

else:
#条件判断:其他条件
    print('您可是被梅林选中的孩子,我们不接受这个选项。')
#其他条件的结果

So, let's first take a look at the assignment statement in the first line of code.

choice = input('请输入您的选择:')
#变量赋值

First, let’s look at it as a whole. What this code means is that it uses the input() function to receive data and assign the data to the variable choice.

Secondly, let’s break it down to see what each part of this line of code represents:

Insert image description here
For the input() function, no matter what answer we enter, whether you enter the integer 1234 or the string "The invisibility cloak is the magic I most want to have", the input value of the input() function (collected Answer), will always be [mandatory] converted to [string] type. (Python3 fixed rules)

Do not believe? Check it with the type() function we learned in the first level?

choice = input('请输入1或2:')
print(type(choice))

operation result:

请输入12:1
<class 'str'>

Isn't it? The integer [1] or [2] we input will be forcibly converted into a string of ['1'] or ['2'].

Therefore, no matter what we enter in the terminal area, the input value of the input() function must be [string].

In this way, since we use the assignment operator [=] to assign the string result of the input() function to the variable choice, this variable must also be of string type.

Insert image description here
Now, we have determined that the data type of the variable choice is string. Next, let's look at the code behind.

Let’s first look at the if conditional statement [if choice==1] in the first block of code and disassemble it:

Insert image description here
Based on the conditional judgment knowledge learned in Level 2, we can interpret the if condition in the first line as: if the variable choice is equal to the integer 1, then execute the result of this if condition.

Insert image description here
Did you find any problem this time? Remember the data type of the variable choice we mentioned when we dismantled the input() function?

In the first variable assignment, the input value of the input() function is a string, and '1' is also a string; but when it comes to the if condition judgment, the if condition becomes [choice == 1] - 1 is gone. Quotation marks are an integer type.

Insert image description here

That's it, because the information we input is always a string, choice is a string type, and 1 is an integer type, of course they cannot be equal, the condition [choice == 1] cannot be established, and we can only perform the following operation else - —Print "You are the child chosen by Merlin. We do not accept this option."

Now, please show your magic. Please change the error statement of the if condition in the following code to the correct one equal to the string type, and run it.

choice = input('请输入您的选择:')
#变量赋值

if choice == 1:
#条件判断:条件1
    print('霍格沃茨欢迎您的到来。')
#条件1的结果

else:
#条件判断:其他条件
    print('您可是被梅林选中的孩子,我们不接受这个选项。')
#其他条件的结果

Reference answer:

choice=input('请输入你的选择:')
if choice=='1':
    print('霍格沃斯欢迎您')
else:
    print('您可是被梅林选中的孩子,我们不接受这个选项')

operation result:

请输入你的选择:1
霍格沃斯欢迎您

Now, we know how to run through the code by modifying the data type of the if condition. Have you learned it?

So, suppose there is a piece of code like the following:

age = 59

choice = input('请你猜一下斯内普教授的年龄:')

if choice == age:
    print('猜对惹~你好厉害! ヽ✿゜▽゜)ノ~~~')

elif choice < age:
    print('斯内普的提示:你猜小了(;´д`)ゞ。。。。')

else:
    print('斯内普的提示:乃猜大了惹(>﹏<)~~')

If you click Run and enter data, you will immediately be given an error message and rubbed on the ground. So, where is the source of the error in Professor Snape's code?

We disassemble it line by line. In the assignment statement of the first line of code, the variable age is of integer type, and the variable choice of the second line is of string type. These two variables cannot be compared due to different types.

How about it, did you answer it correctly? Next, let’s use a picture to deepen it. This is very useful in the future and is also a very important knowledge point:

Insert image description here
In our example, there were only two options. But assuming you have 1, 2, 3, 4... 365 options, regardless of whether the data type conversion is correct or not, typing single quotes one by one is too time-consuming.

Then, we need a simpler and more labor-saving method to change the data types of all input values ​​into integers at once.

Forced conversion of input() function result

But teacher, didn’t you just tell me that the information collected by the input() function is always a string? Can it also be changed to an integer?

That's right, the input value of the input() function can become an integer under certain circumstances. So, do you remember how to convert a string into an integer?

Right? int() is a knowledge point forced type conversion in Level 1, which can forcefully convert a string into an integer.

With the int() function, we can convert the input content into an integer from the source of the input() function.

choice = int(input('请输入您的选择:'))
#将输入值强制转换为整数,并赋值给变量choice

However, this string of code looks like it casts the entire input() function.

But in fact, we perform forced conversion on the result obtained by the input() function, and assign the result of the forced conversion to a variable box named choice.

In this way, even if the if condition is an integer, the program can run accurately.

So, when will we use the forced conversion of the input() function result?

The idea is simple, when the answer you want is a number, such as age:

age = int(input('猜一猜巫师的『法定成年年龄』是几岁,请输入:'))
#将输入的岁数(字符串),强制转换为整数

if age > 17:
#当年龄(整数)大于17(整数)时
    print('哈哈,居然比这个年龄还要小呢!')
#打印if条件下的结果

elif age == 17:
#当年龄(整数)等于17(整数)时
    print('正确!我猜你是个巫师啦~')
#打印if条件下的结果

else:
#当年龄(整数)小于17(整数)时
    print('呜呜,这个年龄~我还是个宝宝呢,正确答案是17岁哦')
#打印else条件下的结果

Another example is when the information that needs to be entered is time, salary or other numbers:

money = int(input('你一个月工资多少钱?'))
#将输入的工资数(字符串),强制转换为整数

if money >= 10000:
#当工资数(整数)大于等于10000(整数)时
    print('土豪我们做朋友吧!')
#打印if条件下的结果

else:
#当工资数(整数)小于10000(整数)时
    print('我负责赚钱养家,你负责貌美如花~')
#打印else条件下

Next, please wave your invisible wings and add another condition to the monthly salary code above: [When the salary is greater than 5,000 and less than 10,000]. Print result: [We are all brick movers. . . ], and write the entire code after adding the conditions in the area below. [Key tip: When three conditions coexist, please use if…elif…else… statements]

Reference answer:

money = int(input('你一个月工资多少钱?'))
#将输入的工资数(字符串),强制转换为整数

if money >= 10000:
#当工资数(整数)大于等于10000(整数)时
    print('土豪我们做朋友吧!')
#打印if条件下的结果

elif 5000 < money < 10000:
#当工资数(整数)大于5000(整数)小于10000(整数)时
    print('我们都是搬砖族。。。')
#打印elif条件下的结果

else:
#当工资数(整数)小于等于5000(整数)时
    print('我负责赚钱养家,你负责貌美如花~')
#打印else条件下的结果

operation result:

你一个月工资多少钱?8000
我们都是搬砖族。。。

Finally, let’s summarize the knowledge points about data type coercion of the input() function:

Insert image description here
So, we have introduced all the knowledge points of the input() function, the focus of this level. Finally, let’s sort out the key points of the input() function.

Summary of input() function knowledge points

Insert image description here
Now, please recall carefully. At this point, do we know how to use the input() function, and combine the variables, assignments, conditional judgments, and forced type conversions we learned before with the input() function? Reviewed and used it again? Have you completed the interactive communication with the computer?

Comprehensive review

At the beginning, we got acquainted with the simplest and most commonly used function in the Python world-the print() function.

Even though this function looks simple, if you dig deeper, you will find that this simplest printing function also has its own secrets. It contains the most basic operation logic in the programming world.

Insert image description here
However, if you want to achieve the purpose of interactive communication with the computer, you also need to master the computer's communication language.

Only when the computer understands what we are saying can it give us the correct feedback.

Insert image description here

Like us humans, the operation of computers also requires formal logic, so in level 2, we mastered the logic of how to communicate with computers.

Insert image description here

With language and logic, we can communicate interactively with computers.

Then, we came to today's level and learned the input() function.

Insert image description here
However, after learning these knowledge points, how can we write a piece of code ourselves, such as a code like the Hogwarts letter? What is the general format of the code group?

Insert image description here
Looking back, after going through these four levels, do you find that you have learned so much without even realizing it? I was exposed to a whole new world.

Come on, you will eventually become the boss of your dreams!

Guess you like

Origin blog.csdn.net/qq_41308872/article/details/132687615