当语句不满足时,如何回到代码的开头?

2024-04-25 07:04:40 发布

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

我一直在用Python做我的第一个计算器,遇到了一个小问题,让我向您展示一下我的代码:

fNum = input('Enter first number:' '\n')  # user gives numbers
sNum = input('Enter second number:' '\n')
if sNum.isalpha() or fNum.isalpha() is True:  # checking are they numbers
    print('You have to give me a number!')

我怎样才能“返回”到代码的开头并给用户另一个写下数字的机会?因为现在如果输入字母或任何不是数字的东西,程序就结束了

谢谢你的帮助,如果这个问题很简单,我很抱歉,但我还没有经验


Tags: 代码numberinputif数字计算器firstenter
1条回答
网友
1楼 · 发布于 2024-04-25 07:04:40

这种技术称为验证,使用while循环直到条件被打破:

num1 = input('Enter 1st number:') 
num2 = input('Enter 2nd number:')

# while both strings are not a bunch of digits 

while not (num1.isdigit() and num2.isdigit()):
    num1 = input('Enter 1st number:') 
    num2 = input('Enter 2nd number:')

相关问题 更多 >

    热门问题