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

写Python程序时,你可能但愿用户与程序有所交互。例如你可能但愿用户输入一些信息,这样就能够让程序的扩展性提升。编程

 

这一节咱们来谈一谈Python的控制台输入。编程语言

 

输入字符串

 

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

 

例如:spa

 

>>> name = input()

 

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

 

具体例子(输入的字符串为Charles,你也能够输入别的):blog

 

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

 

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

 

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

 

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

 

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

 

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

 

Enter your name: Charles

 

一个完整的例子:class

 

>>> 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为单位。

相关文章
相关标签/搜索