繁体   English   中英

无法从python中的“ if”获得所需结果

[英]Unable to get desired result from “ if ” in python

我的任务是简单地以日历格式打印日期。 除了当用户在输入中输入一些字母(字符串)时,一切都完成了,控制台给出了一条错误声明,表明我已经在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"

您不必使用month = string(month),因为输入仅是字符串形式。 删除该行,代码应该可以正常工作

在Python 2中,由于当时必须理解的原因, input()函数试图评估输入为Python表达式的内容 因此,当您在input()提示符下键入jan时,它将尝试查找变量jan 在这种情况下(或几乎所有其他*),这不是您想要的; 您应该改用raw_input()

请注意,在Python 3中(这是从2020年开始唯一受支持的版本input() ,将删除Python 2的input()函数,并将raw_input()函数重命名为just input()


*似乎当您想要一个数字时, input()很有意义; 当用户键入2input()提示,你会得到一个int ,而不是一个str 但是,每当您运行evalinput()都会遇到大量安全问题,因此您仍然应该使用int(raw_input())代替。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM