如何使用示例通过Python raw_input从键盘获取输入

Python provides different functions and methods in order to get input from user, system, network etc. raw_inputis 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 input

    PROMPT是将在数据输入期间显示的文本

Python 3 (Python 3)

DATA = input('PROMPT')
  • DATA is set to the provided data

    DATA设置为提供的数据
  • PROMPT is the text which will shown during data input

    PROMPT是将在数据输入期间显示的文本

获取并打印年龄示例(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')
Get and Print Age Example
Get and Print Age Example
获取并打印年龄示例

转换为整数(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_inputor inputis 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_inputinput最常用的情况之一。 我们提供一些选择,并根据选择等待输入。 在此示例中,我们将获得用户的年龄范围。

#!/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')
Selection Example
Selection Example
选择例
LEARN MORE  HTTP Status 503 Error Code and How To Fix It?
了解更多HTTP状态503错误代码以及如何解决?

翻译自: https://www.poftut.com/get-input-keyboard-python-raw_input-examples/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值