【问题标题】:python warnings saying "Name "X" can be undefined"python警告说“名称“X”可以未定义”
【发布时间】:2020-04-24 09:54:02
【问题描述】:

我对编程很陌生,我制作了一个运行良好的应用程序,但我收到警告说“名称“X”可能未定义”。这是什么意思,我怎样才能摆脱警告?我将 Python 3.8 与 Intelij IDE 2020.1 一起使用。

这是我的问题的屏幕截图:

这是我的代码的最小回购:

print("1. school a \n2. school b")
while True:
    try:
        school_number = int(input("\nEnter the number of what school you are at: "))
        break
    except ValueError:
        print("That was an invalid number.  Please try again...\n")

current_day = input("Please enter what day it is (mon/tue etc): ".lower())

if school_number == 1:
    school_name = "school A"
    cost = (7.50 * 2)
    leave_time_multiplier = 1.15
    if current_day == "mon":
        start_time = 09.30
        finish_time = 14.30
    else:
        pass

if school_number == 2:
    school_name = "school B"
    cost = (9.50 * 2)
    leave_time_multiplier = 1.25
    if current_day == "mon":
        start_time = 17.00
        finish_time = 20.30
    else:
        pass

# renames the days
if current_day == "mon":
    day = "Monday"
else:
    day = "Other"

leave_time = start_time - leave_time_multiplier - 1

print("\nOn {} at {}: It will cost {:.2f} return. You start at {:.2f} and finish at {:.2f} You should leave at"
      "{:.2f}".format(day, school_name, cost, start_time, finish_time, leave_time))

【问题讨论】:

    标签: python python-3.x variables undefined


    【解决方案1】:

    finish_time 将在以下情况下未定义:school_number 不等于 1 或 2,current_day 不等于“mon”等。在这种情况下,您的脚本将引发异常。所以你必须在上面的某处定义finish_timeif school_number == 1:

    【讨论】:

    • 非常感谢! cost, leave_time_multiplier, start_time, finish_time, school_name, day = 0, 0, 0, 0, 0, 0 上面的 if 语句对此进行了排序
    【解决方案2】:

    您必须添加第三个条件,其中值不等于 1 和 2 个数字。因为如果用户输入了 1 或 2 以外的其他数字,则不会创建您打印的所有变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-30
      相关资源
      最近更新 更多