首页 > 解决方案 > 我将如何循环 python 函数的特定部分?

问题描述

所以我的问题是我将如何缩短此代码并仍然允许 3 次尝试?

def numberguess(answernumber):
  guess=input('guess a number between 1-10: ')
  if guess.isnumeric():
    if guess==answernumber:
      print('Correct')
    else:
      print('Incorrect')
      userguess=input('Two more attempts: ')
      if userguess.isalpha():
        if userguess==answerletter:
          print('Correct')
        else:
          print('Incorrect')
          userguess=input('one more attempt: ')
          if guess.isalpha():
            if userguess==answerletter:
              print('Correct')
            else:
              print('Incorrect, No more attempts remaining')
          else:
            print('Invalid')
      else:
        print('Invalid')
  else:
    print('invalid')

我有一组更短的代码,但我不知道如何去允许多次尝试而不会变成以前的代码混乱,我想知道是否有任何方法可以像你一样做一个循环在 python(turtle) 中使用“for i in range:”循环

def letterguess(answerletter,userguess):
  answerletter=answerletter.lower()
  userguess=userguess.lower()
  if userguess.isalpha()==False:
    print('Invalid')
    return False
  elif userguess==answerletter:
    print('Correct')
    return True
  elif userguess>answerletter:
    print('guess is too high')
    return False
  else:
    print('guess is too low')
    return False

如果您想查看差异,这是缩短的版本,但此版本只允许尝试一次

标签: python

解决方案


你在你的问题标题中使用了循环这个词,你是否尝试过谷歌搜索和阅读 Python 中可用的循环结构类型?在您的情况下,您知道您希望循环运行三次,因此您可以使用for循环。

所以基本结构将如下所示:

def number_guess(answer: int, num_attempts: int = 3) -> None:  # The : int and -> None are call type hints or type annotations. I highly highly recommend getting into the habit of using them in Python. It makes your code easier to read and later on, you can use tools like mypy to catch errors before running your code.
    for attempt in range(num_attempts): # Loop a defined number of times
        guess = input("Guess a number between 1 and 10:")
        if validate_guess(guess, answer):  # Wrap up your conditions in a function for readability
            print("Correct")
            break # Exit the loop early because the condition has been met
        else:
            print("Incorrect")
    else:  # This part is a weird python thing, it only runs if the loop completes without reaching a break statement. What does it mean if your loop completed without hitting break in this case? It means that the condition never evaluated to true, hence the correct guess wasn't found and the user ran out of tries.
        print("Sorry, you're out of tries")

现在您需要定义validate_guess

def validate_guess(guess: str, answer) -> bool:
    return guess.isnumeric() and int(guess) == answer

推荐阅读