无法在Python 3中打印两个整数的总和

loading...


-3

我有以下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回答

  • 4

    首先,您应该了解python中的类型转换 .

    当您编写 x=input("enter integer x:") 时,它将以 string 格式输入 .

    所以

    print(i+x)
    

    暗示,添加存储在 i 中的整数值和存储在 x 中的字符串值 . python中不支持此操作 .

    所以你应该使用以下任何一种

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

    要么

    print(i + int(x))
    

  • 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.
    

    这就是我喜欢做作业的方式 .


  • 1

    input(...) 在python 2.x中为python 3.x提供了一个字符串,行为不同 . 如果要读取int,则必须使用 int(input(...)) 显式转换它 .


  • 0

    我的解决方案un python 3是:

    numero1 =int(0)
    numero2 =float(0.0)
    texto = ""  
    
    
    
    # Read and save an integer, double, and String to your variables.
    numero1 = int(input())
    
    numero2 = float(input())
    
    texto = input()
    
    # Print the sum of both integer variables on a new line.
    c_int_sum = int(numero1+i)
    print (c_int_sum)
    
    # Print the sum of the double variables on a new line.
    c_float_sum = float(numero2+d) 
    Rnf = round(c_float_sum,1);
    print (Rnf)
    # Concatenate and print the String variables on a new line
    print (s+texto)
    

loading...

评论

暂时没有评论!