我有一段时间没有编程,所以我想我会继续使用我的codecademy教程来恢复体形。我现在真的很困惑,因为我得到了所有这些语法错误,我很确定我不应该这样做。
这是我的代码:
from random import randint
# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)
guesses_left = 3
# Start your game!
while guesses_left > 0:
guess = int(raw_input("Your guess: ")
if guess == random_number:
print "You win!"
break
guesses_left = guesses_left - 1
else:
print "You lose."
由于第10行的冒号,我收到语法错误。
我不明白为什么,它是一个if语句,在if语句之后你总是有一个冒号不是吗?
对于像这样的简单事情,我今天得到了一堆语法错误,我不明白为什么。
答案 0 :(得分:2)
这是您的代码的直接复制/粘贴吗?你的int()是未公开的
guess = int(raw_input("Your guess: ") <--- missing parenthesis
此外,guesses_left
的减少位置错误。它应该放在else
块之后,因为它应该在每个循环中递减,而不管if/else
此外,else
区块上的缩进与您的if
不对齐。 python中的缩进是关键。
答案 1 :(得分:0)
您的代码略有变化:
from random import randint
# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)
guesses_left = 3
# Start your game!
while guesses_left > 0:
guesses_left = guesses_left - 1
guess = int(raw_input("Your guess: "))
if guess == random_number:
print "You win!"
break
else:
print "You lose."
答案 2 :(得分:0)
此代码可以帮助您完成任务。我得到的主要错误是它有效,但仍然说游戏结束后出现了错误。这是由于我的其他原因:打印'你输了'。成为时间运作的一部分。取而代之的是与while相同的缩进上的else:,这就是他们想要看到的内容
from random import randint
# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)
guesses_left = 3
while guesses_left > 0:
guess = int(raw_input("Your guess: "))
guesses_left -= 1
if guess == random_number:
print "You win!"
break
else:
print "You lose."
答案 3 :(得分:0)
我是这样做的,我为了好玩而添加了一些额外的功能:
from random import randint
# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)
print random_number # For debugging
guesses_left = 3 # Amount of guesses left
print "Guess my number! You've got 3 tries left!"
tries = [] # Array for user input
while guesses_left > 0:
guess = int(raw_input("Your guess: ")) # Asks user to enter a number
if guess in tries: # Checks if user entered the same number before
print "You've already guessed this number: ", guess
print "You've got " , int(guesses_left) , " guess(es) left!"
elif guess > 10 or guess < 1: # Checks if user input is between 1 and 10
print "Wrong input! Guess a number between 1 and 10!"
print "You've got " , int(guesses_left) , " guess(es) left!"
elif guess == random_number: # If user input is the same as the random number you win!
print "You win!"
break
else:
guesses_left -= 1 # Decreases the amount of guesses left
print "You've got " , int(guesses_left) , " guess(es) left!"
tries.append(guess) # Saves user input to "tries"
else:
print "You lose!"