【问题标题】:Python: Looping issue or indentationPython:循环问题或缩进
【发布时间】:2014-12-05 02:26:31
【问题描述】:

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

【问题讨论】:

  • 你似乎已经做对了。
  • 你不需要那个break 声明。由于您将b 设置为True,因此循环不会执行另一次迭代。
  • 一般说明:为了方便人们帮助您,最好提出更具体的问题。在这种情况下,程序现在在做什么需要有所不同?
  • @mattm 现在没有中断声明。当我运行程序时,它要么一遍又一遍地不停地说高,要么低
  • @Player72:查看我的回答的最新编辑

标签: boolean boolean-logic python-3.4


【解决方案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.")
        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

【讨论】:

  • 因为您只提示用户输入一次数字。您提示用户输入一个数字,然后进入循环。如果他们的第一个猜测是不正确的,那么您将永远不会再次提示并无限循环。由于他们永远无法再次猜测,因此循环永远不会终止,因为第一个 if 条件永远不会满足。
猜你喜欢
  • 2016-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多