Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python 3.5:退出if循环(或其他循环)_Python_Python 3.x - Fatal编程技术网

python 3.5:退出if循环(或其他循环)

python 3.5:退出if循环(或其他循环),python,python-3.x,Python,Python 3.x,运行程序时,要求用户输入一个数字。如果数字为1,则退出程序。如果数字不是1,请打印数字 我想知道如何实现这一点 我正在使用python 3.5 我的代码是这样的。我总是会遇到一个错误:“中断”外部循环 我怎样才能解决这个问题 x = input('Please input a number: ') if x == '1': print('quit') break else: continue print(x) 由于关键字break用于中断循环,因此会在循环外出现错误br

运行程序时,要求用户输入一个数字。如果数字为1,则退出程序。如果数字不是1,请打印数字

我想知道如何实现这一点

我正在使用python 3.5

我的代码是这样的。我总是会遇到一个错误:
“中断”外部循环

我怎样才能解决这个问题

x = input('Please input a number: ')
if x == '1':
    print('quit')
    break
else:
    continue
print(x)

由于关键字break用于中断循环,因此会在循环外出现错误break。您在循环之外使用它,因此会得到错误。要退出应用程序,不应使用break。相反,您应该使用:

sys.exit(0)
因此,现在您的代码应该如下所示:

x = input('Please input a number: ')
if x == '1':
    print('quit')
    sys.exit(0)
else:
    print(x)
while True:
    line = 'test'
    if line = 'test':
        break
print "now I'm not in the loop"

在else语句中也不需要continue。您只需将else语句保留为空,程序将继续运行,或者您可以像我对代码所做的那样将
print(x)
放入else语句中。

这不是退出应用程序的方式。尝试
sys.exit(error)
其中error是错误号

break
允许您转义循环,如下所示:

x = input('Please input a number: ')
if x == '1':
    print('quit')
    sys.exit(0)
else:
    print(x)
while True:
    line = 'test'
    if line = 'test':
        break
print "now I'm not in the loop"

代码中没有循环,因此需要添加while语句。将条件设置为True以使其始终运行。您也不需要else continue语句,因为这将跳过打印(x)。X将自动转换为整数,因此将其转换为字符串

while True:    
    x = input('Please input a number: ')
    if str(x) == "1":
        print('quit')
        break
    print(x)

环路在哪里?如果只是检查值。。你没有一个循环可以打破,因为你需要循环。在通用编程语言中查找break和continue的用法。