我是python和编程的新手,我已经为Python中的Guess the Number游戏编写了一些代码。它允许用户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")
答案 0 :(得分:4)
我会重构您的代码以使用for
循环而不是while
循环。使用for
循环无需手动实现计数器变量:
import random
attempts = 5
secret_number = random.randint(1, 100)
for attempt in range(attempts):
guess = int(input('Take a guess: '))
if guess < secret_number:
print('Higher...')
elif guess > secret_number:
print('Lower...')
else:
print()
print('You guessed it! The number was ', secret_number)
print('You guessed it in', attempts, 'attempts')
break
if guess != secret_number:
print()
print('Sorry you reached the maximum number of tries')
print('The secret number was', secret_number)