您的代码有很多问题,这里已经修复:
more_guests = 0
# you don't need to declare types, but if you want to, this is how
loop: bool = False
# however, Python can just infer the type itself like this
ferdig = 1
# you don't want to reset guests every time around the loop
guests = []
while loop == False:
more_guests = 0
if int(ferdig) == 1:
guest = input("type in guest ")
# you always want to append a guest, including if someone types a 1 after
guests.append(guest)
more_guests = int(input("done? 1 for yes 2 for no "))
if int(more_guests) == 1:
ferdig = 3
elif int(more_guests) == 2:
ferdig = 2
else:
print("invalid answer, please use 1 or 2")
ferdig = 1
elif int(ferdig) == 2:
ferdig = 1
elif int(ferdig) == 3:
# after printing, you're done, you don't want to print forever
print(guests)
loop = True
请注意,尽管您的大部分代码并不是真正需要的,但您正在做 Python 可以为您做的大量簿记工作,或者根本不需要:
# this isn't needed, because you set that at the start of the loop anyway
# more_guests = 0
# this isn't needed, because you can tell when to stop from ferdig
# loop: bool = False
# starting at 2, since that means you want to keep going
ferdig = 2
guests = []
while ferdig != 1:
# this isn't needed, you can just read ferdig
# more_guests = 0
# this isn't needed, you want a new guest on every loop
#if int(ferdig) == 1:
guest = input("type in guest ")
guests.append(guest)
ferdig = int(input("done? 1 for yes 2 for no "))
# none of this is needed, all you need to know is if ferdig is 1 or 2
# if int(more_guests) == 1:
# ferdig = 3
# elif int(more_guests) == 2:
# ferdig = 2
# else:
if ferdig not in (1, 2):
print("invalid answer, please use 1 or 2")
ferdig = 1
# this is also not needed, at this point ferdig will be 1 or 2
# elif int(ferdig) == 2:
# ferdig = 1
# elif int(ferdig) == 3:
# put the print outside the loop and it only prints once
print(guests)
# got rid of this
# loop = True
所以,这只是:
ferdig = 2
guests = []
while ferdig != 1:
guest = input("type in guest ")
guests.append(guest)
ferdig = int(input("done? 1 for yes 2 for no "))
if ferdig not in (1, 2):
print("invalid answer, please use 1 or 2")
ferdig = 1
print(guests)
最后,这会做同样的事情:
more_guests = True
guests = []
while more_guests:
guests.append(input("type in guest "))
more_guests = input("done? 1 for yes") != '1'
print(guests)