我对 python 比较陌生,所以如果答案非常简单,我深表歉意。我正在编写一个基本脚本,允许用户输入不同的比赛参与者,代码会将这些条目放入列表中。至少有 4 个条目。 4 个条目后,它会询问您是否要按升序对列表进行排序。我已经测试过这个并且效果很好。最多有 8 个条目,如果达到此限制,则应询问用户对列表进行排序的最后时间,并将打印该列表。当在第 8 个条目上选择“是”时,将打印排序列表。然而,当选择“否”时,列表应该以未排序的方式打印,但由于某种原因,它当前刚刚结束循环。
Race_participants = []
Mworldrec = 9.58
Meuropeanrec = 9.86
Mbritishrec = 9.87
Fworldrec = 10.49
Feuropeanrec = 10.73
Fbritishrec = 10.99
while len(Race_participants) < 8:
name = str(input("\nWhat is the participants name? ")).lower()
gender = str(input("\nIs the participant male or female? ")).lower()
time = int(input("\nWhat is the participants race time? "))
records_beaten = []
if gender == "male":
if Mworldrec > time:
records_beaten.append("mens world record")
if Meuropeanrec > time:
records_beaten.append("mens european record")
if Mbritishrec > time:
records_beaten.append("mens British record")
else:
if Fworldrec > time:
records_beaten.append("womens world record")
if Feuropeanrec > time:
records_beaten.append("womens european record")
if Fbritishrec > time:
records_beaten.append("womens British record")
if records_beaten:
print("\nParticipant", name,"has beaten the following records: ")
for record in records_beaten:
print("\n", record)
print("\nParticipant" ,name, "Successfully recorded")
def get_name(Race_participants):
return Race_participants.get('name')
def get_gender(Race_participants):
return Race_participants.get('gender')
def get_time(Race_participants):
return Race_participants.get('time')
person = {
'name': name,
'gender': gender,
'time': time
}
Race_participants.append(person)
if len(Race_participants) >= 4:
user_choice = input("Do you want to sort the list? (yes/no)").lower()
if user_choice == "yes":
Race_participants.sort(key=get_time)
print("Sorted list in ascending order" ,Race_participants)
elif user_choice == "no":
continue
else:
print("Invalid choice. Please enter 'yes' or 'no'.")
if len(Race_participants)== 8:
print("You have reached the maximum amount of entries")
user_choice = input("\nDo you want to sort the list? (yes/no)").lower()
if user_choice == "yes":
Race_participants.sort(key=get_time)
print("Sorted list in ascending order" ,Race_participants)
elif user_choice == "no":
print(Race_participants)
else:
print("Invalid choice. Please enter 'yes' or 'no'.")
我尝试添加一个单独的打印功能,以防它与我的列表的逻辑相关,但我不认为它会考虑能够打印排序的版本。这样做之后,测试打印功能也没有打印,当选择否时,它只是结束循环。
让我们在头脑中“运行”一个代码实例,看看发生了什么。假设到目前为止您已经报名了 8 名比赛参与者。您的代码现在位于此 if 语句中:
if len(Race_participants) >= 4:
user_choice = input("Do you want to sort the list? (yes/no)").lower()
假设您输入
no
。然后您的代码会跳转到这一行:
elif user_choice == "no":
continue
continue
强制 while 循环重新启动。您已经告诉 while 循环在达到 8 个参与者后结束,因此它结束。它永远不会到达检查 if len(Race_participants) == 8:
的第二条语句。
额外提示:不要在 while 循环内创建函数。虽然从技术上讲这可能不会引发任何错误,但这是令人厌恶的礼仪。