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

0 投票
3 回答
507 浏览
提问于 2025-04-17 23:28
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")

我该如何停止这个循环?

3 个回答

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

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

1

在编程中,有时候我们会遇到一些问题,可能是因为代码写得不够清晰,或者是我们对某些概念理解得不够透彻。比如,有人可能在使用某个函数时,不知道它具体是怎么工作的,或者它的参数应该怎么设置。

这时候,我们可以去一些技术论坛,比如StackOverflow,去寻找答案。在这些地方,很多有经验的程序员会分享他们的解决方案和经验,帮助我们更好地理解问题。

总之,遇到问题时,不要害怕去问,很多人都愿意提供帮助。只要我们保持好奇心,努力学习,就一定能找到解决办法。

# 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

你可以使用 break 来结束最近的 forwhile 循环。在你的情况下,你需要在 while 循环中检查 compareInput 的返回值,然后根据需要选择结束循环或返回。

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

撰写回答