我是编程新手,所以请原谅下面的困惑......我正在尝试编写一个猜数字游戏。计算机应该随机生成 1 到 10 之间的数字(含 1 和 10)。用户只能尝试 3 次来正确猜测数字。如果用户猜测正确或尝试次数耗尽,我应该让程序询问用户是否想再次玩游戏,并且游戏应该重新启动。以下是我的想法。我认为我让这件事变得比需要的更加复杂......我做错了什么,因为它不起作用?
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: "))
attempts = 0
while guess != number and attempts < 4:
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: "))
attempts = attempts + 1
if attempts > 4:
print "You've guessed incorrectly and are out of tries..."
playAgain = raw_input("Would you like to play again? ")
if playAgain = "Yes" or playAgain == "y":
import random
number = random.randint(1,10)
attempts = 0
guess = int(raw_input("Guess a number: "))
while guess != number and attempts < 4:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
else:
print "That is not an interger between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
attempts = attempts + 1
while guess == number:
print "Congratulations, you guessed correctly!"
playAgain = raw_input("Would you like to play again? ")
if playAgain = "Yes" or playAgain == "y":
import random
number = random.randint(1,10)
attempts = 0
guess = int(raw_input("Guess a number: "))
while guess != number and attempts < 4:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
else:
print "That is not an interger between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
attempts = attempts + 1
if attempts > 3:
print "You've guessed incorrectly and are out of tries..."
playAgain = raw_input("Would you like to play again? ")
if playAgain == "yes" or playAgain == "Yes":
import random
number = random.randint(1,10)
attempts = 0
guess = int(raw_input("Guess a number: "))
while guess != number and attempts < 4:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
else:
print "That is not an interger between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
attempts = attempts + 1
if attempts > 3:
print "You've guessed incorrectly and are out of tries..."
playAgain = raw_input("Would you like to play again? ")
if playAgain == "yes" or playAgain == "Yes":
import random
number = random.randint(1,10)
对于初学者来说,这是一个不太高级的解决方案:
import random
attempts = 0
number = random.randint(1,10)
while attempts < 4:
attempts += 1
print number #print number to help with testing
guess = int(raw_input("Guess a number from 1 to 10: "))
if guess == number:
print "you guessed the number!",
again = raw_input("do you want to play again? y or n ")
if again == "y":
number = random.randint(1,10)
attempts = 0 # gives 4 attempts to a new game
else:
print "good bye"
break
elif attempts == 4:
print "The game is over!"
我是一名优秀的程序员,十分优秀!