是否有可能在“while”循环中更改变量的值?
我试图编写代码来解决一个问题:是否有可能在“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循环执行任务。你应该添加异常处理方法来获取输入。
import random
cond = True
while cond:
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
x=random.randint(1,9)
for i in range (10):
z=int(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!')
import sys
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':
break
else:
cond = False
sys.exit()
感谢您的回答!你能告诉我,为什么你在最后一行放了'cond = False'?代码运行良好,没有它! –
由于'''sys.exit()'''语句程序将退出。 – Bodhi94
整个代码嵌入在for循环中,计数器永远不会重置。如果要在for循环中重置i,则必须在for循环之外定义它,以便它具有全局范围。
这是行不通的。即使我将i声明为全局变量,只要我进入for循环,它就会被更改。 –
首先,你只选择一次随机数,所以它总是相同的。其次,你的游戏应该在while循环中而不是for循环中(如果你想让玩家在猜中后重新启动)。
turns = 0
while True:
secret_number = random.randint(1,9)
print('Please enter a number between 1 and 9 including the extremes.')
guess = input()
turns += 1
if int(guess) < secret_number:
print("Too low")
elif int(guess) > secret_number:
print("Too high")
else:
print("You guessed in {} turn(s)".format(turns))
您继续循环,如果用户想继续玩轮流分配= 0,或者你分手,如果他没有。
我会这样写,可能。
from itertools import count
from random import randint
def run_game():
random_value = randint(1, 9)
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
for i in count():
guess_string = input()
try:
guess = int(guess_string)
except ValueError:
print("Invalid value given for guess: {}".format(guess_string))
if guess < random_value:
print("Too low! Please try again.")
elif guess > random_value:
print("Too high! Please try again.")
else:
print('You guessed it right!')
if not i:
print('It took you a single turn! Nice')
else:
print('it took you {} turns.'.format(i + 1))
print('Do you want to play again? Yes or No?')
response_string = input()
return response_string.lower() == 'yes'
if __name__ == "__main__":
while run_game():
pass
但是,对于理解简单:
from itertools import count
from random import randint
if __name__ == "__main__":
playing = True
while playing:
random_value = randint(1, 9)
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
for i in count():
guess_string = input()
try:
guess = int(guess_string)
except ValueError:
print("Invalid value given for guess: {}".format(guess_string))
if guess < random_value:
print("Too low! Please try again.")
elif guess > random_value:
print("Too high! Please try again.")
else:
print('You guessed it right!')
if not i:
print('It took you a single turn! Nice')
else:
print('it took you {} turns.'.format(i + 1))
print('Do you want to play again? Yes or No?')
response_string = input()
if response_string.lower() != 'yes':
playing = False
break
所有进口应该在文件的顶部。然后,放一段时间,让玩家在每场比赛后重新开始;这样,变量x在每场比赛之后也被重置。此外,第一个打印应该放在while和for循环之外,所以它只打印一次(最后一个if会在新游戏开始时打印一个新提示)。
你在这一点上的代码应该是这样的:
import random
import sys
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
while True:
x=random.randint(1,9)
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.')
else:
sys.exit()
使用while循环,而不是为我的range(10)。然后重置计数 –