首页 > 解决方案 > while循环中的重复行

问题描述

print('welcome to cinema')
def msg():
exit = input(' if you want to exit press quit')
print()


while True:
age = input(' enter your age  ')

if age == 'quit':
    break
age = int(age)
if age < 3:
    print('your ticket is free')
    msg()
elif age < 10:
    print('your ticket is S10')
    msg()
else:
    print('your ticket is S20')
    msg()

output:welcome to cinema
enter your age  12
your ticket is S20
if you want to exit press quit 

enter your age( why this line is repeated)

我想在输入退出时退出....当我第一次输入退出时它工作正常。但是当我输入年龄值时该行重复

标签: pythonwhile-loopexit

解决方案


试试这个:

import sys


print('welcome to cinema')
def msg():
    exit = input('if you want to exit press quit')
print()

while True:
    age = input(' enter your age  ')
    if age == 'quit':
        break
    age = int(age)
    if age < 3:
        print('your ticket is free')
    elif age < 10:
        print('your ticket is S10')
    else:
        print('your ticket is S20')
    exit = input("do you want to quit (y/n): ")
    if exit in ["y", "yes"]:
        sys.exit('stopped')

推荐阅读