'Python NameError - Name not defined
A function called month_days, that receives the name of the month and the number of days in that month as parameters. Adapt the rest of the code so that the result is the same. Confirm your results by making a function call with the correct parameters for both months listed.
def month_days(month, days):
month__name = str(month)
month__days = int(days)
print(month__name + "has" + month__days + "days" )
month_days(June,30)
Giving following error
NameError: name 'June' is not defined
Solution 1:[1]
First, let's try to understand what is NameError. NameError in Python often refers to execution or calling an object which is not found or not instantiated.
Here in you case month_days(June, 30), what is this June? Is it a variable already defined?
My guess if you are trying to pass June string as input, if so try to do the following
month_days("June", 30) # works
month_days('June', 30) # also works
In Python generally, all string inputs are enclosed in single or double-quotes.
Solution 2:[2]
You are passing June as value to a function, hence, it should be as string i.e with singe/double quotes. One more issue i have observed with you code is you are adding integer (month_days) with string. Hence, corrected by converting input days as string i/o integer. Please find below code.
def month_days(month, days):
month__name = str(month)
month__days = str(days)
print( month__name+" has " + month__days + " days" )
month_days('June',30)
Solution 3:[3]
This can work too:
def month_days(month, days):
print(month + " has " + str(days) + " days.")
month_days("June", 30)
month_days("July", 31)
Solution 4:[4]
Just a couple of fixes, you are really close.
Within the print statement inside the body, you will want to ensure an explicit conversion takes place on
month__daysby using thestr()function.You will want the appropriate spaces and a
"."at the end of your print statement. This is just what the coursera autograder expects, so it has to be precise.Lastly, as others have mentioned, you will want to put quotations around
JuneandJuly.
def month_days(month, days):
month__name = str(month)
month__days = int(days)
print(month__name + " has " + str(month__days) + " days." )
month_days('June', 30)
month_days('July', 31)
Hope that helps! :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | wjandrea |
| Solution 2 | Tarun Kose |
| Solution 3 | skibee |
| Solution 4 | Freddy Mcloughlan |
