简体   繁体   中英

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.

  1. The user enters their age in the first msg() function.
  2. You print their ticket price and call msg() again recursively.
  3. This time they type "quit", and the recursive function correctly exits.
  4. However, the original msg() function is still running, so it prompts again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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