[英]I'm trying to write a number guessing game in python but my program isn't working
The program is supposed to randomly generate a number between 1 and 10 (inclusive) and ask the user to guess the number. 该程序应该随机生成一个介于1到10(含)之间的数字,并要求用户猜测该数字。 If they get it wrong, they can guess again until they get it right. 如果他们弄错了,他们可以再次猜测,直到正确为止。 If they guess right, the program is supposed to congratulate them. 如果他们猜对了,该程序应该向他们表示祝贺。
This is what I have and it doesn't work. 这是我所拥有的,它不起作用。 I enter a number between 1 and 10 and there is no congratulations. 我输入的数字介于1到10之间,没有任何祝贺。 When I enter a negative number, nothing happens. 当我输入一个负数时,什么也没有发生。
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!"
Just move the congratulations message outside the loop. 只需将祝贺消息移到循环外即可。 You can then also only have one guess input in the loop. 然后,循环中也只能有一个猜测输入。 The following should work: 以下应该工作:
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!"
The problem is that in a if/elif chain, it evaluates them from top to bottom. 问题是在if / elif链中,它从上到下对其进行评估。 Move the last condition up. 向上移动最后一个条件。
if guess == number:
..
elif other conditions.
Also you need to change your while loop to allow it to enter in the first time. 另外,您需要更改while循环以允许它在第一次进入。 eg. 例如。
while True:
guess = int(raw_input("Guess a number: "))
if guess == number:
..
then break whenever you have a condition to end the game. 然后在您有条件结束游戏时休息。
The problem is that you exit the while loop if the condition of guessing correctly is true. 问题是,如果正确猜测的条件为true,则退出while循环。 The way I suggest to fix this is to move the congratulations to outside the while loop 我建议解决此问题的方法是将祝贺移到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.