0

You could call me an extreme newbie, I have a course at school for which I need to be able, sort of, to solve problems using python. All so far have worked, but the last one (just a small part really) wont give in.

The first 4 functions work fine (2 arguments each, a birthday (bday) and a random date (today)). They determine whether or not the random date is a birthday/unbirthday/hundredday/sameweekday, returning True or False if so or not, respectively. First line of every function is the following, rest of the script doesn't matter much.

def birthday(bday, today):

def unbirthday(bday, today):

def hundredday(bday, today):

def sameweekday(bday, today):

Again, these work fine.

The last function has to return all dates, between a certain start and end date, on which one of the above variations of birthdays match. First argument is again bday, the next is start (by default bday, this is the asshole), third is end (by default today) and the fourth is birthday (by default the actual birthday).

def birthdays(bday, start=bday, end=date.today(), birthday=birthday):

its the start=bday that won't work, stating that this bday is undefined. Rest of the script doesn't matter as I don't get so far.

(I import datetime in the beginning of script and all first functions work fine using its tools)

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • 1
    this is no good: `end=date.today()` you need to do `end=None` in the function definition, and the first line or so, do `if end is None:` .. `end = date.today()` the reason is that if you program starts at #/#/#### 11:59:59.999 PM it will have the correct date once, the second time is will be wrong – Javier Buzzi Aug 25 '16 at 18:26
  • 1
    @Simon> worth reading: [python mutable default argument](http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument). It's the same root error, though it's much less problematic in your example. – spectras Aug 25 '16 at 18:28

2 Answers2

2

You cannot read from a variable before it's been created:

def birthdays(bday, start=bday, end=date.today(), birthday=birthday):
                ^---1      ^---2

Function arguments as above are just variable name definitions. "The chunk of data inserted into the function call at this point will be named bday". They don't exist as readable variable WITHIN the function signature, only within the function's body itself. So your #2 above is trying to read from a variable which doesn't exist (yet).

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • 1
    Quick catch. Maybe add a note about the typical way to handle default values, `start=None` and testing `if start is None` at the beginning of the function. – spectras Aug 25 '16 at 18:25
2

One solution would be to default start=None, and then in the function body have:

if start is None:
    start = bday

which should give you the behaviour you want.

StephenTG
  • 2,579
  • 6
  • 26
  • 36