在用户使用While循环在Python上输入整数和非0值之前,如何继续提示用户输入?

时间:2019-02-12 13:58:57

标签: python while-loop

如何继续要求用户输入有效输入,直到用户输入y值的整数和非零数字为止?我仍在练习While Loop,如果您能帮助我,那就太好了。

提前谢谢!

x = 5
y = 0

while y == 0 or y (is not integer??):
    try:
         z = x/y

    except ZeroDivisionError:
        y = int(input('You cannot divide with "0".\nTry using a number bigger than 0 for y-value.'))

    else:
        print(f'dThanks for placing the right value for y. \nYour result is {z}')
        break

    finally:
        print('All Done')

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

wrong = True
while wrong:
    try:
        number = input("please enter a non-zero number: ")
        if isinstance(int(number), int) and int(number) != 0:
            print('You entered: ' + number)
            y = int(number)
            wrong = False
        else:
            print("make sure it's a nonzero number only!")
    except:
        print("try again please.")

z = x/y

print('The answer is: ' + str(z))