Python provides different functions and methods in order to get input from user, system, network etc. raw_input
is a method used to get input from user from interactive shell. We will look different use cases for raw_input
for python.
为了提供来自用户,系统,网络等的输入,Python提供了不同的功能和方法raw_input
是一种用于从交互式shell中获取来自用户的输入的方法。 我们将为python寻找raw_input
不同用例。
句法 (Syntax)
The syntax of the raw_input
changes according to python version. We will look for both of them but use Python 3 version in the examples.
raw_input
的语法根据python版本而变化。 我们将查找它们两者,但在示例中使用Python 3版本。
Python 2 (Python 2)
DATA = raw_input('PROMPT')
- DATA is set to the provided data DATA设置为提供的数据
- PROMPT is the text which will shown during data inputPROMPT是将在数据输入期间显示的文本
Python 3 (Python 3)
DATA = input('PROMPT')
- DATA is set to the provided data DATA设置为提供的数据
- PROMPT is the text which will shown during data inputPROMPT是将在数据输入期间显示的文本
获取并打印年龄示例(Get and Print Age Example)
In this example we will simply get the input data which is age. We will print some prompt and get value and than print the provided value. Use following code.
在此示例中,我们将简单地获取输入数据,即年龄。 我们将打印一些提示并获取价值,然后打印提供的价值。 使用以下代码。
#!/usr/bin/python3
data = input('Please enter your age:')
print('You are '+data+' years old')
转换为整数(Convert To Integer)
We may need to convert provided value into integer. We can use int()
in order to convert to integer.
我们可能需要将提供的值转换为整数。 我们可以使用int()
来转换为整数。
#!/usr/bin/python3
data =int( input('Please enter your age:'))
print('You are '+data+' years old')
选择例 (Selection Example)
One of the most used situation for raw_input
or input
is selection examples. We provide some chooses and wait input according to selection. In this example we will get the age range of the user.
选择示例是raw_input
或input
最常用的情况之一。 我们提供一些选择,并根据选择等待输入。 在此示例中,我们将获得用户的年龄范围。
#!/usr/bin/python3
print('1 - Age between 0 and 18')
print('2 - Age between 19 and 35')
print('3 - Age between 35 and 60')
print('4 - Age over 60')
data = int(input('Please enter your age range'))
if(data == 1):
print('Age is between 0 and 18')
elif(data == 2):
print('Age is between 19 and 35')
elif(data == 3):
print('Age is between 35 and 60')
elif(data == 4):
print('Age is over 60')
else:
print('Please provide acceptable value')
翻译自: https://www.poftut.com/get-input-keyboard-python-raw_input-examples/