我試圖編寫代碼來解決一個問題:是否有可能在「while」循環中更改變量的值?
生成之間1和9(包括1和9)的隨機數。要求用戶猜出這個數字,然後告訴他們他們是否猜測得太低,太高,或者是否正確。跟蹤用戶採取了多少猜測,並在遊戲結束時打印出來。
,我寫的代碼是:
import sys
import random
x=random.randint(1,9)
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
for i in range (10):
z=input()
if int(z)<x:
print('Too low. Please try again.')
elif int(z)>x:
print('Too high. Please try again.')
elif int(z)==x:
print('You guessed it right!')
if i==0:
print('It took you a single turn! Nice')
else:
print('it took you ' + str(i+1)+' turns.')
print('Do you want to play again? Yes or No?')
j=input()
if j.lower()=='yes':
print('Okay, Please enter a number between 1 and 9 including the extremes.')
pass
else:
sys.exit()
這裏是它看起來運行時,如:
Hello there! Please enter a number between 1 and 9 including the extremes.
4
Too high. Please try again.
3
Too high. Please try again.
2
You guessed it right!
it took you 3 turns.
Do you want to play again? Yes or No?
yes
Okay, Please enter a number between 1 and 9 including the extremes.
6
Too high. Please try again.
4
Too high. Please try again.
2
You guessed it right!
it took you 6 turns.
Do you want to play again? Yes or No?
看到,代碼給出了完美的效果首先執行for
循環時。當我們嘗試第二次運行這個「遊戲」時,它會給出奇怪的結果,通過說yes
當它問我們問題:Do you want to play again? Yes or No?
。
是否有可能把i=0
當Python到達4號最後一行與for
循環從i=0
再次啓動,這樣我沒有得到怪異的結果?
或者還有其他更簡單的方法刪除此錯誤嗎?
使用while循環,而不是爲我的range(10)。然後重置計數 –