为什么会出现错误“ NameError:未定义名称'kh'”

时间:2019-05-23 21:37:44

标签: python string if-statement sys

我正在使用sys接收输入数据,有2个字符串// Using Lombok to auto-generate getters/setters @Data @NoArgsConstructor @JsonInclude("JsonInclude.Include.NON_NULL") public class Result { @JsonProperty("name") private String name; // This will handle if assigned_to returned as a JSON object // If assigned_to was empty, it would return as an empty string // and cause this to bomb out until the Data type was String again @JsonProperty("assigned_to") private LinkValueObject assignedTo; } b,它们将进入if语句,并为l和其他分配一个值变量,但我不断收到有关kh

的错误

输入看起来像这样:

kh

if语句如下:

# Data Input

# Latitude
lat = float(sys.argv[1])
# Longitude
lon = float(sys.argv[2])
# Frequency Band
b = str(sys.argv[3])
# Link Type
l = str(sys.argv[4])
# Elevation
hs = float(sys.argv[5])/1000

我期望if b == 'C' and l == 'UL': f = 6 kh = 0.0007056 ah = 1.5900 kv = 0.0004878 av = 1.5728 tao = 45 elif b == 'C' and l == 'DL': f = 4 kh = 0.0001071 ah = 1.6009 kv = 0.0002461 av = 1.2476 tao = 45 k = (kh + kv + (kh - kv) * pow(cos(radians(lat)), 2) * cos(radians(2 * tao))) / 2 print('k = ', k) a = (kh * ah + kv * av + (kh * ah - kv * av) * pow(cos(radians(lat)), 2) * cos (radians(2 * tao))) / (2 * k) print('a = ', a) k的值是浮点型的,但是出现以下错误:

a

为什么会发生这种情况,我该如何解决?

1 个答案:

答案 0 :(得分:2)

这可能是由于您的ifelif语句未涵盖的情况。如果bl与这两种情况都不匹配,则永远不会定义变量或给变量赋值。

您应在else块之后添加默认elif大小写,并添加所需的任何默认值:

else:
    f = 0
    kh = 0
    ah = 0
    kv = 0
    av = 0
    tao = 0

但是,如果您遇到此问题,则意味着您可能会收到意外的输入。您还可以添加一些打印语句来确定bl的值,并编写相应的大小写。