[英]Control loop for a number-guessing game in Python
我正在尝试编写一个程序,该程序生成一个伪随机数,并允许用户猜测它。 当用户最有可能猜到数字错误时,我希望函数返回条件循环的开头,而不是函数的开头(这将使其生成新的伪随机数)。 这是我到目前为止的内容:
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()
如何使伪随机数在本地不可变,以便在错误猜测之后数字不会改变?
尽管在这里循环可能是执行此操作的更好方法,但是这里可以通过最少的代码更改来递归地实现它:
def guessingGame(n=None):
if n is None:
import random
n = random.randint(1, 10)
input = raw_input("Guess what integer I'm thinking of.")
if int(input) == n:
print "Correct!"
elif int(input) < n:
print "Too low."
guessingGame(n)
elif int(input) > n:
print "Too high."
guessingGame(n)
else:
print "Huh?"
guessingGame(n)
通过为guessingGame()
提供可选参数,您可以获得所需的行为。 如果未提供参数,则它是初始调用,您需要在将当前n
传递给调用之后的任意时间随机选择n
,这样就不必创建新参数。
请注意,对random()
的调用已替换为randint()
,因为random()
返回的浮点数介于0和1之间,并且您的代码似乎是期望值和整数。
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()
导入随机数并在函数之外生成随机数? 您可能还想为生成的整数设置范围,例如n = random.randint(1,max)
甚至可以让用户预设最大值。
在这里要做的最简单的事情可能就是在这里使用循环-无需递归。
但是,如果您设置使用递归,则可以将条件放入其自己的函数中,该函数将随机数作为参数,并且可以递归调用自身而无需重新计算数字。
在不同的方法(也称为函数)中创建类并定义逻辑可能是最好的选择。 查看Python文档 ,获取有关类的更多信息。
from random import randint
class GuessingGame (object):
n = randint(1,10)
def prompt_input(self):
input = raw_input("Guess what integer I'm thinking of: ")
self.validate_input(input)
def validate_input(self, input):
try:
input = int(input)
self.evaluate_input(input)
except ValueError:
print "Sorry, but you need to input an integer"
self.prompt_input()
def evaluate_input(self, input):
if input == self.n:
print "Correct!"
elif input < self.n:
print "Too low."
self.prompt_input()
elif input > self.n:
print "Too high."
self.prompt_input()
else:
print "Huh?"
self.prompt_input()
GuessingGame().prompt_input()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.