Python 3.x PythonNoob-寻找反意大利面建议并避免冗余代码

Python 3.x PythonNoob-寻找反意大利面建议并避免冗余代码,python-3.x,function,validation,methods,Python 3.x,Function,Validation,Methods,第一个帖子在这里。我想把这件事告诉你们,因为我正在寻找一些有见地的反馈和我的方法回到这个世界。我的主要经验是在前端工作中使用Javascript,直到昨天下午我才写过一封python的信,所以请原谅我的混乱 我正试图了解您可能会看到的一些关于缩写或清理此代码的即时建议。也许是一些耀眼的“请不要再这样做”的项目,或者任何你可能有的洞察力 这是一个游戏机号码猜测游戏,目前为1-10。它确实在运行,但有一些bug。有一个主要的问题一直让我感到困惑(我相信这很简单),那就是如果你在最后一次尝试中猜到了正

第一个帖子在这里。我想把这件事告诉你们,因为我正在寻找一些有见地的反馈和我的方法回到这个世界。我的主要经验是在前端工作中使用Javascript,直到昨天下午我才写过一封python的信,所以请原谅我的混乱

我正试图了解您可能会看到的一些关于缩写或清理此代码的即时建议。也许是一些耀眼的“请不要再这样做”的项目,或者任何你可能有的洞察力

这是一个游戏机号码猜测游戏,目前为1-10。它确实在运行,但有一些bug。有一个主要的问题一直让我感到困惑(我相信这很简单),那就是如果你在最后一次尝试中猜到了正确的答案(在本例中是第三次),它不会运行“恭喜”代码。它运行“youfailed”部分

只是想寻求一些建议或任何形式的输入,以帮助评估我用这种语言解决问题的思路和方法。另外,如果网络上有更好的地方可以放置这种无趣的东西,请告诉我。谢谢

from random import randint


def guessing_game():
    # Set the count and limits for the loop and game length.
    guess_count = 0
    guess_limit = 2
    # Ask the user to take a guess.
    guess = int(input("I'm thinking of a number between 1 and 10... "))
    # Randomize the answer. Change the range according to preference.
    the_answer = randint(1, 10)
    # Start the loop
    while guess_count < guess_limit:

        if guess == the_answer:  # The user wins and is prompted to play again. Init function would probably be useful.
            print(f"Congrats, you won! The answer is {the_answer}!")
            restart = input("Play again? ")
            if restart.upper() == "Y":
                guessing_game()
            else:  # The user declines to play and we break out of the loop.
                print("Okay, thanks for playing! ")
                break
            break
        elif guess != the_answer:  # The user guessed the wrong answer. Ask again and add to the count.
            print("Oops, try again.")
            guess = int(input("I'm thinking of a number between 1 and 10... "))
            guess_count += 1

        if guess_count == guess_limit:  # Shucks, the user failed. Inform them of their failure and offer redemption.
            print('Sorry, you failed.')
            restart = input("Play again? ")
            if restart.upper() == "Y":
                guess_count = 0
                guessing_game()
            else:  # The user opted out of continuing this exciting adventure.
                print("Okay, thanks for playing! ")
                break


guessing_game()

部门从来没有机会运行。我通过改变现状解决了这个问题

while guess_count < guess_limit:

猜测计数


而guess_count以下代码就是问题所在:

elif guess != the_answer:  # The user guessed the wrong answer. Ask again and add to the count.
    print("Oops, try again.")
    guess = int(input("I'm thinking of a number between 1 and 10... "))
    guess_count += 1
当用户最终得到正确答案时,将执行下一位代码:

if guess_count == guess_limit:  # Shucks, the user failed. Inform them of their failure and offer redemption.
    print('Sorry, you failed.')
    restart = input("Play again? ")
    if restart.upper() == "Y":
        guess_count = 0
        guessing_game()
    else:  # The user opted out of continuing this exciting adventure.
        print("Okay, thanks for playing! ")
        break
现在,如果用户在第三次猜测中,
guess\u count==guess\u limit
将为
true
,代码将执行时说“对不起,您失败了”

为了解决此问题,我执行了以下操作: 移动

到循环的第一行。i、 e:

while guess_count < guess_limit:
    guess = int(input("I'm thinking of a number between 1 and 10... "))

然后,改变:

elif guess != the_answer:
elif guess != the_answer and guess_count != guess_limit:  # CHANGE The user guessed the wrong answer.
    print("Oops, try again.")
    guess = int(input("I'm thinking of a number between 1 and 10... "))
    guess_count += 1
guess_limit = 2

然后,改变:

elif guess != the_answer:
elif guess != the_answer and guess_count != guess_limit:  # CHANGE The user guessed the wrong answer.
    print("Oops, try again.")
    guess = int(input("I'm thinking of a number between 1 and 10... "))
    guess_count += 1
guess_limit = 2

最后,改变:

if guess_count == guess_limit:


手动
while
循环在Python中几乎总是错误的答案。在运行到指定次数的
范围内执行
for
循环要简单得多。此外,Python
for
循环可以接受一个
else
块,该块在循环运行到完成时执行,但如果
中断了
(或
返回
,或出现异常气泡),则不会执行,这使得它们非常适合于“大海捞针”的场景,即没有找到针的情况(
while
循环也可以有
else
块,但是
for
循环是这里更好的选择)。它还允许您移动公共代码(无论他们猜对与否都执行的代码,在本例中,是“新游戏”检查)在
for
else
的外部,因此您可以将循环中的一组数据和
break
输出到公共代码,或者循环运行到完成,并且
else
块在公共代码之前输出不同的消息

因此,您可以通过使用
for
/
else
来大大简化:

from random import randint

def guessing_game():
    # Set the count and limits for the loop and game length.
    guess_limit = 2  # Allows up to two guesses
    # Randomize the answer. Change the range according to preference.
    the_answer = randint(1, 10)
    for guess_count in range(guess_limit):
        guess = int(input("I'm thinking of a number between 1 and 10... "))
        if guess == the_answer:
            print(f"Congrats, you won! The answer is {the_answer}!")
            break  # Go to common code for retry
        elif guess_count != guess_limit:  # Don't need to retest guess != the_answer; this is an else that never executes unless they weren't equal 
            print("Oops, try again.")
            # Don't need to prompt for input again, we'll prompt at top of loop
    else:
        # Only prints if loop ran to completion without breaking
        print('Sorry, you failed.')

    # Common code run for both success and failure:
    restart = input("Play again? ")
    if restart.upper() == "Y":
        guessing_game()
    else:
        print("Okay, thanks for playing! ")

if __name__ == '__main__':  # Get in the habit of using the import guard now; it's not necessary yet, but when it is, you want to be in the habit
    guessing_game()
请注意,这里的无限递归可能存在问题。如果用户玩了近千次,您将达到Python递归限制。如果这是一个问题,我将进行重构,将“一个游戏”与“所有游戏”分开,并将“所有游戏”实现为一个循环,因此您不需要递归来玩另一个游戏:

from random import randint

def play_one_game():
    # Set the count and limits for the loop and game length.
    guess_limit = 2  # Allows up to two guesses
    # Randomize the answer. Change the range according to preference.
    the_answer = randint(1, 10)
    for guess_count in range(guess_limit):
        guess = int(input("I'm thinking of a number between 1 and 10... "))
        if guess == the_answer:
            print(f"Congrats, you won! The answer is {the_answer}!")
            break  # Go to common code for retry
        elif guess_count != guess_limit:  # Don't need to retest guess != the_answer; this is an else that never executes unless they weren't equal 
            print("Oops, try again.")
            # Don't need to prompt for input again, we'll prompt at top of loop
    else:
        # Only prints if loop ran to completion without breaking
        print('Sorry, you failed.')

def guessing_game():
    keep_playing = True
    while keep_playing:
        play_one_game()
        # Common code run for both success and failure:
        keep_playing = input("Play again? ").upper() == "Y"
    print("Okay, thanks for playing! ")

if __name__ == '__main__':  # Get in the habit of using the import guard now; it's not necessary yet, but when it is, you want to be in the habit
    guessing_game()
这种方法还有助于最小化复杂性;
猜谜游戏
用于做两件几乎不相关的事情:

  • 只玩一个游戏实例
  • 决定是否玩另一个游戏
  • 将它们分开会使这两种行为分开,因此在隔离状态下更容易理解任何一种特性

    最后一个建议:没有很好的方法来处理“不要在最后一个循环中给出Oops消息”的情况,我可以马上想到,但是有“不可怕”的方法消除对大多数循环都会失败的测试需求的方法。最简单的方法是将额外消息作为输入的一部分回显,使用最初为空的额外消息,然后无条件地设置为“oops”消息,以便用于所有后续循环。为此,您只需替换:

    for guess_count in range(guess_limit):
        guess = int(input("I'm thinking of a number between 1 and 10... "))
    
    与:

    允许您完全删除:

        elif guess_count != guess_limit:
            print("Oops, try again.")
    

    将每循环条件分支替换为无条件执行路径(这也使代码更易于测试,因为未使用或很少使用的路径更少)。

    我用我所做的更改更新了原始问题。@an0n1m1m1tyso抱歉!忘记提及
    guess\u limit=3
    并删除
    guess=int(输入(“我想的是一个介于1和10之间的数字……”)
    elif guess!=答案和猜测数!=猜测限制:
    我再次更新了我的帖子以反映这些变化。我们很接近了,只有这一个错误仍然存在。@An0n1mity我接受了你的答案,因为答案很清楚,对我帮助很大。我的代码中有一个错误,但你帮我解决了我发布的主要问题,这很好。谢谢非常感谢!非常感谢您对更干净的方法提出的全面建议。非常感谢!我会再讨论几次,并真正消化它,然后尝试自己复制它(至少类似地)以强化概念。我会确保在我的声誉提高后进行投票:)
    elif guess_count == guess_limit:
    
    from random import randint
    
    def guessing_game():
        # Set the count and limits for the loop and game length.
        guess_limit = 2  # Allows up to two guesses
        # Randomize the answer. Change the range according to preference.
        the_answer = randint(1, 10)
        for guess_count in range(guess_limit):
            guess = int(input("I'm thinking of a number between 1 and 10... "))
            if guess == the_answer:
                print(f"Congrats, you won! The answer is {the_answer}!")
                break  # Go to common code for retry
            elif guess_count != guess_limit:  # Don't need to retest guess != the_answer; this is an else that never executes unless they weren't equal 
                print("Oops, try again.")
                # Don't need to prompt for input again, we'll prompt at top of loop
        else:
            # Only prints if loop ran to completion without breaking
            print('Sorry, you failed.')
    
        # Common code run for both success and failure:
        restart = input("Play again? ")
        if restart.upper() == "Y":
            guessing_game()
        else:
            print("Okay, thanks for playing! ")
    
    if __name__ == '__main__':  # Get in the habit of using the import guard now; it's not necessary yet, but when it is, you want to be in the habit
        guessing_game()
    
    from random import randint
    
    def play_one_game():
        # Set the count and limits for the loop and game length.
        guess_limit = 2  # Allows up to two guesses
        # Randomize the answer. Change the range according to preference.
        the_answer = randint(1, 10)
        for guess_count in range(guess_limit):
            guess = int(input("I'm thinking of a number between 1 and 10... "))
            if guess == the_answer:
                print(f"Congrats, you won! The answer is {the_answer}!")
                break  # Go to common code for retry
            elif guess_count != guess_limit:  # Don't need to retest guess != the_answer; this is an else that never executes unless they weren't equal 
                print("Oops, try again.")
                # Don't need to prompt for input again, we'll prompt at top of loop
        else:
            # Only prints if loop ran to completion without breaking
            print('Sorry, you failed.')
    
    def guessing_game():
        keep_playing = True
        while keep_playing:
            play_one_game()
            # Common code run for both success and failure:
            keep_playing = input("Play again? ").upper() == "Y"
        print("Okay, thanks for playing! ")
    
    if __name__ == '__main__':  # Get in the habit of using the import guard now; it's not necessary yet, but when it is, you want to be in the habit
        guessing_game()
    
    for guess_count in range(guess_limit):
        guess = int(input("I'm thinking of a number between 1 and 10... "))
    
    extra = ''  # No oops message the first time
    for _ in range(guess_limit):  # Don't even name guess_count, we never use it; by convention, _ means unused variable
        guess = int(input(extra + "I'm thinking of a number between 1 and 10... "))
        extra = "Oops, try again.\n"  # From now on, oops incorporated into prompt
    
        elif guess_count != guess_limit:
            print("Oops, try again.")