Python教程(2.5)——控制台输入

写Python程序时,你可能希望用户与程序有所交互。例如你可能希望用户输入一些信息,这样就可以让程序的扩展性提高。

这一节我们来谈一谈Python的控制台输入。

输入字符串

Python提供一个叫做input()的函数,用来请求用户输入。执行input()函数时,程序将会等待用户在控制台输入信息,当用户输入换行符(即enter)时,返回用户输入的字符串。

例如:

>>> name = input()

这将会等待用户输入一行信息。注意接下来的一行开头处没有>>>命令提示符,因为>>>是指示用户输代码的,这里不是代码。

具体例子(输入的字符串为Charles,你也可以输入别的):

>>> name = input()
Charles
>>> print('You entered:', s)
You entered: Charles

但这里也有一个问题:不了解程序的用户,看见程序等待输入,不知道要输入什么。如果有提示文字不就更好了吗?如果你学过其它编程语言,你可能会这样写:

print('Enter your name:')
name = input()

然而Python提供了更简洁的写法:input()可以接受一个参数,作为提示文字:

>>> name = input('Enter your name: ')

这样,等待输入就变成这个样子了(仍以Charles为例):

Enter your name: Charles

一个完整的例子:

>>> fname = input('Enter your first name: ')
Enter your first name: Charles
>>> lname = input('Enter your last name: ')
Enter your last name: Dong
>>> print('Your name: %s, %s' % (lname, fname))
Your name: Dong, Charles

输入数字

那输入数字呢?你可能会想这么做:

>>> height = input('Enter your height, in centimeters: ')

然后输出:

>>> print('You\'re', height, 'cm tall.')

也没有问题。

但如果这样写:

>>> print('You\'re 1 cm taller than', height - 1, 'cm.')

你会得到:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'int'

注意最下面一行:

TypeError: unsupported operand type(s) for -: 'str' and 'int'

意思是说,-两边的参数分别是str和int,而-运算符不能用在这两种类型之间!

原来,input()返回的是一个str,返回值被赋给height,因此height也是str类型。height-1就是str和int进行减法了。

那怎么办呢?联系之前说的类型转换知识,把input()的返回值转换成我们所需要的int类型就可以了:

>>> height = int(input('Enter your height, in centimeters: '))

现在再试一下,是不是没有问题了。

输入非str变量的格式:

var = type(input(text))

var为输入变量,type为要输入的类型,text为提示文字。

不过这里还有一个小问题:无法在一行输入多个数字。这个问题将在后面解决。

小结

1. 使用input()进行输入。

2. 对于非字符串类型,需要进行转换,格式为type(input(text))。

练习

1. 要求用户输入身高(cm)和体重(kg),并输出BMI(Body Mass Index)。BMI=体重/(身高**2),体重单位为kg,身高单位为m。下面是一个例子:

Enter your height, in cm: 175
Enter your weight, in kg: 50
Your BMI: 16.3265306122449

注意输入的身高需要转换成以m为单位。

上一篇:Redis学习第二课:Redis String类型及操作


下一篇:android开发布局文件imageview 图片等比例缩放: