我试图编写代码来解决一个问题:是否有可能在“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)。然后重置计数 –