【问题标题】:How to exit a loop in Python? [closed]如何在 Python 中退出循环? [关闭]
【发布时间】:2016-02-17 23:54:19
【问题描述】:

我想让循环在x + y =z 时停止,否则。

代码:

# -*- coding: utf-8 -*-
"""
Created on Mon Nov 16 18:39:40 2015

@author: gabri
"""

from random import randint
import os

x = randint(1,11)
y = randint(1,11)

print ("", x,"+", y,"=\n")
z = int(input("Resposta="))

if z == x + y:
    input ("\n\nCorreto\nPrima enter para continuar...")

else:
    for z in range(0, 10):
        os.system('CLS')
        input ("Incorreto.\n\n Tente de novo...")
        x = randint(1,11)
        y = randint(1,11)
        os.system('CLS')
        print ("", x,"+", y,"=\n")
        z = int(input("Resposta="))
        if z == x + y:
            input ("\n\nCorreto\nPrima enter para continuar...")
            exit

【问题讨论】:

  • 如果用户从未给出正确答案会发生什么?这段代码只是脱离了循环。

标签: python syntax syntax-error


【解决方案1】:

exit 替换为breakExit 不是在 Python 中退出循环的方法。

break statement docs

【讨论】:

  • exit 是一个内置函数。如果它“不是一个东西”,你会得到一个语法错误。
  • 已编辑。很高兴你抓住了这一点。我可能会误导几代人。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-15
  • 1970-01-01
  • 1970-01-01
  • 2023-01-15
  • 2021-09-10
  • 1970-01-01
相关资源
最近更新 更多