【问题标题】:I'm trying to write a number guessing game in python but my program isn't working我正在尝试用 python 编写一个猜数字游戏,但我的程序不工作
【发布时间】:2015-11-07 19:12:30
【问题描述】:

该程序应该随机生成一个介于 1 和 10(含)之间的数字,并要求用户猜测该数字。如果他们猜错了,他们可以再次猜测,直到他们猜对为止。如果他们猜对了,程序应该祝贺他们。

这就是我所拥有的,但它不起作用。我输入一个介于 1 和 10 之间的数字,但没有祝贺。当我输入一个负数时,什么也没有发生。

import random


number = random.randint(1,10)

print "The computer will generate a random number between 1 and 10. Try  to guess the number!"

guess = int(raw_input("Guess a number: "))


while guess != number:
    if guess >= 1 and guess <= 10:
       print "Sorry, you are wrong."
       guess = int(raw_input("Guess another number: ")) 
   elif guess <= 0 and guess >= 11: 
      print "That is not an integer between 1 and 10 (inclusive)."
      guess = int(raw_input("Guess another number: "))
   elif guess == number:
     print "Congratulations! You guessed correctly!"

【问题讨论】:

  • 你是如何生成number的?
  • 首先,while 循环中的所有内容都取决于猜测是否错误。然后在其中,如果第一个 if 条件匹配(即如果 guess 在 1 和 10 之间),则告诉玩家他们错了。这将阻止猜测正确的情况。
  • 把祝贺移到while循环外,去掉最后一个elif
  • guess &lt;= 0 and guess &gt;= 11 永远不能是True。你需要guess &lt;= 0 or guess &gt;= 11

标签: python python-2.7


【解决方案1】:

只需将祝贺信息移到循环之外。然后,您也可以在循环中只有一个猜测输入。以下应该有效:

while guess != number:
    if guess >= 1 and guess <= 10:
        print "Sorry, you are wrong."
    else:
        print "That is not an integer between 1 and 10 (inclusive)."

    guess = int(raw_input("Guess another number: "))

print "Congratulations! You guessed correctly!"

【讨论】:

  • 对于3-guess版本,您可以添加一个以while True:开头的外循环,并在循环的底部询问用户是否想再玩一次。如果答案是否定的,则执行break 语句退出循环。
【解决方案2】:

问题在于,在 if/elif 链中,它从上到下评估它们。 将最后一个条件上移。

if guess == number:
   ..
elif other conditions.

您还需要更改您的 while 循环以允许它在第一次进入。例如。

while True:
 guess = int(raw_input("Guess a number: "))
 if guess == number:
   ..

然后在你有条件结束游戏时休息。

【讨论】:

  • 鉴于while 条件,它永远不会匹配该条件。
  • 这不会有任何区别。循环体只执行是guess 不等于number
  • 我应该把它改成“while guess >=1 and guess
  • 如果您要像这样检查它,则需要初始化猜测。但是,如果您将其初始化为 1,那么当然,如果您键入 11,它将结束。
【解决方案3】:

问题是,如果正确猜测的条件为真,则退出 while 循环。我建议解决此问题的方法是将祝贺移到 while 循环之外

import random


number = random.randint(1,10)

print "The computer will generate a random number between 1 and 10.   Try  to guess the number!"

guess = int(raw_input("Guess a number: "))


while guess != number:
    if guess >= 1 and guess <= 10:
       print "Sorry, you are wrong."
       guess = int(raw_input("Guess another number: ")) 
    elif guess <= 0 and guess >= 11: 
       print "That is not an integer between 1 and 10 (inclusive)."
       guess = int(raw_input("Guess another number: "))

if guess == number:
 print "Congratulations! You guessed correctly!"

【讨论】:

    猜你喜欢
    • 2021-07-03
    • 2018-06-25
    • 1970-01-01
    • 2013-03-31
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2023-01-22
    • 1970-01-01
    相关资源
    最近更新 更多