简体   繁体   English

while 循环中的重复行

[英]repeated line in while loop

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)

i want to exit as i type quit....it works fine when i type quit at first time.but the line repeted when i enter age value我想在我输入退出时退出......当我第一次输入退出时它工作正常。但是当我输入年龄值时重复该行

try this out:试试这个:

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

The problem is that you're calling msg() recursively from itself.问题是您从自身递归地调用msg()

  1. The user enters their age in the first msg() function.用户在第一个msg()函数中输入他们的年龄。
  2. You print their ticket price and call msg() again recursively.您打印他们的票价并再次递归调用msg()
  3. This time they type "quit", and the recursive function correctly exits.这次他们输入“quit”,递归函数正确退出。
  4. However, the original msg() function is still running, so it prompts again.但是原来的msg()函数还在运行,所以再次提示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM