2016-08-19 5 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'

Помогите пожалуйста?

EDIT: Я прочитал весь комментарий. Я получаю ошибку при добавлении двух двойных типов. Я попробовал двойную отливку, но он не работает:

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

Преобразование переменных x, y и z в int с помощью int (x) и т. Д. – elzell

+0

Ошибка объясняет проблему. Невозможно добавить int и str вместе. Таким образом, вы должны понять, как заставить вашу строку использовать целое число. –

+1

Домашнее задание .... – u8y7541

ответ

3

Прежде всего, вы должны знать, преобразования типов в питона.

Когда вы пишете x=input("enter integer x:"), он примет ввод в формате string.

Так

print(i+x) 

означает, добавьте целое значение, хранящееся в i и значение строки, хранящейся в x. Эта операция не поддерживается в python.

Таким образом, вы должны использовать одно из следующих

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

или

print(i + int(x)) 
+0

Спасибо @niyasc. Можете ли вы проверить редактирование, пожалуйста? – user2192774

0

input(...) дает строку в питона 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. 

вот как я предпочитаю делать домашнее задание.

Смежные вопросы