【问题标题】:Correct way of coding a 'Guess the Number' game in Python [closed]在 Python 中编写“猜数字”游戏的正确方法 [关闭]
【发布时间】:2012-10-19 04:59:27
【问题描述】:

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

【问题讨论】:

  • 对我来说看起来不错。您可以通过将elif ... 替换为else 来简化while 循环中的if 条件。
  • 如果此代码有效并且您正在寻找改进,这属于codereview.stackexchange.com(我已将其标记为建议迁移)
  • 您的代码中有一个小错误:如果有人在第六次尝试时猜对了,您会打印出错误消息。使用if attempts == 6 and secret_number != guess:。或者,检查if secret_number == guess:

标签: python python-3.x


【解决方案1】:

我会重构您的代码以使用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)

【讨论】:

    猜你喜欢
    • 2022-12-09
    • 2016-06-21
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多