[Project] Verifying a user's age

Nice for a first!

  1. No need to use input(): You can use command line arguments, so (everything in <> needs to be filled in): >>>python firstProj.py <day> <month> <year> In your code, you can then access these using a special list called "argv" - this is the list of all command line arguments! Here's what will be inside:

argv[0] == "firstProj.py" argv[1] == <day> argv[2] == <month> argv[3] == <year>

In python, argv is part of the sys module (get to it using sys.argv). Your code might look like this if you used argv: import sys #Imports the sys module from Python's standard library. import datetime

now = datetime.datetime.now()

birthTime = dict(zip(["day", "month", "year"], sys.argv[1:])) #Gonna explain this, don't worry.
currentTime = dict(zip(["day", "month", "year"], [now.day, now.month, now.year]))

#Do the days/month thing much easier and more readably using two DICTIONARIES.
  1. WHAT is that? First of all, DICTIONARIES: L = [1, 5, 2, 3] #Indexed by 0, 1, 2, 3. L[1] == 5 and L[0] == 0 #L[1] means "the item at index 1 of list L"

    True

    D = {"hi" : 2, "yes" : 42} #Notice the pairing of "hi" to 2, and of "yes" to "42". D["hi"] == 2 #D["hi"] means "the item at index "hi" of dictionary D".

    True Dictionaries are like lists, in that you say dict[index]. But in dictionaries, you can use an easily understandable STRING (or other objects even) to index by.

So why did I make two of these dictionaries? I will demonstrate: birthTime["day"] == currentTime["day"] #Remember the quotes around strings!!! >>>True Isn't that cool? And more importantly, doesn't it kinda just tell you what it's trying to do?

  1. So what's that zip() business? zip() makes a list of tuples (think of these as lists you can't change) out of two lists, like so: tupList = zip(["day", "month", "year"], [4, 5, 6]) >>>[("day", 4), ("month", 5), ("year", 6)]

Notice the pairing of the two lists: index 0 of the first list is paired with index 0 of the second, and so on. But, on the topic of pairing, isn't that what dictionaries are for? Turns out, we can make a dictionary very easily from a list of tuples, using the dict() function: D = dict(tupList) >>>{'day': 4, 'year': 6, 'month': 5}

Python is all about readability and power, which is part of why it's such a great first language. Still, some conventions are good: Variable names, for example, should in all cases be understandable. myVar3 is not understandable, even in a little script such as this. You will, in future larger projects, thank yourself for establishing good variable naming habits early on :).

Hopefully I was helpful! Have a nice day!

/r/beginnerprojects Thread Parent