2016-08-19 24 views
-3

我對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

+0

通過執行int(x)等將變量x,y和z轉換爲整數。 – elzell

+0

錯誤解釋了此問題。無法將int和str一起添加。所以你應該如何使你的字符串成爲一個整數來使用。 –

+1

家庭作業問題.... – u8y7541

回答

3

首先,你應該知道在Python類型轉換。

當您編寫x=input("enter integer x:")時,它將採用string格式的輸入。

所以

print(i+x) 

意味着,添加存儲在x存儲在i一個整數值和字符串值。 python不支持這個操作。

所以,你應該使用以下

x = int(input("enter integer x:")) 

print(i + int(x)) 
+0

謝謝@niyasc。你可以檢查編輯嗎? – user2192774

0

input(...)要麼讓你在Python 3.X的字符串在Python 2.x的行爲是不同的。如果你想讀int,你必須使用int(input(...))明確地轉換它。

0
# Read and save an integer, double, and String to your variables. 
x=int(input("enter integer x:")) 
y=float(input("enter double y:")) 
z=str(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+(d*2)) 
# Concatenate and print the String variables on a new line 
print(str(s)+": " + str(z)) 
# The 's' variable above should be printed first. 

這就是我更喜歡做我的功課。