2016-09-30 45 views
-1

我正在使用Python 3.5.2並且被要求編寫一個小程序來要求用戶輸入一個數字,然後程序會打印輸入數字的正方形和多維數據集。這是我的代碼到目前爲止已經寫的:要求用戶輸入一個數字並在Python 3.5中打印該數字的正方形和立方體的代碼是什麼?

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' 

什麼是正確的代碼來獲得這個工作?

+1

'input'總是返回一個字符串(在Python 3中),並且您不能對字符串進行算術運算,因此您必須將其轉換爲數字類型。 '數字= int(輸入('請輸入數字'))' –

回答

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' 

,你可以看到,數量是一個字符串,因爲在python3,input返回用戶輸入的字符串

更改爲int(input('Please enter a number'))

+0

非常感謝,這工作 – Henry

0

的錯誤是相當不言自明:

TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int' 

(number)基本上是一個字符串,而2是一個整數。你需要做的是將numberstr轉換爲int。 試試這個:

y = int(number) ** 2 
z = int(number) ** 3 
print(y+z) 

這應該是訣竅。

+0

謝謝,我試過這個和上面的建議,他們都解決了我遇到的問題。 – Henry

相關問題