![](/img/trans.png)
[英]I'm trying to write a Python program to find the number of notes in an integer, but my code isn't working
[英]I'm trying to write a number guessing game in python but my program isn't working
该程序应该随机生成一个介于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!"
只需将祝贺消息移到循环外即可。 然后,循环中也只能有一个猜测输入。 以下应该工作:
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!"
问题是在if / elif链中,它从上到下对其进行评估。 向上移动最后一个条件。
if guess == number:
..
elif other conditions.
另外,您需要更改while循环以允许它在第一次进入。 例如。
while True:
guess = int(raw_input("Guess a number: "))
if guess == number:
..
然后在您有条件结束游戏时休息。
问题是,如果正确猜测的条件为true,则退出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!"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.