Python:循环问题或缩进

时间:2014-10-10 01:32:01

标签: boolean boolean-logic python-3.4

Python 3.4

你好!我的程序中需要布尔运算符的帮助。 您必须猜测程序设置的数字,从1到1000。 如果你认为它说得好,如果不是它说高/低。

使用While,if / elif / else(其中任何一个),以及playagain循环。

这是我到目前为止所拥有的。

import random

a = int(input("I have a number between 1 and 1000. Can you guess my number?\nPlease type your first guess."))
x = random.randrange(1,1000)
counter = 0
b = False
while not b:
    if a == x:
        print ("Excellent! You guessed the number in", counter1,"tries.")
        b = True
    elif a > x:
        print ("high")
        counter = counter + 1

    elif a < x:
        print ("low")
        counter = counter + 1

1 个答案:

答案 0 :(得分:0)

你的主要问题是你没有在循环中提示他们。

import random

x = random.randrange(1,1000)    
counter = 0 

while True:
    guess = int(input("I have a number between 1 and 1000. Can you guess my number?\nPlease type your first guess.")) 
    if guess == x:
        print ("Excellent! You guessed the number in", counter,"tries.")
        break
    else:
        if guess > x:
            print("high")
        else:
            print("low")
        counter += 1

要提示用户是否希望再次播放,请执行以下操作:

import random

x = random.randrange(1,1000)    
counter = 0 

while True:
    guess = int(input("I have a number between 1 and 1000. Can you guess my number?\nPlease type your first guess.")) 
    if guess == x:
        print ("Excellent! You guessed the number in", counter,"tries.")
        play_again = input("Type Y if you'd like to play again, or N if not")
        if play_again == 'N':
            break
    else:
        if guess > x:
            print("high")
        else:
            print("low")
        counter += 1