'if语句'中的变量集不能在Python之外打印

时间:2016-11-07 15:58:22

标签: python if-statement

当我在if语句中分配变量时,它不会在底部打印出来:

#!/usr/bin/env python

import datetime
date = datetime.datetime.today().weekday()

#0 monday, 1 tuesday, 2 wednesday, 3 thursday, 4 friday, 5 saturday, 6 su$

if (date == 1 or date == 2): #tuesday wednesday
        location = 'Baltimore'
if (date == 3): #thursday
        location = 'DC'
if (date == 4):
        location = 'Johns Hopkins Cath/Baltimore'

我得到的错误是:

Traceback (most recent call last):
  File "./ifwhile.py", line 13, in <module>
    print location
NameError: name 'location' is not defined

2 个答案:

答案 0 :(得分:1)

需要考虑的事项:

#!/usr/bin/env python

import datetime
date = datetime.datetime.today().weekday()

#0 monday, 1 tuesday, 2 wednesday, 3 thursday, 4 friday, 5 saturday, 6 su$
whereToGo = {
    0: None
    1: 'Baltimore',
    2: 'Baltimore',
    3: 'DC',
    4: 'Johns Hopkins Cath/Balitmore',
    5: None,
    6: None
}

location = whereToGo[date]

希望这有帮助。

答案 1 :(得分:1)

None if条件为True,因此location的值未初始化。因为今天星期一(2016年11月7日),将date的值设置为0。在您的代码中,您没有0的条件。

您的代码应该是:

if (date == 1 or date == 2): #tuesday wednesday
        location = 'Baltimore'
elif (date == 3): #thursday
# ^ I am using elif, because there will only one condition which will be
# True at a time, no need of separate if blocks
        location = 'DC'
elif (date == 4):
        location = 'Johns Hopkins Cath/Baltimore'
else:  # For rest of the weekdays
        location = 'New location'