10. Variables

In a program, data is held in variables. variables can be manipulated by functions appropriate for their data type (i.e. math on numbers, string functions on strings). Fire up your editor in your class_files directory and try this (you do not need the shebang if you're in windows). Save the file as variables.py (you can swipe the code with the mouse if you like. In X-window, the tabs are replaced by spaces, which may cause problems with your python interpreter. You could edit the mouse swiped code to replace all occurences of 8 spaces with a tab.)

#! /usr/bin/python
""" variable.py
    Kirby. 2008
    class exercise in variables
"""
#
#put in a name (your own if you like).
name="Kirby"    	#name is a string, it needs quotes.

#Put in an age.
age=12          	#age is an integer, however it will be output as a string.

age_next_year=age + 1   #another integer

print "Hi, my name is " + name + ", a word with " + repr(len(name)) + " letters."
print "I'm " + repr(age) + " years old."
print "On my next birthday I will be " + repr(age_next_year) + " years old"
print "and will have been alive for " + repr(int(round(age_next_year * 365.25))) + " days."
# variable.py -------------------------

If it didn't run

What's the code doing?

Rerun the program without round() or int() to see what happens. When you modify working code, you comment (#) out the current code (keeping it incase you decided to return to it - always keep working code, till you're sure that you have better code), make a copy and then modify the copy. Here's how you'd start modifying the last line of the code above.

#print "and will have been alive for " + repr(int(round(age_next_year * 365.25))) + " days."
print "and will have been alive for " + repr(round(age_next_year * 365.25)) + " days."

When you have the code you want, you delete all the commented attempts.

Change the line

print "On my next birthday I will be " + repr(age_next_year) + " years old"

to output your age on your next birthday, by using the variable "age" and some arithmetic, rather than the variable "age_next_year" [53] .

change this line again (including the text) to give your age in 2050 [54] .

Note
Did you get a reasonable answer? Starting with your age now, count your age to the same day at the end of the decade (say 2010), then add 40. The 2008 in the above line must be the year of your last birthday. If it's 2008 and your last birthday was in 2007, then you will need to put 2007 in the above line.


[53]

print "On my next birthday I will be " + repr(age + 1) + " years old"

[54]

print "In 2050 I will be " + repr(age + 2050 - 2008) + " years old"