【问题标题】:Function that gets it numerical input from another function that should give an error if the number is negative从另一个函数获取数字输入的函数,如果该数字为负数,则该函数应给出错误
【发布时间】:2018-09-29 20:59:44
【问题描述】:

我正在创建一个函数 sum(),它应该从函数 number() 中获取一个正整数 x。如果输入为负数,函数 number() 应该给出错误并要求用户输入另一个输入。

def number():
    try:
        x = int(input('Please enter a positive number: '))
        if x <= 0:
            raise ValueError
    except ValueError:
        print('Could you please enter positive number once againg!!')
        x = int(input('Enter a positive number: '))
    return x

def sum(x):
    print(f'Your number is {x}')

x = number()
sum(x)

我尝试运行它,当我给它一个负值时它会再次询问,但如果我再次给它一个负数,就会出现问题。有什么想法吗?

Please enter a positive number: -4
Could you please enter positive number once againg!!
Enter a positive number: -4
Your number is -4

【问题讨论】:

    标签: python-3.x input error-handling


    【解决方案1】:

    这就是您的代码所做的。尝试单步执行您的函数(手动或使用调试器),您会发现这正是预期的结果。要让代码一直询问直到获得正数,您需要一个 while 循环。

    此外,没有必要引发错误,因为您会立即捕获它。您的代码实际上相当于:

    def number():
        x = int(input('Please enter a positive number: '))
        if x <= 0:
            print('Could you please enter positive number once againg!!')
            x = int(input('Enter a positive number: '))
        return x
    

    【讨论】:

    • 好吧,我把它复杂化了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 2019-07-20
    • 1970-01-01
    相关资源
    最近更新 更多