python input函数

时间:2022-07-23
本文章向大家介绍python input函数,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Evacloud

  • 对于python的input函数需要从python2和python3两方面讲。
  • 对于python3,通过input函数输入的所有内容都会作为str类型的字符串变量传入,只需要使用int和float进行强制类型转换就可以。
# python3
d=float(input('Please enter what is your initial balance: n'))
p=float(input('Please input what is the interest rate (as a number): n'))
Please enter what is your initial balance:
50000
Please input what is the interest rate (as a number):
2.3
  • 对于python2,input函数可以识别输入的是int还是float,但是String类型的一定要""引号引起来,否则会出现错误。
# python2
>>>a = input("input:")
input:123                  # 输入整数
>>> type(a)
<type 'int'>               # 整型
>>> a = input("input:")
input:"runoob"           # 正确,字符串表达式
>>> type(a)
<type 'str'>             # 字符串
>>> a = input("input:")
input:runoob               # 报错,不是表达式,输入的runoob必须用括号括起来
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'runoob' is not defined
<type 'str'>
  • python2中的raw_input() 函数和python3中的input函数是一样的使用方法,将命令行的输入都会视为string类型。
# python2
>>>a = raw_input("input:")
input:123
>>> type(a)
<type 'str'>              # 字符串
>>> a = raw_input("input:")
input:runoob
>>> type(a)
<type 'str'>              # 字符串
>>>