我怎么能在python中结束某个条件?

问题描述 投票:0回答:4

如果满足某个条件,我该如何退出?在我写完正确答案后,循环中的输入仍然会弹出。

我尝试过使用exit()breaksystem.exitsystem.quit

x = int(input("write a number : "))
y = int(input("write another number : "))
result = x * y
guess = int(input(str(x) + " is multiplied to "+ str(y) + " is equals to? \n " ))
if guess == result:
    print("congrats")
    ### if this condition is met i want to end here
guess1 = 0
while guess1 != result:
    guess1 = int(input("write another answer : "))
    if guess1 == result:
        print("this time you got it")

如果满足其他条件,我想摆脱其他输入。

python
4个回答
0
投票

只需在if块后添加else语句即可。如果满足条件,它将停止代码,或者它将继续到代码的else部分。

if guess == result:
    print("congrats")
    ### if this condition is met it will print congrats and stop
else:
    guess1 = 0
    while guess1 != result:
        guess1 = int(input("write another answer : "))
        if guess1 == result:
            print("this time you got it")

0
投票

最简单的方法是在满足条件时将结果设置为0。

x = int(input("write a number : "))
y = int(input("write another number : "))
result = x * y
guess = int(input(str(x) + " is multiplied to "+ str(y) + " is equals to? \n " ))
if guess == result:
    print("congrats")
    result = 0  # if the condition is met, the while loop would never run if the result is the same as guess1
guess1 = 0
while guess1 != result:
    guess1 = int(input("write another answer : "))
    if guess1 == result:
        print("this time you got it")

###I want to get rid of the other input if the other condition is met

0
投票

您可以使用else跳过部分代码

if guess == result:
    print("congrats")
else:
    guess1 = 0
    while guess1 != result:
       guess1 = int(input("write another answer : "))
       if guess1 == result:
           print("this time you got it")

# this line will be executed 

或者exit()退出剧本

if guess == result:
    print("congrats")
    ### if this condition is met i want to end here
    exit()

guess1 = 0
while guess1 != result:
    guess1 = int(input("write another answer : "))
    if guess1 == result:
        print("this time you got it")

0
投票

两种解决方案

  1. 将该代码放在函数中并在想要终止整个事件时使用return
  2. 在您要终止的位置使用sys.exit(0)。您需要为此导入sys模块(import sys)。

另外,您可以通过以下方式重构代码并使其更清晰:

最初将guess设置为None,然后进入循环。您的代码将是:


x = int(input("write a number : "))
y = int(input("write another number : "))
result = x * y
guess = None
while guess != result:
    guess = int(input("write another answer : "))
    if guess == result:
        print("congrats")

© www.soinside.com 2019 - 2024. All rights reserved.