Python on the Raspberry Pi: Numbers and Dates

Python on the Raspberry Pi: Numbers and Dates

The very reason for being for the Raspberry Pi is to be able to use it to teach kids. By having a computer inexpensive enough to widely distribute them to schools, the The Raspberry Pi Foundation  hopes to be able to teach many young people about computers.

Python is both powerful and easy to understand as a programming language. Python is used by many educators to introduce programming to students.

While I am enjoying learning and sharing what I have learned about my Raspberry Pi on blogspot, I am also attempting to teach an eleven year old boy, Chris, about computer science, as well.

In this post, I will be sharing my first actual Python session that I guided Chris through. We start out calculating our ages in years, and then in days. We covered the basic use of a variable to store values in names that we can reference. Finally, we took a look at a precise way to calculate our ages in days by using the datetime module. Here are some things to note:

  • (#) Comments starting with a # are made where I typed the next line
  • (##) Comments starting with ## are made where Chris was supposed to type the line
  • The dates have been changed, but are close enough
  • Many error in our typing have been removed

To get started, if you are in the GUI (startx), then open the terminal. If you are on the command line only, then your are ready to go!

pi@raspberrypi:~$ python
Python 2.7.3 (default, Jun 18 2012, 16:19:55)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.

# How many years old am I?
>>> 2012 - 1966
# So, how about many days old does that make me?
>>> 46*365
## About how many years old are you?
>>> 2012 - 2001
## So, how many days old are you?
>>> 11*365

# One of the cool things about Python is it can use variables, as names to store values.
# If I wanted to remember how many days old I am, I could store it in a variable called keithdays
>>> keithdays=46*365
>>> keithdays
## What would good be a good variable name to use to store how many days old you are?
>>> chrisdays=11*365
>>> chrisdays

# Why would we want to have Python remember a value for us?
# So, we wouldn't have to remember ourselves or have to type those values in again like:
>>> 16790/4015
>>> 46/11
# Oh, we noticed Python pushes the value down to the floor, or rounds it down.
# It won't in other cases though. If we do operations with decimals, it won't.
>>> 46/11.0

# Back to the variables, if I wanted to know about how many more times old I am than you, I could use:
>>> keithdays/chrisdays
## So, if we wanted a variable to store your Mom's age in days, how would you do it?
>>> momdays = 47*365

## How can you view that value?
>>> momdays
# You can also ask Python to print a value or a variable
>>> yeardays=365
# You can assign the value from one variable to another, especially for a shorter name
>>> y=yeardays
>>> print yeardays

>>> print y

## What is the value of y?
>>> y
## How do you print the value of yeardays?
>>> print yeardays
# See now we can use this variable along with numbers or other variables to do calculations
>>> 10 * y
>>> 10 * 365
## Try to use y in a calculation
>>> 100 * y
# Reminds Chris about how multiplication with factors of 10s is an easy pattern to follow
# What if you multiply y by 1000?
>>> 1000 * y

# Let's do some calculations with variables that have long descriptive names that later on will be clear
>>> daysPerYear = 365
>>> chadiAgeYears = 14
>>> chadiAgeYears * daysPerYear
## Create a variable to store Chadi's age in days.
>>> chadiAgeDays = chadiAgeYears * daysPerYear
>>> chadiAgeDays
## Create a variable to store how many days in a week.
>>> daysPerWeek = 7
## Calculate Chadi's age in weeks
>>> chadiAgeWeeks = chadiAgeDays / daysPerWeek
>>> chadiAgeWeeks

# Does this value make sense, I might double check it like:
>>> 730*7

# Is Chadi really that many days old. Do you remember some years we have a leap year?
# This went off on a whole tangent about leap years and http://en.wikipedia.org/wiki/Leap_year
# (If I had a more advanced student, I would be tempted try a Python function for the pseudo code)
# (update: function is posted in Python on the Raspberry Pi: Leap Year Module)
# So, given Chadi's age, how might we calculate how many leapDays?
>>> leapDays = chadiAgeYears * 1/4
>>> leapDays
>>> 14/4

>>> 14/4.0
## Instead of using 1/4.0, what might we do instead?

>>> leapDaysPerYear = 1/4.0
# Remember the decimal is added to avoid the rounding.
>>> 1/4
>>> 1/4.0
## How many days old are you including leap days?
>>> chrisAgeYears = 11
>>> chrisAgeDays = chrisAgeYears * daysPerYear
>>> chrisLeapDays = chrisAgeYears * leapDaysPerYear
>>> chrisLeapDays
# We did have an old value for your age in days, but the new one reads better

>>> chrisdays

>>> chrisAgeDays
## So now add them together
>>> chrisAgeDays + chrisLeapDays

# Is that really how old you are in days?
# Should the leap days be rounded up or down?
# What about the days since your birthday?
# What is we wanted to calculate your age in days exactly as of today, would that be hard in Python?
# It would be hard if we tried without taking advantage of what other people have already written for Python.
# To be able to use code already written to be used in Python, you import a module like so:

>>> from datetime import datetime
>>> help(datetime)
>>> keithFakeDate = datetime(1966, 12, 31)
>>> keithFakeDate
datetime.datetime(1966, 12, 31, 0, 0)
>>> print keithFakeDate
1966-12-31 00:00:00
>>> todayDate = datetime.today()
>>> todayDate
datetime.datetime(2012, 6, 24, 13, 57, 38, 194119)
>>> print todayDate
2012-06-24 13:57:38.194119
>>> dateDelta = todayDate - keithFakeDate
>>> dateDelta
datetime.timedelta(16612, 50258, 194119)
>>> print dateDelta
16612 days, 13:57:38.194119
>>> dateDelta.days
# We made a lot more mistakes than this, but if we try to access attribute that doesn't exist we got:
>>> dateDelta.hours
Traceback (most recent call last):
  File "", line 1, in
AttributeError: 'datetime.timedelta' object has no attribute 'hours'
>>> dateDelta.seconds
>>> dateDelta.microseconds
## So how old are you in days exactly?
>>> bday = datetime(2001,6,1)
>>> today - bday
datetime.timedelta(4041, 51691, 369045)
>>> days = today - bday
>>> days
datetime.timedelta(4041, 51691, 369045)
>>> days.days
>>> print days
4041 days, 14:21:31.369045

Parsing and Formatting Dates and Times in Python

At this point, we spent a bit of time looking at and playing around with some of the stuff from the Python documentation of the datetime module. One especially interesting section was useful for strptime() and strftime() functions in Python.

As result we also looked at doing simple string concatenation and raw_input() for obtaining user input:

>>> yearNum = raw_input('Enter the four digit year that your were born in (yyyy): ')
Enter the four digit year that your were born in (yyyy): 1966
>>> monthNum = raw_input('Enter the two digit month that your were born in (01-12): ')
Enter the two digit month that your were born in (01-12): 12
>>> dayNum = raw_input('Enter the two digit day that your were born on (01-31): ')
Enter the two digit day that your were born on (01-31): 31

# We captured three strings and we can combine them together with the slashes
>>> dateString =  monthNum + '/' + dayNum + '/' + yearNum
>>> dateString

# We can use the datetime.strptime to parse our string with a certain format string
>>> keithBday = datetime.strptime(dateString, '%m/%d/%Y')
# We get a new datetime.datetime object
>>> keithBday
datetime.datetime(1966, 12, 31, 0, 0)

# We can use many different formatting codes to change the appearance of our date
>>> print keithBday.strftime('%A the %d of %B in %Y')
Saturday the 31 of December in 1966

No comments:

About Me - WrightRocket

My photo

I've worked with computers for over 30 years, programming, administering, using and building them from scratch.

I'm an instructor for technical computer courses, an editor and developer of training manuals, and an Android developer.