Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

X is not defined

I’m going through basic pythonprinciples problems, and one of them lists the instructions as:

Write a function named make_day_string that takes an integer named day and returns the string "it is day X of the month" where X is the value of the day parameter.

For example, calling make_day_string(3) should return "it is day 3 of the month".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Remember that to concatenate a string with an integer, you must cast the integer to a string.

Note that the function should return a value. It should not print anything.

My answer is:

def make_day_string(day):
    day == str(X)
    return ("it is day " + X + " of the month")
    
print(make_day_string(3)

However, the terminal says

NameError: name 'X' is not defined

I’m confused on how to properly define X in this context, if it’s not day == str(X)

>Solution :

There are a couple of problems with your code. X isn’t defined because you aren’t ever passing it in as a value when you call the function. You never say X = someValue before you try to assign X’s value (which doesn’t exist) to a different variable.

Also, you wrote day == str(X) instead of day = str(X).The former is a comparison operation, while the latter is an assignment statement. You are also missing a closing parenthesis at the end of your print statement.

Here’s one way that you could modify your code to return the dayString;

def make_day_string(X):
    dayStr = str(X)
    return ("it is day " + dayStr  + " of the month")
    
print(make_day_string(3))

Since we pass X into the function, it has a value and is defined.

Also, it might be easier if you used an fstring instead. They allow you to add variables into a string, so you can just do this instead:

def make_day_string(day):
    return (f"it is day {day} of the month")

print(make_day_string(3))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading