我有一个任务,可以简单地以日历格式打印日期。除了用户在输入中输入一些字母(字符串)时,所有操作都已完成,控制台给出了一条错误声明,表明我已经在if
语句中包含了代码。
这是我在控制台中遇到的错误:
Please enter the number/name of the month (in any case/form)
you want the program to display calendar of: jan
Traceback (most recent call last):
File "<ipython-input-16-8ac5bd6555cd>", line 1, in <module>
runfile('D:/Studies & Learnings/Programming/Python/Calendar.py', wdir='D:/Studies & Learnings/Programming/Python')
File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 685, in runfile
execfile(filename, namespace)
File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 71, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "D:/Studies & Learnings/Programming/Python/Calendar.py", line 3, in <module>
month = input("\nPlease enter the number/name of the month (in any case/form)\nyou want the program to display calendar of:\t")
File "C:\Python27\lib\site-packages\IPython\kernel\zmq\ipkernel.py", line 364, in <lambda>
input = lambda prompt='': eval(raw_input(prompt))
File "<string>", line 1, in <module>
NameError: name 'jan' is not defined
我刚刚开始学习python。这是我在python中的第一个代码。因此,如果我做错了明显的事情,请告诉我,而不是将我的问题评为“负值”
谢谢大家...
month = input("\nPlease enter the number/name of the month (in any case/form)\nyou want the program to display calendar of:\t")
month = str(month)
if(month == "1" or month == "jan" or month == "Jan" or month == "january" or month == "January"):
monthNumber = 1
monthName = "January"
elif(month == "2" or month == "feb" or month == "Feb" or month == "february" or month == "Februrary"):
monthNumber = 2
monthName = "February"
答案 0 :(得分:2)
您不必使用month = string(month),因为输入仅是字符串形式。删除该行,代码应该可以工作
答案 1 :(得分:0)
在Python 2中,input()
函数由于当时必须合理的原因tries to evaluate what's typed as a Python expression。因此,当您在jan
提示符下键入input()
时,它将尝试查找变量jan
。在这种情况下(或几乎所有其他*),这不是您想要的;您应该改用raw_input()
。
请注意,在2020年之后将成为唯一受支持的版本的Python 3中,Python 2的input()
函数被删除,而raw_input()
函数被重命名为input()
*看来,当您想要一个数字时,input()
是有意义的;当用户在2
提示符下键入input()
时,将得到int
,而不是str
。但是,任何时候运行eval
都会遇到巨大的安全性问题,因此input()
仍然应该使用int(raw_input())
。