【问题标题】:Variable defined in while loop cannot be defined无法定义 while 循环中定义的变量
【发布时间】:2015-05-01 11:59:46
【问题描述】:

我有一个这样的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 告诉我它无法定义。这些值正在计算中使用并打印阶段。

【问题讨论】:

  • 你想在循环时存储所有的“h”/相位值,还是只存储最后一个?
  • 您在 IDE 中看到的异常是什么?

标签: python loops variables while-loop


【解决方案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.'

【讨论】:

  • phase 应该是一个字符串''。
  • 除非定义了h,否则执行不会通过循环
  • Python 是弱类型的,因此阶段可以用任何类型的值初始化。
  • 我想你的意思是dynamically typed
  • 我的意思是在循环之前需要定义 h - 这是多余的
猜你喜欢
  • 1970-01-01
  • 2016-02-19
  • 2015-10-09
  • 2018-03-14
  • 1970-01-01
  • 2016-01-12
  • 1970-01-01
  • 2015-07-23
  • 2022-01-12
相关资源
最近更新 更多