Python中的猜数字游戏的控制循环 [英] Control loop for a number-guessing game in Python

查看:307
本文介绍了Python中的猜数字游戏的控制循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个生成伪随机数并允许用户猜测的程序.当用户最有可能猜到数字错误时,我希望函数返回条件循环的开头,而不是函数的开头(这将使其生成新的伪随机数).这是我到目前为止的内容:

I'm trying to write a program which generates a pseudo-random number and allows the user to guess it. When the user guesses the number wrong, as is most likely, I would like the function to return to the beginning of the conditional loop, not the very beginning of the function (which would cause it to generate a new pseudo-random number). Here's what I have so far:

def guessingGame():
    import random
    n = random.random()
    input = raw_input("Guess what integer I'm thinking of.")
    if int(input) == n:
        print "Correct!"
    elif int(input) < n:
        print "Too low."
        guessingGame()
    elif int(input) > n:
        print "Too high."
        guessingGame()
    else:
        print "Huh?"
        guessingGame()

如何使伪随机数在本地不可变,以便在错误猜测之后数字不会更改?

How could make the pseudo-random number locally immutable so that after a wrong guess the number would not change?

推荐答案

from random import randint

def guessingGame():
    n = randint(1, 10)
    correct = False
    while not correct:
        raw = raw_input("Guess what integer I'm thinking of.") 
        if int(i) == n:
            print "Correct!"
            correct = True
        elif int(i) < n:
            print "Too low."
        elif int(i) > n:
            print "Too high."
        else:
            print "Huh?"

guessingGame()

这篇关于Python中的猜数字游戏的控制循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆