【问题标题】:Why are my four "final" variable undefined? I thought I defined them before I used them为什么我的四个“最终”变量未定义?我以为我在使用它们之前就定义了它们
【发布时间】:2022-01-07 04:46:39
【问题描述】:

在你开始大笑之前,请了解我大约 2 周前开始使用 python,而这只是我正在做的实验。当我在上面的 if 语句中列出它们时,有人可以向我解释为什么我的“最终”变量是未定义的吗?在最后的 print 语句中,它突出显示了那些带有“final”的变量,并告诉我这些变量是未定义的,并且在我运行它时会引发错误。 (在return语句上面有一个叫做“diff”的函数)

        return x-y

    if sale_type.upper() == "RS":
        final1_quantity = diff(int(rs_quantity), int(sale_quantity))
    elif sale_type.upper() == "BS":
        final2_quantity = diff(int(bs_quantity), int(sale_quantity))
    elif sale_type.upper() == "BP":
        final3_quantity = diff(int(bp_quantity), int(sale_quantity))
    elif sale_type.upper() == "GP":
        final4_quantity = diff(int(gp_quantity), int(sale_quantity))
        
    quant = input("Would you like to see our stock? (Y/N)")
    if quant.upper() == "Y":
        print(f'''{final1_quantity} red shirts.
                {final2_quantity} blue shirts
                {final3_quantity} black pants
                {final4_quantity} grey pants''')```

【问题讨论】:

  • 它们在if 语句中。根据条件,它们可能未被分配。
  • 欢迎来到 Stackoverflow。提供最少的代码来重现问题。当前的编码块在重现问题方面没有用。
  • 很高兴知道。同样,我是一名高中生,这样做是为了好玩。还有 arsho,这是代码中唯一包含这些变量的区域

标签: python variables undefined


【解决方案1】:

当不能输入变量定义的'if'时,变量未定义。 您必须将它们全部定义为

final1_quantity = 0
final2_quantity = 0
final3_quantity = 0
final4_quantity = 0

在 'if' 条件之前。

【讨论】:

  • 谢谢拜拉姆,它成功了。
猜你喜欢
  • 1970-01-01
  • 2011-06-29
  • 1970-01-01
  • 2022-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-21
  • 1970-01-01
相关资源
最近更新 更多