如何制作elif语句和except VALUERROR repeat函数?

2024-06-27 02:24:45 发布

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

我正在学习Udemy“自动化枯燥的东西”课程的第4部分,其中包括使用try/except处理错误

如果用户输入是无效的非整数或负整数,如何让脚本从头开始运行

print('How many cats do you have?')
numCat = input()
try:
    while True:
        if int(numCat) >= 4:
            print('That is a lot of kitties')
            break
        elif int(numCat) <= -1:
            print('You can not have '+str(numCat)+' kitties, try again')
            break
        else:
            print('That is not that many kitties')
            break
except ValueError:
    print('Please enter a number, try again')

Tags: thatishavenot整数manyintprint
3条回答

我个人会这样做:

奖金:isdigit只计算正数

numCat = None
while True:
  numCat = input()
  if numCat.isdigit():
     break
  print('Please enter a positive number.')
if int(numCat) >= 4:
  print('That is a lot of kitties')
else:
  print('That is not that many kitties')

如果每个路径中都有一个break,那么循环的目的是什么? 你可以这样做:

cond = True
while cond:
    print('How many cats do you have?')
    numCat = input()
    try:
        cond = False
        if int(numCat) >= 4:
            print('That is a lot of kitties')
        elif int(numCat) <= -1:
            print('You can not have '+str(numCat)+' kitties, try again')
        else:
            print('That is not that many kitties')
    except ValueError:
        print('Please enter a number, try again')

或者使用break

while True:
    print('How many cats do you have?')
    numCat = input()
    try:
        if int(numCat) >= 4:
            print('That is a lot of kitties')
        elif int(numCat) <= -1:
            print('You can not have '+str(numCat)+' kitties, try again')
        else:
            print('That is not that many kitties')
        break
    except ValueError:
        print('Please enter a number, try again')

不确定这是最有效的解决方案还是有更好的解决方案。但是我要做的是通过try循环,让用户再次输入

print('How many cats do you have?')
numCat = input()
loopCount = 0
while loopCount == 0:
    numCat = input()
    try:
        while True:
            if int(numCat) >= 4:
                print('That is a lot of kitties')
                break
            elif int(numCat) <= -1:
                print('You can not have '+str(numCat)+' kitties, try again')
                break
            else:
                print('That is not that many kitties')
                break
        loopCount = 1
    except ValueError:
        print('Please enter a number, try again')

相关问题 更多 >