[英]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)
此處使用此循環的目的是在游戲中擲骰子,並根據擲骰數獲得獎勵,除非擲出的擲骰與第一次擲骰相匹配。 現在,如果發生這種情況,我需要循環停止,並且我知道使用 break 語句可以輕松實現這一點,但是,我被指示不允許使用 break 語句。 如果 roll == first_roll,我還能如何終止循環?
你可以:
使用標志變量; 您已經在使用一個,只需在此處重用它:
running = True while running: # ... if roll == first_roll: running = False else: # ... if answer.lower() in ('n', 'no'): running = False # ...
從函數返回:
def game(): while True: # ... if roll == first_roll: return # ... if answer.lower() in ('n', 'no'): return # ...
引發異常:
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
如果要退出循環,可以使用將設置為false
的變量。
cont = True
while cont:
roll = ...
if roll == first_roll:
cont = False
else:
answer = input(...)
cont = (answer == 'Y')
獲得一些獎勵積分和關注,使用生成器功能。
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')
允許continue
嗎? 它可能與break
太相似了(兩者都是一種受控的goto
,其中continue
返回到循環的頂部而不是退出它),但這里有一種使用它的方法:
while answer == 'Y':
roll = get_a_roll()
display_die(roll)
if roll == first_roll:
print("You lost!")
answer = 'N'
continue
...
如果您輸了, answer
被硬編碼為“N”,這樣當您返回頂部重新評估條件時,結果為假,循環終止。
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
解釋:您定義了一個 end_game 函數,該函數在最后執行您想要的操作,然后結束代碼
#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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.