为了账号安全,请及时绑定邮箱和手机立即绑定

我将如何循环 python 函数的特定部分?

我将如何循环 python 函数的特定部分?

至尊宝的传说 2023-11-09 21:36:51
所以我的问题是如何缩短这段代码并仍然允许 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如果您想查看差异,这是缩短版本,但此版本仅允许尝试一次
查看完整描述

3 回答

?
皈依舞

TA贡献1851条经验 获得超3个赞

您在问题标题中使用了“循环”一词,您是否尝试过谷歌搜索并阅读有关 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


查看完整回答
反对 回复 2023-11-09
?
千万里不及你

TA贡献1784条经验 获得超9个赞

紧凑版本可能是:


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 梯子中。相反,请使用逻辑来确定在何处以及如何更有效地使用这些条件。结果将是更高效、更简洁的代码。


查看完整回答
反对 回复 2023-11-09
?
扬帆大鱼

TA贡献1799条经验 获得超9个赞

好吧,呃,出于某种原因,我有一个奇怪的想法,仅仅因为它们用于 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'))

查看完整回答
反对 回复 2023-11-09
  • 3 回答
  • 0 关注
  • 73 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信