2
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?

2
  • you can encapsulate your code in a function then use the return statement to get out. Commented Nov 4, 2013 at 17:56
  • 1
    Or create another boolean variable and check its value in the while statement using and Commented Nov 4, 2013 at 17:56

6 Answers 6

5

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
    
Sign up to request clarification or add additional context in comments.

5 Comments

I think he want's to add an additional condition for breaking: while answer=='y' or most_recent_roll == first_roll
Does it matter what the conditions are? It's not the condition that matters here, its the method of exiting the loop.
Absolutely, that's why I gave +1. But he already used a flag variable in his code, even if not knowingly, and probably was looking for the pointer to use another one.
The first variant would need a continue after the first running = False (or an else branch, since continue is presumable "forbidden" as well).
@SvenMarnach: yes, it was sort of implicit. I'll make that explicit.
1

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')

Comments

1

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')

Comments

0

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.

Comments

0
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

Comments

0

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()
    

2 Comments

Please don't post only code as an answer, but also provide an explanation of what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes
explanation: you define an end_game function that does what you want at the end then ends the code

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.