【问题标题】:"Name can be undefined" problem in pythonpython中的“名称可以未定义”问题
【发布时间】:2020-12-18 07:22:01
【问题描述】:

我正在尝试改进我的代码,所以这是关于一个“问题通知”,告诉我一个变量可以是未定义的。 这是我的代码:

print('\nWindow types')
print('1:1200 x 1300 mm')
print('2:800 x 1000 mm')
print('3:2100 x 1500 mm')
Window_Dimension = float(input('Select window type: '))
if Window_Dimension == 1:
    A = 1200
    B = 1300
elif Window_Dimension == 2:
    A = 800
    B = 1000
elif Window_Dimension == 3:
    A = 2100
    B = 1500
else:
    print('Invalid input!')

Lip_height = float(input('\nEnter lip eight (mm): '))
SWind_velocity = 80  # m/s Static wind velocity
print('Assuming a peak wind velocity of: 80 m/s')
Wind_pressure = (SWind_velocity ** 2) / 1600  # kN/m^2
print('Wind pressure (kN/m^2):', Wind_pressure)
a = A - (2 * Lip_height)
b = B - (2 * Lip_height)
Lip_area = (A * B) - (a * b)  # m^2
Lip_pressure = (Wind_pressure * (A * B) / 1000000) / (Lip_area / 1000000)  # kN/m^2
print('Uniform pressure on the lip (kN/m^2): ', round(Lip_pressure, 3))

它工作得很好,但我不断收到关于这两行的问题通知:

a = A - (2 * Lip_height)
b = B - (2 * Lip_height)

告诉我 A 和 B 可以是未定义的。我不知道是否有办法解决这个问题,或者即使我应该解决它,但我是 python 新手,我正在努力避免未来的“编码坏习惯”。谢谢

【问题讨论】:

  • @OcasoProtal 这个问题将在 codereview 的心跳中关闭,因为我们希望相关代码能够正常工作。损坏的代码是题外话。

标签: python input undefined


【解决方案1】:

不要简单地打印错误消息并在出现问题时继续。抛出异常。而不是

print('Invalid input!')

考虑

raise Exception('Invalid input!')

【讨论】:

  • 这很好用,我会阅读关于“raise Exception()”命令的文档,谢谢
【解决方案2】:

据我所知,它运行良好。我没有收到任何错误。也许您需要在一开始就定义变量。 就在开头,将其添加到:

a = 0
b = 0

这会在开始时设置变量,无需计算。稍后,它只会重写变量,而不是创建它。

让我知道这是否有效!

【讨论】:

  • 定义一个虚幻的变量值可能会在以后弄乱代码。我最初发布的内容没有提示错误,只是警告。
猜你喜欢
  • 2018-01-28
  • 1970-01-01
  • 2019-11-29
  • 1970-01-01
  • 2022-12-25
  • 1970-01-01
  • 1970-01-01
  • 2014-11-09
  • 2021-10-18
相关资源
最近更新 更多