在Python 3中停止函数内部的循环

时间:2014-03-23 01:07:10

标签: python function loops

import random

def compareInput(n):
    if n == randomNumber: #Compares guess and the random number
        print("YAY!! you won the number was: " + n)
        return
        #(something) Loop should stop here.
    else:
        print("Wrong guess")



print("Guess the number") #Prints guess number duh!
randomNumber = str(random.randint(1,20)) #Generates a number between 1 and 20 and converts it to string
while True: #Input loop
    guess = str(input()) #Takes input and converts it to string
    if len(guess) > 0 and guess.isdigit() : #input must be a number and at lest 1 digit
        compareInput(guess) #Call compareInput function
    else:
        print("Wrong input")

如何停止while循环?

3 个答案:

答案 0 :(得分:2)

您可以使用break来破解最近的forwhile循环。在您的情况下,您需要检查compareInput循环中while的返回值,然后根据需要中断或返回。

import random

def compareInput(n):
                if n == randomNumber: #Compares guess and the random number
                        print("YAY!! you won the number was: " + n)
                        return True
                        #(something) Loop should stop here.
                else:
                        print("Wrong guess")
                        return False



print("Guess the number") #Prints guess number duh!
randomNumber = str(random.randint(1,20)) #Generates a number between 1 and 20 and converts it to string
while True: #Input loop
        guess = str(input()) #Takes input and converts it to string
        if len(guess) > 0 and guess.isdigit() : #input must be a number and at lest 1 digit
                if compareInput(guess): #Call compareInput function
                        break # We got the right guess!
        else:
                print("Wrong input")

答案 1 :(得分:1)

# assumes Python 3.x
import random

def get_int(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            # not an int, try again
            pass

def is_correct(guess, target):
    if guess == target:
        print("YAY!! you won, the number was {}".format(target))
        return True
    else:
        print("Wrong guess")
        return False

def main():
    print("Guess the number")
    target = random.randint(1,20)

    while True:
        guess = get_int("What's your guess?")
        if is_correct(guess, target):
            break

if __name__=="__main__":
    main()

答案 2 :(得分:0)

while True: #Input loop
    guess = str(input()) #Takes input and converts it to string
    if len(guess) > 0 and guess.isdigit() : #input must be a number and at lest 1 digit
        compareInput(guess) #Call compareInput function
        break  ## you exit loop with break statement
    else:
        print("Wrong input")