【问题标题】:Why is using a variable in elif giving an error if it is declared in if?如果在 if 中声明,为什么在 elif 中使用变量会出错?
【发布时间】:2021-12-31 02:29:29
【问题描述】:

opt = int(input('enter'))
if opt ==1:
    m = int(input('enter'))
    print(m)
if opt == 2:
    print(m)

错误是这样的

文件“”,第 6 行,在 NameError: 名称“m”未定义

【问题讨论】:

  • 如果opt 是2,你希望打印什么?
  • m 如果opt==2 则永远不会被定义
  • 1.你没有elif。 2.当程序进入opt == 2时,表示opt2,也就是说opt不能是1。这意味着程序没有看到第一个if 语句的内部。所以m 没有定义。
  • 我不能使用在 if 语句中声明的变量在另一个 elif 或 else 中使用它吗?
  • 在这种情况下你不能这样做,因为如果 opt 为 2,定义 m 的那一行将不会被执行

标签: python if-statement variables


【解决方案1】:

如果 opt 等于 2,则 Python 运行代码“print(m)”,但仅当 opt 等于 1 时才定义 m。

opt = int(input('enter'))
m = int(input('enter'))
if opt ==1:
    print(m)
elif opt == 2:
    print(m)

【讨论】:

  • 没问题!实际上,您根本不需要使用 if-else 语句,因为您在两者中都打印相同的内容;)
猜你喜欢
  • 2016-05-30
  • 2011-07-06
  • 2018-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-09
  • 2020-04-14
相关资源
最近更新 更多