在while循环中嵌套if / else语句

时间:2019-01-11 18:11:56

标签: python python-3.x if-statement while-loop

这是一个文字冒险游戏。用户面临着第一种情况AtomicBoolean firstReposition = new AtomicBoolean(true); //Create position call ISSPositionService service = ServiceGenerator.createService(ISSPositionService.class); //create observable Observable<ISSPositionData> issPositionCall = service.getPosition(); Disposable disposable = issPositionCall.subscribeOn(Schedulers.io()) .repeatWhen(completed -> completed.delay(30, java.util.concurrent.TimeUnit.SECONDS)) .observeOn(AndroidSchedulers.mainThread()) .subscribe(positionData -> { LatLng currentIssPosition = new LatLng(positionData.getIssPosition().getLatitude(), positionData.getIssPosition().getLongitude()); if (firstReposition) { issMarkerOptions.position(currentIssPosition); map.addMarker(issMarkerOptions); firstReposition.set(false); } else { issMarker.setPosition(currentIssPosition); } //animate camera so it shows current position map.animateCamera(CameraUpdateFactory.newLatLng(currentIssPosition)); }); 。如果他们选择2,游戏将继续。如果他们选择1,他们将死亡,并有机会再次玩。不知道我在做什么错。

a()

编辑:从下面的评论中得出的解决方案很简单:

"""
MAIN LOOP
"""
play_again = "yes"
while play_again == "yes" or play_again == "y":
    a()  # user makes a choice
    choice = choose_ans()
    check_ans_a(choice)  # intention: if user chooses "1", they die and are asked to play again
        if choice == "1":  # problem: Unexpected indent. If indent is deleted, b() becomes unreachable
            play_again = input('Play again?\n'
                               '(y)es ')
            break
        else:
            continue
    b()
    choice = choose_ans()
    check_ans_b(choice)

3 个答案:

答案 0 :(得分:2)

问题出在您的else: continue上。如果代码进入if块,它将break退出while循环。但是,如果不满足条件,将进入else块。在while循环内,continue将自动转到循环顶部并重新开始,这就是从未达到b()的原因。

答案 1 :(得分:0)

问题是继续。继续使代码再次“跳转”到while循环的开始。建议:删除else / continue部分。如果只有这两个选项,则不需要。如果a == 1,则中断将退出while循环。如果其2 a == 2不为True,则将测试其后的零件(b)。

https://www.tutorialspoint.com/python3/python_continue_statement.htm

答案 2 :(得分:0)

尝试运行此版本的代码以进行调试,请注释/取消注释以查看结果如何变化。我使用random模拟了用户输入摆脱了方法调用的情况。

import random

play_again = "yes"
while play_again == "yes" or play_again == "y":
    choice = random.choice(["1","2"])
    print('choice = choose_ans()', choice)
    if choice == "1":
        play_again = random.choice(["yes","no"])
        print('play_again?', play_again)
        # break # <-- the break control is already made by while condition
    # else:
    #     continue
    # b()
    choice = random.choice(["1","2"])
    print('check_ans_b(choice)', choice)