如何在while循环中限制输入需要认真研究

2024-04-27 00:49:54 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将srj的输入限制在1和0之间,然后重新启动整个程序

def gen0():      # input all the initial data
    while True:  # this will loop infinitely if needed
        try:     # this will try to take a float from the user
            j=int(input('how many juveniles are there in generation 0? '))
            srj=float(input('what is the survival rate of juveniles '))
            break             # if the user gives a number then break the loop
        except ValueError:    #if the user does not give a number then the user will be told to retry
            print("Sorry, there was an error. Please enter a positive number")

Tags: thetoloopnumberinputiffloatthis
2条回答

因为您是在try/except中中断,所以如果数据不正确,您可以简化raisea ValueError。你知道吗

if  srj > 1.0 or srj < 0.0:
    raise ValueError

将if语句if srj > 1 or srj < 0:gen0()放在break行之前
:^)

相关问题 更多 >