[英]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. 到目前为止,我已经用while循环解决了这个问题,但是我想不使用while循环来解决这个问题,并且仍然不断提示用户输入新名称。
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? 有什么建议么?
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
. 无需单独跟踪
count
因为它已经按照participants
的长度进行了编码。
If you are looking for solution using for
loop then you can do as follow: 如果您正在寻找使用
for
循环的解决方案for
则可以执行以下操作:
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
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. 通过使用
participants
列表本身并提供一个初始元素(开始循环),这是一种有点棘手的方法,该元素最终将被删除。 The loop will keep going as long as there is a name being inputted, because the participants
list grows at every iteration. 只要输入了名称,循环就将继续进行,因为
participants
列表在每次迭代时都会增长。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.