我正在使用Python 3.5.2,并且已经被要求编写一个小程序来要求用户输入一个数字,然后程序将打印出正方形和输入数字的立方体。这是我到目前为止编写的代码:
number = input ('Please enter a number ')
y = (number)**2
z = (number)**3
print (y+z)
当我运行它时,我收到以下错误消息:
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
使这个工作正常的代码是什么?
答案 0 :(得分:2)
如有疑问,请添加打印声明
number = input ('Please enter a number ')
print("number is %s of type %s" % (number, type(number)))
print("number is {} of type {}".format(number, type(number)))
y = number ** 2
print("y is {} of type {}".format(y, type(y)))
z = number **3
print("z is {} of type {}".format(z, type(z)))
print (y+z)
输出:
python3 x.py
Please enter a number 4
number is 4 of type <class 'str'>
number is 4 of type <class 'str'>
Traceback (most recent call last):
File "x.py", line 5, in <module>
y = number ** 2
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
如您所见,number是一个字符串,因为在python3中,input
将用户输入作为字符串返回
将其更改为int(input('Please enter a number'))
答案 1 :(得分:0)
错误很明显:
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
基本上(number)
是一个字符串,而2
是一个整数。您需要做的是将number
从str
转换为int
。
试试这个:
y = int(number) ** 2
z = int(number) ** 3
print(y+z)
这应该可以解决问题。