简体   繁体   English

是否可以使用 try/except 语句结束 while 循环?

[英]Is it possible to end a while loop with a try/except statement?

So the goal here is to end my while loop , or my script really if a user's bank amount reaches 0 (zero) or if the user inputs a 0 (zero) for bet amount to terminate the script.所以这里的目标是结束我的while loop ,或者我的脚本,如果用户的银行金额达到0 (zero)或者用户输入0 (zero)作为下注金额以终止脚本。 THE PROBLEM is that I am NOT allowed to use a break statement, and though the program works perfectly with exit() , I cannot use that either because we haven't "gotten there yet" via the book (the instructor wants us to use what we are learning in the book and not what we already know).问题是我不允许使用break语句,尽管该程序与exit()完美配合,但我也不能使用它,因为我们还没有通过这本书“到达那里”(讲师希望我们使用我们在书中学到的,而不是我们已经知道的)。 I am just really stumped.我真的很难过。 Part of it is because I struggle a lot with the try/except statements so maybe I am just doing something wrong there, or maybe I need to try a different loop.部分原因是因为我在 try/except 语句中挣扎了很多,所以也许我只是在那里做错了什么,或者我可能需要尝试不同的循环。 Maybe you guys can help?也许你们可以帮忙? Gonna post my code below.将在下面发布我的代码。 As far as I am concerned, everything works perfectly fine, but I cannot use exit() or break so I need some advice on another python basics-orientated method... So can I use try/except?就我而言,一切正常,但我不能使用exit()break所以我需要一些关于另一个面向 Python 基础的方法的建议......所以我可以使用 try/except 吗? If so, how?如果是这样,如何? I need the program to continue looping unless banking reaches 0 (zero) or user input is equal to 0 (zero) , it's why I chose the while loop .我需要程序继续循环,除非银行达到0 (zero)或用户输入等于0 (zero) ,这就是我选择while loop的原因。 Do I need to use a different loop method?我需要使用不同的循环方法吗? The help will be GREATLY appreciated and I thank everyone in advance.非常感谢您的帮助,我提前感谢大家。

import random

def rollDice(cnt):
    die1 = random.randint(1,6)
    die2 = random.randint(1,6)
    x = int(die1 + die2)
    print('Roll #', cnt, 'was', x)
    return x

def total_bank(bank):
    bet = 0
    while bet <= 0 or bet > min([500,bank]):
        print(f'You have ${bank} in your bank.')
        get_bet = input('Enter your bet (or 0 to quit): ')
        if get_bet == '0': 
            print('Thanks for playing!')
            exit()
        bet = int(get_bet)
    return bank,bet

def get_guess():
    guess = 0
    while (guess < 2 or guess > 12):
        try:
            guess = int(input('Choose a number between 2 and 12: '))
        except ValueError:
            guess = 0
        return guess

bank = 500
guess = get_guess
rcnt = 1

while rcnt < 4:
    rcnt = 0
    bank,bet = total_bank(bank)
    guess = get_guess()
    if guess == rollDice(rcnt+1):
        bank += bet * 2
    elif guess == rollDice(rcnt+2):
        bank += bet * .5
    elif guess == rollDice(rcnt+3):
        bank = bank
    else:
        bank = bank - bet
        if bank == 0:
            print(f'You have ${bank} in your bank.')
            print('Thanks for playing!')
            exit()

You can certainly exit the loop using an exception;您当然可以使用异常退出循环; just raise an exception inside your while loop, and catch it outside the loop:只需在while循环内引发异常,并在循环外捕获它:

def total_bank(bank):
    bet = 0
    try:
        while bet <= 0 or bet > min([500,bank]):
            print(f'You have ${bank} in your bank.')
            get_bet = input('Enter your bet (or 0 to quit): ')
            if get_bet == '0': 
                print('Thanks for playing!')
                raise StopIteration()
            bet = int(get_bet)
    except StopIteration:
        pass
    return bank,bet

But even easier is just to return from inside the loop:但更简单的是从循环内部返回:

def total_bank(bank):
    bet = 0
    while bet <= 0 or bet > min([500,bank]):
        print(f'You have ${bank} in your bank.')
        get_bet = input('Enter your bet (or 0 to quit): ')
        bet = int(get_bet)
        if get_bet == '0': 
            print('Thanks for playing!')
            return bank, bet
        return bank, bet

我对 try 和 except 函数不是很了解,但是使用 try 块,您可能会引发错误并像这样结束程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM