首页 > 解决方案 > 访问在 while 循环中生成的函数的名称。(Python)

问题描述

下面是一个超级英雄的名字生成器。我希望能够将选择的名称添加到它说出去拯救世界的地方。有谁知道我该怎么做?

def superhero_name_generator():
    print("Welcome to the superhero name generator:\nTo choose your name follow the instructions below")
    first_part = input("Please enter the name of the city you grew up in. ")
    second_part = input("Please enter the name of your pet or your favorite mythical creature (Ie. Dragon). ")
    superhero_name = first_part + second_part
    print("your superhero name is {}".format(superhero_name))


end = '-'
while end != 0:
    superhero_name_generator()
    print("If you want to generate another name please press 1 to quit press 0")
    end = int(input())
else:
    print("Go out and save the world")

标签: pythonfunctionwhile-loop

解决方案


您必须从函数返回值。我还通过将其设为无限循环,稍微简化了您的循环break

def superhero_name_generator():
    print("Welcome to the superhero name generator:\nTo choose your name follow the instructions below")
    first_part = input("Please enter the name of the city you grew up in. ")
    second_part = input("Please enter the name of your pet or your favorite mythical creature (Ie. Dragon). ")
    superhero_name = first_part + second_part
    print("your superhero name is {}".format(superhero_name))
    return superhero_name


while True:
    name = superhero_name_generator()
    print("If you want to generate another name please press 1 to quit press 0")
    if int(input()) == 0:
        break

print("Go out and save the world,", name)

推荐阅读