2013-11-04 45 views
1
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,我怎么能得到循环终止?打破了蟒蛇循环不使用破

+0

你可以将你的代码封装在一个函数中,然后使用'return'语句退出。 – jramirez

+1

或者创建另一个布尔变量,并在while语句中使用'and'检查它的值 – jacktheripper

回答

4

您可以:

  • 使用标志变量;你已经在使用一个,只是重复使用它在这里:从功能

    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 
    
+1

我想他想添加一个* additional *条件来打破:while answer =='y'或most_recent_roll == first_roll' –

+0

是否事情的条件是什么?这不是重要的条件,它是退出循环的方法。 –

+0

绝对,这就是我给+1的原因。但是他已经在他的代码中使用了一个标志变量,即使不是有意的,并且可能正在寻找使用另一个标志的指针。 –

1

你可以使用变量,如果你想退出循环,你将设置为false

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

是否允许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”,以便当您返回到顶部重新评估条件时,它是错误的并且循环终止。

1

获得一些奖励积分和注意力,使用发电机功能。

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