如何跳出 Python 中的 while 循环? [英] How to break out of while loop in Python?

查看:27
本文介绍了如何跳出 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

推荐答案

一些变化意味着只有 Rr 会滚​​动.任何其他字符都会退出

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天全站免登陆