无法定义while循环中定义的变量

时间:2015-02-28 22:24:20

标签: python loops variables while-loop

我有一个像这样的while循环:

while True:
    try:
        h = int(raw_input("Please Enter your altitude in metres > "))
        if h > 0 and h < 11000:
            phase = 'Troposphere'
            break
    except ValueError:
            print 'Your entered value contained letters or punctuation. Please enter a numerical value.'

以后我想使用hphase的值,但是我的IDE告诉我它无法定义。这些值正在计算中使用,并打印出相位。

1 个答案:

答案 0 :(得分:1)

在while块之外定义变量,以便可以在这样的块之外使用它们:

h = 0
phase = 0
while True:
    try:
        h = int(raw_input("Please Enter your altitude in metres > "))
        if h > 0 and h < 11000:
            phase = 'Troposphere'
            break
    except ValueError:
            print 'Your entered value contained letters or punctuation. Please enter a numerical value.'