如何在python中结束某个条件?

时间:2019-04-20 10:10:19

标签: python

如果满足特定条件,如何退出?输入正确答案后,循环中的输入仍会弹出。

我尝试使用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")

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

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

两种解决方案:

  1. 将该代码放入函数中,并在需要终止整个操作时使用return
  2. 在要终止的地方使用sys.exit(0)。为此,您需要导入sys模块(import sys)。

另一方面,您可以通过以下方式重构代码并使其更加简洁:

最初将猜测设置为“无”,然后进入循环。您的代码将是:


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")

答案 2 :(得分:0)

只需在if块之后添加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")

答案 3 :(得分: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")