简体   繁体   中英

breaking out of python loop without using break

while answer  == 'Y':
    roll = get_a_roll()
    display_die(roll)
    if roll == first_roll:
        print("You lost!")
    amount_won = roll
    current_amount = amount_earned_this_roll + amount_won
    amount_earned_this_rol = current_amoun
    print("You won $",amount_won)
    print(  "You have $",current_amount)
    print("")
    answer = input("Do you want to go again? (y/n) ").upper()


if answer == 'N':
    print("You left with $",current_amount)
else:
    print("You left with $",current_amount)

The purpose here of using this loop is in a game, dice are rolled, and you are rewarded money per the number of your roll, unless you roll a roll matching your first roll. Now, I need the loop to stop if that occurs, and I know this is easily achievable using a break statement, however, I have been instructed no break statements are allowed. How else can I get the loop to terminate if roll == first_roll?

You can:

  • Use a flag variable; you are already using one, just reuse it here:

     running = True while running: # ... if roll == first_roll: running = False else: # ... if answer.lower() in ('n', 'no'): running = False # ...
  • Return from a function:

     def game(): while True: # ... if roll == first_roll: return # ... if answer.lower() in ('n', 'no'): return # ...
  • Raise an exception:

     class GameExit(Exception): pass try: while True: # ... if roll == first_roll: raise GameExit() # ... if answer.lower() in ('n', 'no'): raise GameExit() # ... except GameExit: # exited the loop pass

You could use a variable that you will set to false if you want to exit the loop.

cont = True
while cont:
    roll = ...
    if roll == first_roll:
        cont = False
    else:
        answer = input(...)
        cont = (answer == 'Y')

Get some bonus points and attention, use a generator function.

from random import randint

def get_a_roll():
    return randint(1, 13)

def roll_generator(previous_roll, current_roll):
    if previous_roll == current_roll:
        yield False
    yield True

previous_roll = None 
current_roll = get_a_roll()

while next(roll_generator(previous_roll, current_roll)):
    previous_roll = current_roll
    current_roll = get_a_roll()
    print('Previous roll: ' + str(previous_roll))
    print('Current roll: ' + str(current_roll))
print('Finished')

Is continue allowed? It's probably too similar to break (both are a type of controlled goto , where continue returns to the top of the loop instead of exiting it), but here's a way to use it:

while answer  == 'Y':
    roll = get_a_roll()
    display_die(roll)
    if roll == first_roll:
        print("You lost!")
        answer = 'N'
        continue
    ...

If when you lose, answer is hard-coded to "N" so that when you return to the top to re-evaluate the condition, it is false and the loop terminates.

import random


# Select highest score

def highest_score(list_of_scores):
    m_score = 0

    m_user = 1

    for user in list_of_scores:

        if m_score <= list_of_scores.get(user):
            m_score = list_of_scores.get(user)

            m_user = user

    return m_score, m_user


# -----------------------------------------------------------------------------------------------------------------------------------------------


# Get the dice value

def dice_value():
    d1 = random.randint(1, 6)
    return d1


# -------------------------------------------------------------------------------------------------------------------------------------------------


# Prints the game instructions such as opening message and the game rules


print(
    "\n**************************************************************************************************************\n")

print("                                          Welcome To OVER 12!\n")

print("                                           << GAME RULES >> ")

print(
    "______________________________________________________________________________________________________________\n")

print("   <<< Each player rolls a single dice and can choose to roll again (and again) if they choose")

print("   <<< Their total is the sum of all their rolls")

print("   <<< The target is 12, if they go over twelve they score zero")

print("   <<< Once a player decides to stay the next player takes their turn")

print("   <<< DO FOLLOW THE INSRUCTIONS PROPERLY (Use ONLY Yes/No) ")

print(
    "______________________________________________________________________________________________________________\n")

# ---------------------------------------------------------------------------------------------------------------------------------------------------


game_over = True

player_score = {}

game_started = False

while game_over:

    exit_game = input('Exit The Game (Yes/No)? ')
    # The Player Can Either Start The Game Saying Yes or Exit The Game Without Starting By Saying No

    if exit_game == 'Yes':

        game_over = False




    else:

        game_started = True

        no_of_players = int(input('\n<< How Many Players Are Playing ? '))

        for player in range(1, no_of_players + 1):

            print(f'\n   Now playing player {player}')

            continue_same_player = True
            # If The Same Player Needs To Play
            total_score = 0

            while continue_same_player:

                d2 = dice_value()

                total_score = total_score + d2

                if total_score >= 12:
                    print('\nSorry..!, Your Total Score Is OVER 12, You Get ZERO!!')

                    total_score = 0

                print(f'\n   Dice Turned Value Is: {d2}')

                print(f'   Your Total Score is: {total_score}')

                same_player = input('\n<< Continue With The Same Player (Yes/No)? ')

                if same_player == 'No':
                    # If The Player Needs To Be Changed
                    player_score[player] = total_score

                    continue_same_player = False

                    print(f'\nPlayer {player} Total Score Is {total_score}')
                    break

# --------------------------------------------------------------------------------------------------------------------------------------------------


if game_started:
    u1 = highest_score(player_score)
    # Display The Highest User Score

    print(f'\n    << Highest Score User Is: {u1[1]} ')
    # The Most Scored Player Is Being Calculated
    print(f'\n    << Player Highest Score Is: {u1[0]}')

print(
    '\n   Good Bye....! \n   Thank You For Playing OVER 12.. \n   See You Again!!')  # Prints The Ending Message For the Players

explanation: you define an end_game function that does what you want at the end then ends the code

#do this 
def end_game()
    if answer == 'N':
        print("You left with $",current_amount)
    else:
        print("You left with $",current_amount)
        exit()
while answer  == 'Y':
    roll = get_a_roll()
    display_die(roll)
    if roll == first_roll:
        print("You lost!")
        end_game()
    amount_won = roll
    current_amount = amount_earned_this_roll + amount_won
    amount_earned_this_rol = current_amoun
    print("You won $",amount_won)
    print(  "You have $",current_amount)
    print("")
    answer = input("Do you want to go again? (y/n) ").upper()
    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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