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?
Start with documentation (needed for all code) so in 6 months you (and other people) will know why you wrote it.
Comments
Put the filename somewhere and a description of what the code does (not how it does it - that belongs in the code). If you're ever going to give this code to anyone else, you need to put the author and date in the code.
In the print lines, the variables were output, along with some text for the user.
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. |