This is Part III of Understanding Programming: A Primer, an exclusive series for EDUKWEST designed to teach you the basics of computer programming. This series is designed to be a tutorial and you will be the most successful if you work through the tutorial with your text editor open. Key in the code as it appears and try to make it run correctly yourself. You’ll find that by the end of this series, you’ll be able to develop simple programs and understand the process of computer programming.
In the last lesson, we looked at input and output, which, of course, allow us to get data into and out of our Python program. In this lesson we’ll take a closer look at one of the most important aspects of programming–variables. You may not equate this to computer programming, but you’ve likely been using variables since high school as you took courses in Algebra, Chemistry and Physics. In classic “solve for x” problems, “x” is a variable.
Let’s first take a look at how the Python programming environment handles variables.
Declaring and Initializing Variables
Many languages require that you declare a variable before use– however in Python we have a simpler paradigm in which variables can be declared and initialized at the same time. In Python variables aren’t differentiated by the type of data they hold. In more complex languages like C++ or Java, variables are typed according to the type of data they hold. In Python declaring and initializing a variables is this simple:
blogName = “Edukwest”
Here, we’ve created a variable called blogName and initialized with the string value “Edukwest.” The equals sign in this context is the assignment operator. The string value “Edukwest” is being assigned to the variable blogName. There are actually three types of primary values we can store in variables.
Key in the following code (Of course, feel free to substitute your own values for the variables):
gpa = 3.82 #floating point number
age = 40 #integer
name = “Mark Lassoff” #string
print name, “is “, age ,” years old and had a GPA much lower than “, gpa
Save your file as variables.py and run it with the Python command. Your output should appear similar to the screenshot below.
Figure 1.1: Variables.py executing in the Koding.com virual Linux environment.
In the code I used comments to indicate the types of variables that were being created. Regardless of the type of variable being created, the syntax is the same. To review the types of variables are:
String: String variables are comprised of a series of characters in a particular order that have no mathematical value.
Integer: Integer variables contain whole number values with no decimal point.
Floating Point Values: Floating point variables contain more precise numbers that have a whole number and fractional amount represented by a decimal point value.
Variables are dynamic– in that the value can be changed or reassigned through the life of the program. Imagine, for example, that in a video game you have a variable that tracks the player’s score. As they players score changes that value would go up until the game is over. Once the game ends, the value inside the player’s score variable might be reassigned the value zero,
Consider the following code:
first = raw_input(“What is your first name? “)
last = raw_input(“What is your last name? “)
fullName= first + ” “+ last
middle = raw_input(“What is your middle name? “)
fullName = first + ” “ + middle +” “+ last
Enter the code and running the program yields the following result:
Figure 1.2 : During the lifetime of the fullName variable the value is reassigned
Note that when we first declare the fullName variable, it is assigned the values of first and last concatenated by the + sign. That value is then printed to the console. As the program continues to execute, the value of fullName is reassigned to include the variable middle as well. When a variable is assigned a new value, it’s original value is cleared and replaced with the new value.
Arithmetic with Variables
Variables are frequently used as part of arithmetic expressions in Python. Arithmetic in Python is no different than the arithmetic you learned in grade school. The following symbols are used:
If you are new to programming, modulus, may be unfamiliar to you, but the concept is easy– Modulus is the remainder after division. For example:
10 % 3 = 1
11 % 3 = 2
12 % 3 = 0
Most frequently when programming, I use modulus to determine if a number is even or odd. Any even number, used with modulus 2 will result in zero.
Talk the Talk: Most programmers will say ‘mod for short when they are talking about modulus.
Math with variables looks pretty much as you’d expect. Key in the following example program:
operand1 = 3432.4
operand2 = 1232.55
print operand1 + operand2
print operand1 – operand2
print operand1 * operand2
print operand1 / operand2
print 14 % 5
In this program two variables are declared as operand1 and operand2. Then the operands are put in two expressions using addition, subtraction, multiplication and edition. A final print statement uses the modulus statement in an expression. When you run the program with the python command the result should appear similar to this:
Figure 1.3: Python program evaluating several mathematical expressions and outputting the result to the console.
When working with arithmetic in programming it’s important to keep in mind the order of operations. Let’s use Python’s interactive mode for this example. At your system prompt, just type Python. This will put you in Python’s interactive mode where you can interact withthe Python interpreter directly. Using the following example as your guide enter the following and see if you can explain the result in terms of the order of operations.
Figure 1.4: Different expressions are evaluated in Python’s interactive mode demonstrating the order of operations.
Was the result always what you expected? The order of operations determines what part of a mathematical expression is evaluated first. The order of operations is:
A common error made by new programmers is to incorrectly interpret the order of operations within a math related problem– Often times when this happens a program will still run but give an incorrect result.
Working with Strings
Python is frequently used to manipulate strings. In fact manipulating strings is a common task for programmers. Imagine, for example, you’re given a list of data where first and last names are combined into a single field. Using string manipulation techniques you’d have to separate them into separate fields by extracting data from the string.
The Python String Methods will allow you to manipulate strings in every way imaginable. You can see the Python documentation on the String Methods here:
Let’s work with a few String Methods. Key in the following program– our last for this week. This program demonstrates just a few of the string functions. You don’t have to type the embedded comments if you don’t want to. They are just for your reference.
phrase = “The quick brown fox jumped over the lazy dogs.”
print len(phrase) #length of the phrase in characters
print phrase.index(“fox”) #Where is fox in the phrase
print phrase.replace(“jumped”, “galavanted”) #replace jumped with new word
print phrase.swapcase() #Swap upper and lower
Once you run the program, you should see a result similar to the screenshot below.
Figure 1.5: String manipulation result in Python
As you can see, Python’s string manipulation features are powerful.
I’m looking forward to seeing you next time!
Please contact the author at firstname.lastname@example.org if you are interested in this and similar lessons for classroom use.
If you are interested in a formal version of this course for yourself or others, LearnToProgram has a special discount for EDUKWEST readers. Programming for Absolute Beginners is the starting point for our Development Club which provides over 30 self-paced courses, and as many live courses as you want to take. For more information and to access the EDUKWEST reader discount, visit: