簡體   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