所以我正在编写一个小游戏,我正在尝试做一些我不知道该怎么做的事情。我已经定义了一个函数,当没有任何条件可以使用该代码时,我希望它返回到另一行代码。但是我不知道该怎么做。这是我正在处理的代码的一部分
print "What's your favourite type of pokemon?"
fav_type = raw_input()
def chosen_pokemon():
if "fire" in fav_type:
print "So you like fire types? I'll give you a chimchar!"
elif "water" in fav_type:
print "So you like water types? I'll give you a piplup!"
elif "grass" in fav_type:
print "So you like grass types? I'll give you a turtwig!"
else:
print "sorry, you can only choose grass, water or fire"
start()
chosen_pokemon()
就像我希望代码返回到“您最喜欢的神奇宝贝类型是什么?”如果以其他方式结束,但是如何?回答时请尽可能清楚,因为我才刚刚开始学习编程,对此我几乎一无所知
python大神给出的解决方案
您可以使raw_input
步骤进入while循环,并且仅在收到有效响应后退出。我添加了一些评论来解释发生了什么。
def chosen_pokemon():
while True: # repeat forever unless it reaches "break" or "return"
print "What's your favourite type of pokemon?"
fav_type = raw_input()
if "fire" in fav_type:
print "So you like fire types? I'll give you a chimchar!"
elif "water" in fav_type:
print "So you like water types? I'll give you a piplup!"
elif "grass" in fav_type:
print "So you like grass types? I'll give you a turtwig!"
else:
print "sorry, you can only choose grass, water or fire"
continue # jumps back to the "while True:" line
return # finished; exit the function.
chosen_pokemon()
输出:
>>> chosen_pokemon()
What's your favourite type of pokemon?
yellow
sorry, you can only choose grass, water or fire
What's your favourite type of pokemon?
grass
So you like grass types? I'll give you a turtwig!
>>>
这是有关while
循环的教程。 http://www.tutorialspoint.com/python/python_while_loop.htm