python - 如何循环回到开头
问题描述
我将如何解决这个问题:
print 'Adventure Game'
choice_1 = raw_input('You are travelling down a long road, there is a fork in the route, one side goes to a jungle, and the other leads to a hill biome, which side do you choose? J for Jungle, H for Hill ')
if choice_1 == 'J':
print 'Jungle?, very well then'
elif choice_1 == 'H':
print 'Hill, good decision'
if choice_1 == 'J':
choice_2 = raw_input('In the jungle, a king cobra appears behind you, as you look forward, an ape leaps from a tree onto the ground. Do you take your chances with the venomous king cobra, or the enormous ape? C for cobra, A for ape ')
while choice_2 != 'A':
print 'Sorry, you were bit by the cobra and died'
print 'Please try again'
if choice_2 == 'A':
break
elif choice_2 == 'A':
print 'You were almost mauled by the ape, luckily, it fleed the scene after loosing sight of you'
如果用户为choice_2选择c,我希望它重新启动,这样每次发生这种情况时它都会从头开始
解决方案
我建议为每个位置使用函数,这样您就可以多次调用相同的函数或在其他函数中调用相同的函数。
例如:
def road():
choice = ''
while choice not in ['j','h']:
choice = raw_input('You are travelling down a long road, there is a fork in the route, one side goes to a jungle, and the other leads to a hill biome, which side do you choose? J for Jungle, H for Hill ').lower()
if choice == 'j':
jungle()
elif choice == 'h':
hill()
def jungle():
choice = ''
while choice not in ['c','a']:
choice = raw_input('In the jungle, a king cobra appears behind you, as you look forward, an ape leaps from a tree onto the ground. Do you take your chances with the venomous king cobra, or the enormous ape? C for cobra, A for ape ').lower()
if choice == 'c':
print 'Sorry, you were bit by the cobra and died'
print 'Please try again'
return
elif choice == 'a':
print 'You were almost mauled by the ape, luckily, it fleed the scene after loosing sight of you'
next_func_here()
while True:
print 'Adventure Game Starts Here!'
road()
print 'restarting...'
这样您就可以快速轻松地继续添加功能,并且也更易于调试。while
循环意味着如果退出road()
,它会循环回到开头并重新启动road()
。
推荐阅读
- sql-server - 使用 pentaho 数据集成器从 SQL Server 表中的 varchar(max) 列加载 Oracle 表中的 clob 列时提高性能
- matlab - 如何将数据采集 Matlab 脚本转换为 Simulink?
- typescript - Vue 根据条件选择选项
- laravel - Laravel 5.6 嵌套查询关系
- javascript - 如何在不刷新页面的情况下格式化模态内容
- kubernetes - 未经授权获取 kubectl api-versions
- python - Python 3.4.3 - 多项目追加和列表扩展
- java - LibGDX:AssetManager 有限制吗?
- rest - microsoft sharepoint 使用 REST API 访问文档返回 404
- php - laravel 服务提供者对 laravel 有什么用