首页 > 解决方案 > 如何检查此输入是否为负数

问题描述

我是 python 新手,想制作一个程序,用给定的十进制数字生成 Pi。问题是我不知道如何检查用户是否输入了正数。

这是生成 Pi 的函数(我不确定它是如何工作的)

def PiBerekening(limiet):

q = 1
r = 0
t = 1
k = 1
n = 3
l = 3

decimaal = limiet
teller = 0

while teller != decimaal + 1:
    if 4 * q + r - t < n * t:
        # yield digit
        yield n
        # insert period after first digit
        if teller == 0:
            yield '.'
        # end
        if decimaal == teller:
            print('')
            break
        teller += 1
        nr = 10 * (r - n * t)
        n = ((10 * (3 * q + r)) // t) - 10 * n
        q *= 10
        r = nr
    else:
        nr = (2 * q + r) * l
        nn = (q * (7 * k) + 2 + (r * l)) // (t * l)
        q *= k
        t *= l
        l += 2
        k += 1
        n = nn
        r = nr

这就是我问用户他想看到多少个小数的方式

while not verlaatloop:
    try:
        pi_cijfers = PiBerekening(int(input("With how many decimals would you like to calculate Pi?")))
        assert pi_cijfer > 0  # This is one of the things I've tried but I get the "NameError: name 'pi_cijfer' is not defined" error and I don't know what to do to check if the inputted number is negative
    except ValueError:
        print("This isn't a valid number, try again")
    except AssertionError:
        print("This number is negative, try again")
    else:
        verlaatloop = True

这就是我显示计算的 Pi 的方式

    for pi_cijfer in pi_cijfers:
    print(pi_cijfer, end='')

标签: python-3.x

解决方案


您可以先验证输入,然后将其传递给 PiBerekening 函数。像这样的东西:

while not verlaatloop:
    try:
        no_decimals = int(input("With how many decimals would you like to calculate Pi?"))
        if no_decimals > 0:
           pi_cijfers = PiBerekening(no_decimals)
        #assert pi_cijfer > 0  # This is one of the things I've tried but I get the "NameError: name 'pi_cijfer' is not defined" error and I don't know what to do to check if the inputted number is negative
    except ValueError:
        print("This isn't a valid number, try again")
    except AssertionError:
        print("This number is negative, try again")
    else:
        verlaatloop = True

推荐阅读