简体   繁体   English

这个程序一遍又一遍地循环同样的事情,我希望它做一次并继续循环下面的其他程序

[英]This program loops the same thing over and over again and I want it to do it once and continuing on to the other programs below the loop

When I run this, it just keeps on repeating itself asking for a number over and over again.当我运行它时,它只是不断重复自己一遍又一遍地要求一个数字。 I am a beginner at python so please don't judge.我是python的初学者所以请不要判断。

import random
import time

while True:
    guess = input("Please enter a lucky number between 1 to 10:\n")
    number = random.randint(0, 10)
    print ("Random number is " + str(number) + ":")
    if guess == number:
        print ("Awesome - You guessed correctly!")
        answer = input('Would you like to try again? (y/n):\n')
        def func():
            if answer == 'n':
                print ("Have a wonderful day!")
                time.sleep(2)
else:
    print("Good try, Would you like to play again? (y/n):")     
    func()

you can do it like this:你可以这样做:

import random
import time

number = random.randint(0, 10)

while True:
    guess = int(input("Please enter a lucky number between 1 to 10:\n"))
    
    print ("Random number is " + str(number) + ":")
    if guess == number:
        print ("Awesome - You guessed correctly!")
        answer = input('Would you like to try again? (y/n):\n')
        if answer == 'n':
            print ("Have a wonderful day!")
            break
        else:
            print("generating new number...")
            number = random.randint(0, 10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM