Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Syntax Error' when returning True on Python 3.2

I have the following function in my script at the minute:

def _convert_time(p):
    """Converts a percentage into a date,
    based on current date."""

    # This is the number of years that we subtract from
    # the current date.
    p_year = pow(math.e, (20.344 * pow(p, 3) + 3)) - pow(math.e, 3)

    # Returns in YYYY-MM-DD format
    date_in_history = date.today() - timedelta(days=(p_year * 365)

    # Return to the control loop
    return True

All of my functions use this system of returning True at the end, this is due to there being a central function which runs each function in sequence and check if they ran correctly before executing the next function.

However, when I run the script, before I even get to input a value to start the script, I get the following error:

 File "C:\Users\Callum\Desktop\Tempus\TempusTest.py", line 59
 return True
      ^

If I make a function in the IDLE that returns True and check it, it works fine, but for some reason it doesn't in my script

Have you guys got any ideas on why this might be?

Thanks! :)

like image 608
Callum Booth Avatar asked Sep 12 '25 05:09

Callum Booth


1 Answers

You are missing a bracket.

You need to change this line:

date_in_history = date.today() - timedelta(days=(p_year * 365)

with:

date_in_history = date.today() - timedelta(days=(p_year * 365))
                                                              ^
                                                              |
                                                       it was this one :)

Q: Why was it showing an error on the return line and not there?

Because the error is actually there.

How could Python know that you weren't going to give another legit timedelta argument on the next line?
Or adding a +100 to (p_year * 365)? (like DSM suggested)

Let's take a look at this IDE session:

>>> t = ('one', 'two',
...      'three'
... def f(): pass
  File "<stdin>", line 3
    def f(): pass
      ^
SyntaxError: invalid syntax

The IDE couldn't know that my tuple was finished and I wasn't going to add a 'fourth' element.

You may want to play the devil's advocate and say that I dind't typed the comma so Python should have guessed that I was going to end the tuple there.

But take a look at this other example:

>>> t = ('one', 'two',
...      'three'
...      'fourth')
>>> 
>>> t
('one', 'two', 'threefourth')

So as you see the error occured exactly when Python encountered a return True in a place where it wasn't supposed to be.

like image 174
Rik Poggi Avatar answered Sep 14 '25 20:09

Rik Poggi