python-3.x - 从另一个函数获取数字输入的函数,如果数字为负,则应该给出错误

标签 python-3.x input error-handling

我正在做一个函数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

最佳答案

那就是你的代码所做的。尝试逐步完成您的功能(手动或通过调试器),您会发现这正是预期的结果。为了使代码不断询问直到获得正数,您需要一个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

关于python-3.x - 从另一个函数获取数字输入的函数,如果数字为负,则应该给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52572501/

相关文章:

python - 类型错误 : cannot unpack non-iterable bool object

python - 如何根据用户输入将列表与动态大小相乘

ios - 为什么Objective-C中的 "try catch"会导致内存泄漏?

python - 使用 python 请求模块时出现 HTTP 503 错误

python - 将字符串二进制转换为单独的位 python dataframe

python - 在 python 3 中使用 itertools.product 和列表

javascript - 如何使输入类型列表只接受列表选择?

c - 默认情况下,读取输入缓冲区中的哪个字符会使 scanf() 停止读取字符串?

c++ - 错误 : invalid initialization of reference of type

php - 检测(在自定义错误处理程序中)PHP 错误是否实际上被 @ 抑制了