读取字符串时出错_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 + bprint("resultValue: ", result)print("resultType: ", type(result))

    运行结果示例:

Enter a number: 100↙
Enter another number: 45↙
aType: 
bType: 
resultValue:  10045
resultType: 

表示按下回车键,按下回车键后 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 + bprint("resultValue: ", result)print("resultType: ", type(result))

    运行结果:

Enter a number: 12.5↙
Enter another number: 64↙
aType: 
bType: 
resultValue:  76.5
resultType: 

    关于 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 + bprint "resultValue: ", resultprint "resultType: ", type(result)

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

Enter a number: 45↙
Enter another number: 100↙
aType: 
bType: 
resultValue:  145
resultType: 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值