-1

我是 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")           
4

1 回答 1

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)
于 2012-10-19T05:09:48.953 回答