Python input 函数

文章目录


Python 3.x

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'>
  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梁辰兴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值