你在正确的轨道上。以后,让自己通过程序思考每一行在做什么以及顺序是否合乎逻辑。
您的代码中只有一个实际错误:在 while 循环中调用 guess 时,您没有在代码中收集新的 x 值。其他元素是正确的,只是乱序而已。这是一个更合乎逻辑的顺序,解决了收集问题,
import random
rand_num = random.randint(1,6)
print("\nNUMBER GUESSING GAME")
lives = 5
def guess():
guess = int(input("Input guess: "))
return guess
print(rand_num) #to see the correct answer
x = guess()
if x == rand_num:
print("Good job! YOU WIN.\n")
else:
while x != rand_num:
# 1) Notify the user
print("Incorrect. Please try again")
# 2) Decrement remaining guesses
lives -= 1
# 3) Check if maximum number of guesses
# reached - end if yes
if lives == 0:
print("YOU LOSE.\n")
break
# 4) Get a new guess
x = guess()
# 5) Compare
if x == rand_num:
print("Good job! YOU WIN.\n")
您可能想通知您的玩家要猜的数字范围是多少。您还可以扩展此练习,编写多个难度级别,每个级别都有不同的范围(例如简单级别 1-6、中等级别 1-20 等),供玩家选择。
正如@Stef 在评论中提到的那样,将猜测数(生命)条件作为 while 循环条件的一部分在技术上更简洁且更常见,
import random
rand_num = random.randint(1,6)
print("\nNUMBER GUESSING GAME")
lives = 5
def guess():
guess = int(input("Input guess: "))
return guess
print(rand_num) #to see the correct answer
x = guess()
if x == rand_num:
print("Good job! YOU WIN.\n")
else:
while (x != rand_num) and (lives > 0):
# 1) Notify the user
print("Incorrect. Please try again")
# 2) Decrement remaining guesses
lives -= 1
# 3) Get a new guess
x = guess()
# 4) Compare, enf if correct
if x == rand_num:
print("Good job! YOU WIN.\n")
# If ending because no more guesses left
if lives == 0:
print("YOU LOSE.\n")
我对每个条件都使用括号,这里没有必要和样式问题。我喜欢这样分隔条件。
此外,如果所有猜测都用尽了,"YOU LOSE.\n" 部分现在会打印在末尾。
请注意:使用您现在的代码,您的玩家实际上可以猜测 6 次,在开始时猜测一次,在 while 循环中再猜测 5 次。