我是 python 和一般编程的新手,我已经为 Python 中的猜数游戏编写了一些代码。它允许用户 6 次尝试猜测一个随机数。它有效,但是我不确定这是否是编写它的最佳方式或最有效的方式,如果我能得到一些建设性的反馈,我将不胜感激。
代码:
#Guess my Number - Exercise 3
#Limited to 5 guesses
import random
attempts = 1
secret_number = random.randint(1,100)
isCorrect = False
guess = int(input("Take a guess: "))
while secret_number != guess and attempts < 6:
if guess < secret_number:
print("Higher...")
elif guess > secret_number:
print("Lower...")
guess = int(input("Take a guess: "))
attempts += 1
if attempts == 6:
print("\nSorry you reached the maximum number of tries")
print("The secret number was ",secret_number)
else:
print("\nYou guessed it! The number was " ,secret_number)
print("You guessed it in ", attempts,"attempts")
input("\n\n Press the enter key to exit")