【问题标题】:How do I reduce a score from inside a function如何从函数内部减少分数
【发布时间】:2020-10-31 14:16:33
【问题描述】:

试图让我的第一个程序运行。我试图根据用户输入减去分数。但我的分数不会改变现在的样子。你能帮我理解怎么回事吗?

您可以在下面看到我正在尝试运行的代码:

    score = 75
    def round_1(score):
        shots_1 = input("What did you score: ")
        if shots_1 == 1:
            return score - 1
        elif shots_1 == 2:
            return score - 2
        elif shots_1 == 3:
            return score - 3
        else:
            return score

【问题讨论】:

  • int(input("What did you score: "))。默认input()返回一个字符串,你需要将它转换为一个int。
  • input() 返回一个字符串值,但您正在检查整数值。您的if 语句都不为真,因此始终执行else
  • 您必须对return 语句的返回值实际做一些事情 才有意义。向我们展示您调用此函数的代码。
  • 用 int() 包装 input() 或使用 if shots_1 == '1' 等等
  • @RobinBorg 不要忘记接受答案。

标签: python reduce


【解决方案1】:

您的问题与数据类型有关。您必须将shots_1 转换为int。或将其输入为 shot_1 == '1':

【讨论】:

  • 该函数的目的是返回分数减去一个数字,因此使用'1' 是不够的。它必须转换为整数。
  • 在这个函数中,除了条件 if 语句之外,他没有使用 shot_1 来处理任何事情。如果是得分,我会同意 - shot_1
  • 啊,原来如此。我的错。
【解决方案2】:

命令行input 始终采用string 格式。您必须根据用户的输入转换为所需的格式。

def round_1(score):
    shots_1 = int(input("What did you score: "))
    print(shots_1)
    if shots_1 == 1:
        return score - 1
    elif shots_1 == 2:
        return score - 2
    elif shots_1 == 3:
        return score - 3
    else:
        return score
        

print(round_1(75))

您可以在此处阅读有关类型转换的更多信息。 https://www.geeksforgeeks.org/taking-input-from-console-in-python/

【讨论】:

    【解决方案3】:

    input返回一个字符串,所以所有这些ifs 都将为假:

        if shots_1 == 1:
            return score - 1
        elif shots_1 == 2:
            return score - 2
        elif shots_1 == 3:
            return score - 3
    

    你可以这样做:

        if shots_1 == '1':
            return score - 1
        elif shots_1 == '2':
            return score - 2
        elif shots_1 == '3':
            return score - 3
    

    【讨论】:

      【解决方案4】:

      当您要求输入时,它会自动将输入作为字符串,因此您也应该将选项转换为字符串,因为您的代码位于 def 函数中,您需要先运行它:

      score = 75
      def round_1(score):
          shots_1 = input("What did you score: ")
          if shots_1 == '1':
              print(score-1)
          elif shots_1 == '2':
              print(score-2)
          elif shots_1 =='3':
              print(score-3)
          else:
              print(score)
      round_1(75)
      
      
      

      【讨论】:

        猜你喜欢
        • 2022-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-04
        • 2011-06-06
        • 1970-01-01
        相关资源
        最近更新 更多