我對Python的訓練下面的代碼:不能打印兩個整數的和在Python 3
import sys
# Declare second integer, double, and String variables.
i=12
d=4.0
s="HackerRank"
# Read and save an integer, double, and String to your variables.
x=input("enter integer x:")
y=input("enter double y:")
z=input("enter string z:")
# Print the sum of both integer variables on a new line.
print(i+x)
# Print the sum of the double variables on a new line.
print(y+d)
# Concatenate and print the String variables on a new line
print(s+z)
# The 's' variable above should be printed first.
我想實現的是以下幾點:
Print the sum of i plus your int variable on a new line. Print the sum of d plus your double variable to a scale of one decimal place on a new line. Concatenate s with the string you read as input and print the result on a new line.
當我運行我的代碼,我得到這個錯誤:
Traceback (most recent call last): File "C:...\lesson2.py", line 12, in print(i+x) TypeError: unsupported operand type(s) for +: 'int' and 'str'
你能幫忙嗎?
編輯: 我讀了所有的評論。添加兩個雙精度型時出錯。我試過雙鑄造,但它不工作:
import sys
# Declare second integer, double, and String variables.
i=12
d=4.0
s="HackerRank"
# Read and save an integer, double, and String to your variables.
x=input("enter integer x:")
y=input("enter double y:")
z=input("enter string z:")
# Print the sum of both integer variables on a new line.
print(i+int(x))
# Print the sum of the double variables on a new line.
print(y+double(d))
# Concatenate and print the String variables on a new line
print(s+z)
# The 's' variable above should be printed first.
的錯誤是:
所有的Traceback (most recent call last): File "C:...\lesson2.py", line 14, in print(y+double(d)) NameError: name 'double' is not defined
通過執行int(x)等將變量x,y和z轉換爲整數。 – elzell
錯誤解釋了此問題。無法將int和str一起添加。所以你應該如何使你的字符串成爲一個整數來使用。 –
家庭作業問題.... – u8y7541