我有以下Python培训代码:
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.
我想要实现的目标如下:
在新行上打印i加上int变量的总和 . 将d加上双变量的总和打印到新行上一位小数的比例 . 使用您读取的字符串连接s并将结果打印在新行上 .
当我运行我的代码时,我收到此错误:
回溯(最近一次调用最后一次):文件“C:... \ lesson2.py”,第12行,打印(i x)TypeError:不支持的操作数类型:'int'和'str'
你能帮帮忙吗?
EDIT: 我读了所有的评论 . 添加两个double类型时出错 . 我试过双重铸造,但它不起作用:
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.
错误是:
回溯(最近一次调用最后一次):文件“C:... \ lesson2.py”,第14行,打印(y double(d))NameError:名称'double'未定义
4 回答
首先,您应该了解python中的类型转换 .
当您编写
x=input("enter integer x:")
时,它将以string
格式输入 .所以
暗示,添加存储在
i
中的整数值和存储在x
中的字符串值 . python中不支持此操作 .所以你应该使用以下任何一种
要么
这就是我喜欢做作业的方式 .
input(...)
在python 2.x中为python 3.x提供了一个字符串,行为不同 . 如果要读取int,则必须使用int(input(...))
显式转换它 .我的解决方案un python 3是: