再一次,我仍然得到蟒蛇的坑。我製作了一個程序,讓用戶猜測一個由計算機隨機生成的「幻數」。經過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變量都會上升。不管它是否正確。
任何建議將非常感激,感謝提前嚮導!
你有沒有聽說過'break'? –
不要重複自己,你在循環之前和循環中都有相同的代碼。使用'while True:'。 –
我有,但我真的不知道如何將它添加到那裏。我想我可以這樣做,如果count> 6:break'。但是,作爲第一行,我會把它放在哪裏?假設這就是我需要的權利 – user2662440