gpt4 book ai didi

python - 循环回到代码中的特定点

转载 作者:行者123 更新时间:2023-11-28 22:46:33 25 4
gpt4 key购买 nike

所以我正在编写一个小游戏,我正在尝试做一些我不明白该怎么做的事情。我已经定义了一个函数,当代码工作的任何条件都不满足时,我希望它返回到另一行代码。但我不明白该怎么做。这是我正在处理的代码的一部分

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()

就像我想让代码返回到“你最喜欢的口袋妖怪是什么类型?”如果它以其他方式结束,但是如何呢?回答的时候尽量说清楚,因为我才刚开始学编程,对编程几乎一无所知

最佳答案

您可以将 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

关于python - 循环回到代码中的特定点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27364956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com