在Python中获取用户输入是一个非常基本的疑问,Python是否将任何输入作为字符串并使用它进行计算,我们必须将其更改为整数还是什么?在下面的代码中:
a = raw_input("Enter the first no:")
b = raw_input("Enter the second no:")
c = a + b
d = a - b
p = a * b
print "sum =", c
print "difference = ", d
print "product = ", p
Python 给出以下错误:
Enter the first no:2
Enter the second no:4
Traceback (most recent call last):
File "C:\Python27\CTE Python Practise\SumDiffProduct.py", line 7, in <module>
d=a-b
TypeError: unsupported operand type(s) for -: 'str' and 'str'
有人可以告诉我为什么会收到此错误吗?
是的,每个输入都是字符串。但只要尝试一下:
a = int(a)
b = int(b)
在你的代码之前。
但请注意,用户可以使用 raw_input 传递他喜欢的任何字符串。安全的方法是 try/ except 块。
try:
a = int(a)
b = int(b)
except ValueError:
raise Exception("Please, insert a number") #or any other handling
所以它可能是这样的:
try:
a = int(a)
b = int(b)
except ValueError:
raise Exception("Please, insert a number") #or any other handling
c=a+b
d=a-b
p=a*b
print "sum =", c
print "difference = ", d
print "product = ", p
来自文档:
然后该函数从输入中读取一行,将其转换为字符串(去除尾随换行符),然后返回该字符串。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)