Home > Software design >  How to use a counter in a program, or how to use looping in simple code
How to use a counter in a program, or how to use looping in simple code

Time:11-22

I have a pre-defined invited guest list. I ask a user for their name and check if the name is in the list. If it is, we simply print welcome. If not, we print the statement in the else condition. After that I want to add looping of name.

What should I add in this? The program should work repeatedly when run once.

guest_list = ['abhishek olkha' , 'monika' , 'chanchal' , 'daisy' , 'mayank']
name= input('enter your name please  ')
if name in guest_list:
    print( "welcome sir/ma'am")
else:
    print('sorry you are not invited')

CodePudding user response:

guest_list = ['abhishek olkha' , 'monika' , 'chanchal' , 'daisy' , 'mayank']
#infinite loop
while True:
    name= input('enter your name please  ')
    if name in guest_list:
        print( "welcome sir/ma'am")
    else:
        print('sorry you are not invited')

CodePudding user response:

Use a for loop and specify how many time you want it check

guest_list = ['abhishek olkha' , 'monika' , 'chanchal' , 'daisy' , 'mayank']
name= input('enter your name please  ')
for i in range(10):  #the loop would run for 10 times starting from 0 to 9
    if name in guest_list:
        print( "welcome sir/ma'am")
    else:
        print('sorry you are not invited')

CodePudding user response:

If you want to indefinitely loop by giving a new name and checking the result you should wrap everything in a while(true) loop.

If you want to exit the loop and the program when the name is not in the list you should use a boolean variable set to True at first and that variable is set to False if the name is not in the list

guest_list = ['abhishek olkha' , 'monika' , 'chanchal' , 'daisy' , 'mayank']
condition=True
while(condition):
    name= input('enter your name please  ')
    if name in guest_list:
        print( "welcome sir/ma'am")
    else:
        print('sorry you are not invited')
        condition=False
  • Related