如何在Python中突破while循环? [英] How to break out of while loop in Python?

查看:89
本文介绍了如何在Python中突破while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须为我的补习班制作这款游戏​​,但我不知道如何摆脱这种循环。看,我必须与计算机对抗,滚动更大的数字,看看谁的得分更高。但是我不知道该如何轮流休息并过渡到计算机。我需要 Q(退出)来表示计算机开始转动,但我不知道该怎么做。

I have to make this game for my comp class, and I can't figure out how how break out of this loop. See, I have to play against the "computer," by rolling bigger numbers, and seeing who has the bigger score. But I can't figure out how to "break" from my turn, and transition to the computers turn. I need "Q" (quit) to signal the beginning of the computers turn, but I don't know how to do it.

ans=(R)
while True:
    print('Your score is so far '+str(myScore)+'.')
    print("Would you like to roll or quit?")
    ans=input("Roll...")
    if ans=='R':
        R=random.randint(1, 8)
        print("You rolled a "+str(R)+".")
        myScore=R+myScore
    if ans=='Q':
        print("Now I'll see if I can break your score...")
        break


推荐答案

进行一些更改意味着仅 R r 会滚动。其他任何字符都会退出

A couple of changes mean that only an R or r will roll. Any other character will quit

import random

while True:
    print('Your score so far is {}.'.format(myScore))
    print("Would you like to roll or quit?")
    ans = input("Roll...")
    if ans.lower() == 'r':
        R = np.random.randint(1, 8)
        print("You rolled a {}.".format(R))
        myScore = R + myScore
    else:
        print("Now I'll see if I can break your score...")
        break

这篇关于如何在Python中突破while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆