繁体   English   中英

我需要编写一个仅在两个数字为整数时才打印两个数字之和的代码,否则返回错误?

[英]I need to write a code which prints the sum of two numbers only when they are integer otherwise returns error?

这是我的代码,您能解释什么错误并且我没有得到正确的输出吗?

import sys

n = input()
m = input()

if (type(n) == type(int) and type(m) == type(int)):
    sum = n + m
    print(sum)
else:
    print("error")

我期望1和2的输出为3,但实际输出是错误的。

input返回一个字符串。 此代码有效:

try:
    n = int(input())
    m = int(input())
except ValueError:
    print('Please enter a number')

sum = n + m
print(sum)

您的方法行不通,因为input始终返回字符串。 相反,您可以使用tryexcept将字符串转换为如下所示的整数:

inp1 = input()
inp2 = input()

# try to change the type of the input into integer
try: 
    int_inp1 = int(inp1)
    int_inp2 = int(inp2)
    # if it works: print the sum of both integers
    sum1_2 = int_inp1 + int_inp2
    print(sum1_2)
# if it fails: print "error"
except:
    print("error")

请参阅有关处理异常的文档

Python尝试除外

使用try block可以测试代码块是否存在错误。

except block ,您可以处理该错误。

finally块使您可以执行代码,而不管try-和except块的结果如何。

当发生错误或异常时,Python通常会停止并生成错误消息。

try:
    n = int(input())
    m = int(input())
    sum = int(n) + int(m)
    print(sum)
except:
    print("error")

注意:

input()返回字符串。

int(input()) :如果输入字符串表示整数,则它将字符串转换为整数并执行try块,否则将返回错误并执行exept块

您的代码输出error因为type(int)返回类型'type',而不是整数。 要更正此错误,您可以简单地:

import sys

n = input()
m = input()

if (type(n) == int and type(m) == int):
    sum = n + m
    print(sum)
else:
    print("error")

尽管正如其他人在回答中说的那样,但通常使用try except来代替if块使用python更具Python性。 您可以找到有关此问题中最佳的更多信息。

注意:

此答案仅对python 2有效

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM