What is the correct syntax to accomplish my task?

Viewed 59

I am learning python through an online course. One of the tasks is to create a function that asks for the users' age. Put the function in a .py file, then run it from the command line. Everything seems to work fine. The file is created, I call the file and receive the expected result, but I also get a syntax error and I can't figure out why. Can someone please tell me what I am doing wrong?!

I know if I change it from a .py to .txt it runs with no errors, but the request is for a .py and I can't figure out the problem.

I am running Python version 3.8.5.

Here is my code:

def your_age(year):
    return f"You are {year} years old!"

your_age(46)

answer = your_age(46)

file_name = input("Enter a file name: ")

file_name = f"{file_name}.py"

with open(file_name, "w") as f:
    f.write(answer)
    f.close

Screenshot of my syntax error


Update

Thank you everyone for your help.

I realized I was focusing too much on the error and not the actual task.

Correct, I was to put the function itself into a .py file and then call the file in order to get the required result. Making the age a constant was just for the basis of practice. I have re-written my code and actually saved it to a .py file.

I have removed the constant age and added the question 'How old are you?

Here is the updated code:

year = ()

def your_age(year):
    year = input("How old are you? ")
    return f"You are {year} years old!"

age = your_age(year)

print(age)
1 Answers

You're trying to execute a file with Python that has no valid Python code. The file test1.py contains:

You are 46 years old!

...which is not valid Python. If you want to execute this file with Python, you have to make sure that it has valid syntax.

A possible solution to your problem would be editing your your_age function to return a valid Python statement, like this:

def your_age(year):
    return f"print('You are {year} years old!')"

With this, your test1.py file would contain:

print('You are 46 years old!')

...which is valid Python code!

Upon calling python test1.py, You are 46 years old! will be printed to the console.

Related