数字游戏:不能赢:不打印:你赢,但结束脚本

时间:2017-05-16 01:22:20

标签: python

我的问题是,当我得到正确的数字时,python脚本会结束,但不会打印:for i in a: print(i)

You win!

我只有11岁,刚开始编程几个月前,请帮助我!

2 个答案:

答案 0 :(得分:2)

如果猜测正确,您的代码将失败第一个条件:

while guess != number and tries > 0 :

如果猜测完成,循环将在你的else语句之后中断,并且永远不会返回到if条件检查猜测。

由于在输入正确答案之前无法继续循环,因此您可以按如下方式编写:

import random 

number = random.randint(1,100) # This part works fine

guess = input('Guess a number between 1 and 100: ') #Asks question

guess = float(guess)

tries = 10 

while guess != number and tries > 0 :

    if guess < number:    # This part works fine
        print('Too low')
        tries = tries - 1
        print('You have %s tries left' % (tries))

    if guess > number:
        print('Too high')     # This part is also good
        tries = tries - 1
        print('You have %s tries left' % (tries))

    if tries == 0:
        print('You lose!')
        print('The answer was ' + str(number)) 
        continue

    else :
       guess = input('Try Again: ')
       guess = float(guess)

print('You win!')

请记住,这有一个错误会导致你赢了,也会在用户用完猜测后打印出来。我决定把它留在这里,因为我觉得它很容易修复,并且对你有好处,可以自己去学习。如果您希望我为您这样做,请随意在评论中写一下。

我还建议您在帖子中使用代码注释。在这种情况下,我会提出您的问题的代码如下:

import random 

number = random.randint(1,100) # This part works fine

guess = input('Guess a number between 1 and 100: ') #Asks question

guess = float(guess)

tries = 10 

while guess != number and tries > 0 :

    if guess < number:    # This part works fine
        print('Too low')
        tries = tries - 1
        print('You have %s tries left' % (tries))

    if guess > number:
        print('Too high')     # This part is also good
        tries = tries - 1
        print('You have %s tries left' % (tries))

    if tries == 0:
        print('You lose!')
        print('The answer was ' + str(number)) 
        continue

    if guess == number :
        print('You win!')       # Why doesn't this work?
                # Python ends at this line if I get it right, but doesn't print: You win!

    else :
       guess = input('Try Again: ')
       guess = float(guess)

pass     # WHILE*

答案 1 :(得分:1)

在代码中进行比较时,通常最好只尝试一次特定问题(进行比较)。在这里,我展示了一种方法来重构你的两个问题(正确的猜测和尝试),只做一次问题。

import random

number = random.randint(1, 100) 
guess = input('Guess a number between 1 and 100: ')  # Asks question
guess = float(guess)

tries = 10
while True:
    tries -= 1

    if guess < number:
        print('Too low')
        print('You have %s tries left' % (tries))

    elif guess > number:
        print('Too high')
        print('You have %s tries left' % (tries))

    else:
        print('You win!')
        break

    if tries == 0:
        print('You lose!')
        print('The answer was ' + str(number))
        break

    guess = input('Try Again: ')
    guess = float(guess)