You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python函数内break无法终止外层while循环 无歌曲时如何直接结束程序

解决方案

你可以通过给fate函数增加返回状态的方式,向外层循环传递当前歌曲库存是否为空的信号,外层循环收到库存为空的信号后直接终止即可,修改后的代码如下:

import random
Genre = ["Power metal", "Melodic death metal", "Progressive metal", "Rock"]
Power_metal = ["Helloween", "Dragonforce", "Hammerfall"]
Melodic_death_metal = ["Kalmah", "Insomnium", "Ensiferum", "Wintersun"]
Progressive_metal = ["Dream theater", "Symphony X"]
Rock = ["Bon Jovi", "Nirvana"]

a = ["Pumpkins united", "Halloween"]

Helloween = set(a)

Music = input("\nSelect a music genre from available: %s:" % (Genre))
def bands(Music):
    while True:
        if Music == "Melodic death metal":
            return (Melodic_death_metal)
        elif Music == "Power metal":
            return (Power_metal)
        elif Music == "Progressive metal":
            return (Progressive_metal)
        elif Music == "Rock":
            return (Rock)
        else:
            Music = input("\nYou entered the wrong name. Please, enter again: %s:" % (Genre))

Band = input("\nReffering to chosen genre, I have bands such as: %s. Choose a specific band and I'll suggest a random song:\n" % bands(Music))
# 修改fate函数,增加返回值
def fate(Band):
    while True:
        if Band == "Helloween":
            if len(Helloween) != 0:
                print("Suggested song: ", Helloween.pop())
                return True # 还有剩余歌曲,返回True
            elif len(Helloween) == 0:
                print("I don't have more songs to propose. Enjoy your music")
                return False # 无剩余歌曲,返回False

# 首次调用获取初始库存状态
has_song = fate(Band)
# 仅当有剩余歌曲时才弹出继续询问
while has_song:
    next = input("\nWould you like me to suggest one more song from the band of your choice ?  Answer yes or no:\n")
    if next == "no":
        print("Enjoy your music")
        break
    elif next == "yes":
        has_song = fate(Band)
        # 无剩余歌曲时会自动终止循环,无需用户输入no

改动说明

  • 调整fate函数逻辑,用return替代原有break语句,同时返回布尔值标记当前乐队是否还有未推荐的歌曲
  • 新增has_song变量接收fate的返回值,将外层循环的触发条件修改为「还有剩余歌曲」,一旦fate返回库存为空的标记,外层循环会直接终止运行

内容的提问来源于stack exchange,提问作者Tomek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 08:24:02