簡體   English   中英

我將如何循環 python 函數的特定部分?

[英]How would i go about looping specific parts of a python function?

所以我的問題是如何縮短這段代碼並仍然允許 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 中可用的循環結構類型? 在您的情況下,您知道您希望循環運行 3 次,因此您可以使用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

緊湊版本可能是:

def numberguess(answerletter):
    for attempt in range(3):
        user_guess = input('Enter Guess:')
        if user_guess.isnumeric() and int(user_guess)==answerletter:
            print('Correct')
            return True
        else:
            print(f'incorrect, {2-attempt} attempts left')
    print('failed')
    return False

你需要做的工作:

  1. 循環。 當某些操作需要重復所需次數時使用它們
  2. 結合條件。 您不只是在長長的 if-else 階梯中列出它們。 相反,使用邏輯來確定可以更有效地使用這些條件的位置和方式。 結果將是一個更高效、更干凈的代碼。

好吧,嗯,出於某種原因,我有一個奇怪的想法,僅僅因為它們用於 python(turtle) 就意味着我不能對普通 python 使用 while 循環,這是使用臨時的 while 循環修改后的代碼,它不會改變很多原始代碼

def letterguess(answerletter):
  answerletter=answerletter.lower()
  i=0
  while i<3:
    userguess=input('guess a letter A-Z: ')
    userguess=userguess.lower()
    if userguess.isalpha()==False:
      print('Invalid')
      return False
    elif userguess==answerletter:
      print('Correct')
      i=4
      print('You guessed correctly')
    elif userguess>answerletter:
      print('guess is too high')
      i+=1
    else:
      print('guess is too low')
      i+=1
  else:
    print('you failed to guess')
print(letterguess('L'))

感謝那些回答我愚蠢問題的人,他們只是想說明我大約一個半月前開始學習 Python,所以坦率地說,我對你提供的一些代碼感到困惑,但無論如何感謝他們幫助我

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM