page contents

Python input()函数:获取用户输入的字符串

input() 是Python的内置函数,用于从控制台读取用户输入的内容。input() 函数总是以字符串的形式来处理用户输入的内容,所以用户输入的内容可以包含任何字符。

input() 函数的用法为:

str = input(tipmsg)

说明:

  • str 表示一个字符串类型的变量,input 会将读取到的字符串放入 str 中。
  • tipmsg 表示提示信息,它会显示在控制台上,告诉用户应该输入什么样的内容;如果不写 tipmsg,就不会有任何提示信息。


【实例】input() 函数的简单使用:

a = input("Enter a number: ")
b = input("Enter another number: ")
print("aType: ", type(a))
print("bType: ", type(b))
result = a + b
print("resultValue: ", result)
print("resultType: ", type(result))

运行结果示例:

Enter a number: 100↙
Enter another number: 45↙
aType:  <class 'str'>
bType:  <class 'str'>
resultValue:  10045
resultType:  <class 'str'>

表示按下回车键,按下回车键后 input() 读取就结束了。

本例中我们输入了两个整数,希望计算出它们的和,但是事与愿违,Python 只是它们当成了字符串,+起到了拼接字符串的作用,而不是求和的作用。

我们可以使用 Python 内置函数将字符串转换成想要的类型,比如:

  • int(string) 将字符串转换成 int 类型;
  • float(string) 将字符串转换成 float 类型;
  • bool(string) 将字符串转换成 bool 类型。


修改上面的代码,将用户输入的内容转换成数字:

a = input("Enter a number: ")
b = input("Enter another number: ")
a = float(a)
b = int(b)
print("aType: ", type(a))
print("bType: ", type(b))
result = a + b
print("resultValue: ", result)
print("resultType: ", type(result))

运行结果:

Enter a number: 12.5↙
Enter another number: 64↙
aType:  <class 'float'>
bType:  <class 'int'>
resultValue:  76.5
resultType:  <class 'float'>

关于 Python 2.x

上面讲解的是 Python 3.x 中 input() 的用法,但是在较老的 Python 2.x 中情况就不一样了。Python 2.x 共提供了两个输入函数,分别是 input() 和 raw_input():

  • Python 2.x raw_input() 和 Python 3.x input() 效果是一样的,都只能以字符串的形式读取用户输入的内容。
  • Python 2.x input() 看起来有点奇怪,它要求用户输入的内容必须符合 Python 的语法,稍有疏忽就会出错,通常来说只能是整数、小数、复数、字符串等。


比较强迫的是,Python 2.x input() 要求用户在输入字符串时必须使用引号包围,这有违 Python 简单易用的原则,所以 Python 3.x 取消了这种输入方式。

修改本节第一段代码,去掉 print 后面的括号:

a = input("Enter a number: ")
b = input("Enter another number: ")
print "aType: ", type(a)
print "bType: ", type(b)
result = a + b
print "resultValue: ", result
print "resultType: ", type(result)

在 Python 2.x 下运行该代码:

Enter a number: 45↙
Enter another number: 100↙
aType:  <type 'int'>
bType:  <type 'int'>
resultValue:  145
resultType:  <type 'int'>

  • 发表于 2021-06-08 15:24
  • 阅读 ( 801 )
  • 分类:Python开发

0 条评论

请先 登录 后评论
Cara
Cara

36 篇文章

作家榜 »

  1. 轩辕小不懂 2403 文章
  2. 小柒 1324 文章
  3. Pack 1135 文章
  4. Nen 576 文章
  5. 王昭君 209 文章
  6. 文双 71 文章
  7. 小威 64 文章
  8. Cara 36 文章