再一次,我仍然掌握python的窍门。我制作了一个程序,让用户猜测一个由计算机随机生成的“幻数”。在 5 次错误尝试后,它以加法问题的形式提供提示,使用两个随机生成的变量,其总和等于幻数。
这是代码:
def moot():
count = 0
# magicNumber is the randomly generated number from 1 to 100 that must be guessed
magicNumber = random.randint(1,100)
var1 = 0
var2 = 0
guess = eval(input('Enter a number: '))
# This loop sets random values for var1 and var2 that sum up to the magicNumber
while var1 + var2 != var:
var2 = random.randint(1,100)
var3 = random.randint(1,100)
# an addition problem is made from var1 and var2 to be used as a hint later
hint = 'Try adding '+ str(var1)+ ' and '+ str(var2)+'\n'
# withinRange checks to see if the users guess is (valid) within the range of 1 to 100
# if not, asks for another number until a valid one is provided
withinRange = True if (guess <= 100 and guess >= 1) else False
while not withinRange:
count = count + 1
guess = eval(input('Number is invalid.Enter a number between 1 and 100: '))
withinRange = True if (guess <= 100 and guess >= 1) else False
# rng tells the user if his guess is too high or low
rng = 'low' if guess < magicNumber else 'high'
# the following loop repeatedly asks for input until the user enteres the majicNumber
while magicNumber != guess:
count = count + 1
print('\nThats incorrect. Your number is too',rng,end='\n')
# after 5 incorrect guesses the program prints out the addition problem that
# was made using var1 and var2
if count > 5:
print(hint)
guess = eval(input('Guess: '))
withinRange = True if (guess <= 100 and guess >= 1) else False
while not withinRange:
count = count + 1
guess = eval(input('Nope, has to be between 1 and 100. Try again: '))
withinRange = True if (guess <= 100 and guess >= 1) else False
rng = 'low' if guess < magicNumber else 'high'
print('\nYou entered the right number!')
print('Number:',magicNumber)
print('range of last guess was too',rng)
print('Number of guesses:',count + 1)
上次,有人告诉我,我没有提供有关我的程序的足够信息。我希望我没有过度使用评论。这是我的目标/问题/查询/目标:我想在程序中添加一些代码行,让它在 7 次尝试后终止。
该程序现在所做的是一遍又一遍地接受猜测,直到找到正确的猜测。但我想添加一些代码,在“count”变量达到 6 后将其杀死。每次输入猜测时,count 变量都会上升。不管它是否正确。
任何建议将不胜感激,在此先感谢向导!