【问题标题】:How do I def a function and input two positive ints such that when it inputs negative ints or strings it raises a ValueError but prints out 'invalid'?如何定义一个函数并输入两个正整数,这样当它输入负整数或字符串时,它会引发一个 ValueError 但打印出“无效”?
【发布时间】:2021-11-03 06:24:50
【问题描述】:
import math

def coprimeTestFunction(val1, val2):
    if val1 < 0 or val2 < 0:
        raise ValueError
    if type(val1) != int or type(val2) != int:
        raise ValueError
        
    result = math.gcd(val1, val2)
    
    if result == 1:
        print('The values {0} and {1} are coprime'.format(int1, int2))
    elif result != 1:
        print('The values {0} and {1} are not coprime, they have a GCD of {2} '.format(int1, int2, result))
    else:
        print('We have encountered an error')

try:
    int1 = int(input('Enter first integer: '))
    int2 = int(input('Enter second integer: '))
    
except ValueError:
    print('Invalid entry')
    
coprimeTestFunction(int1, int2)

【问题讨论】:

  • 也许更改错误消息可能会有所帮助:raise ValueError("Invalid entry")

标签: python python-3.x python-2.7 try-catch try-except


【解决方案1】:

您的代码似乎有点放错了位置。您的 try/except 代码应包括您调用该函数的位置。例如:

try:
    int1 = int(input('Enter first integer: '))
    int2 = int(input('Enter second integer: '))
    coprimeTestFunction(int1, int2)

except ValueError:
    print('Invalid entry')
    

应该可以。这背后的原因是因为您的输入实际上并未检查数字是否大于 0 或整数。该功能可以。因此,通过将函数调用留在循环之外,错误不会被捕获。

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2021-07-25
    相关资源
    最近更新 更多