是否可以在“while”循环中更改变量的值?

时间:2017-07-16 15:18:24

标签: python python-3.x python-3.6

我试图编写代码来解决问题:

  

生成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再次开始时,是否可以放置tf.nn.ctc_loss以便我不会得到奇怪的结果?

或者是否有其他更简单的方法可以删除此错误?

5 个答案:

答案 0 :(得分:1)

您可以使用while循环执行任务。你应该添加异常处理方法来获取输入。

Letter A
B
Letter C
Letter D
Y
Letter Z

答案 1 :(得分:1)

首先,你只选择一次随机数,所以它总是一样的。

其次,你的游戏应该是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))

你继续循环,如果用户想要继续玩,则指定turn = 0,否则指定break = 0。

答案 2 :(得分:1)

我可能是这样写的。

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

答案 3 :(得分:1)

所有导入都应该放在文件的顶部。然后,放一个while循环,这样玩家可以在每场比赛后重新开始;这样,变量x也在每次游戏后重置。此外,第一次打印应该放在while和for循环之外,因此它只打印一次(最后一次打印将在新游戏开始时打印一个新提示)。
此时您的代码应如下所示:

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()

答案 4 :(得分:0)

整个代码嵌入在for循环中,计数器永远不会重置。如果要在for循环中重置i,则必须在for循环外定义它,以使其具有全局范围。