Madman12
Madman12

Reputation: 37

How do I make a code that repeats without while-loop?

I'm trying to repeat a code that asks the user for a name, and thereafter asks for a new name. If the user writes a number, the program should ask for a new name. If the user types 'quit' the program should print how many names the user has entered.

So far I've solved it with a while-loop, but would like to do it WITHOUT using a while-loop and still keep prompting the user for new names.

participants=[]
count=0

while True:
    user_name=input("Course participant name: ")
    if user_name == "quit":
        print("Number of participants: ", count)
    elif user_name.isdigit():
        continue
    elif user_name.isalpha():
        participants.append(user_name)
        count+=1
    else:
        print("Invalid input")
        break

Any suggestions?

Upvotes: 0

Views: 1081

Answers (3)

BishalG
BishalG

Reputation: 1424

If you are looking for solution using for loop then you can do as follow:

participants=[]
count=0
from itertools import cycle
for i in cycle(range(0, 1)):
    user_name=input("Course participant name: ")
    if user_name == "quit":
        print("Number of participants: ", count)
    elif user_name.isdigit():
        continue
    elif user_name.isalpha():
         participants.append(user_name)
         count+=1
    else:
         print("Invalid input")
         break

Upvotes: 0

Andreas
Andreas

Reputation: 2521

This is a slightly tricky way to do it, by using the participants list itself and providing an initial element (to start the loop), which will be deleted in the end. The loop will keep going as long as there is a name being inputted, because the participants list grows at every iteration.

participants=["Start"] # insert initial element, to start the loop
count=0

for i in participants:
    user_name=input("Course participant name: ")
    if user_name == "quit":
        print("Number of participants: ", count)
    elif user_name.isdigit():
        continue
    elif user_name.isalpha():
        participants.append(user_name)
        count+=1
    else:
        print("Invalid input")
        break

del participants[0] # remove initial element

Upvotes: 0

piripiri
piripiri

Reputation: 2005

You could use recursion:

def ask(participants):
    user_name = input("Course participant name: ")
    if user_name == "quit":
        print("Number of participants: ", len(participants))
    elif user_name.isdigit():
        ask(participants)
    elif user_name.isalpha():
        participants.append(user_name)
        ask(participants)
    else:
        print("Invalid input")
        return

Instead of looping, you go deeper and deeper into the call stack. No need to track count separately because it is already encoded in the length of participants.

Upvotes: 3

Related Questions