当我在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
答案 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'