Getting started with Python (part 3 – for newbs)
In this tutorial, I’ll go over some of the basic concepts of programming, and how to use them in Python.
Keep in mind that having good reference material is important. The Python documentation, and some of the free Python books can be very helpful.
Starting with the basics, what is a program? A program is a collection of steps to accomplish a task. Technically, that’s true for every program that was ever created.
You’ll probably see Python programs referred to as “scripts”. Programs and scripts are in a way, synonyms. Both are a collection of steps to accomplish a task. However, scripts sometimes depend on, or are run by other programs. Scripts are usually stored in plain text, and are run by an interpreter. Programs are usually compiled (into a intermediate language, or directly to machine code).
Variables
Variables are locations in memory, referenced by an identifier, that can be used to store data.
Variables allow us to make our scripts useful (as opposed to completely useless), since without them, we could never operate on different data without editing the source code.
Now, what is an identifier? An identifier is a name for something. There are some rules that apply when choosing identifier names.
- Identifiers must start with a upper or lower case letter or underscore, and can be followed by other letters, numbers or underscores. You can’t use other characters in identifier names.
- Certain names are “reserved” by the Python language, and can’t be used as identifiers.
- Identifiers are case sensitive. E.g. Abc is not the same as abc.
- There are important conventions to follow when choosing an identifier (we will explore them later)
Here’s how we’d create a variable that holds an integer:
identifierHere = 5
What that statement means is: Take the data 5, make identifierHere a name for that data.
What if you want to make another name for 5? It’s easy:
anotherName = identifierHere
This line of code is a little tricky. It means: Take the data that identifierHere is a name for, and make anotherName a name for that data (5 in this case).
What would happen to anotherName if I added one to identifierHere? identifierHere would be assigned a new value of 6, and anotherName would keep it’s value of 5. Variables that contain classes behave differently, and we’ll explore that later.
Python is not strongly typed, which means that you don’t specify the type of a variable when you create it. By assigning it a value you give it that value’s type. You also can change a variable’s type, by assigning a value of another type.
You can create floating point variables just as easily as we did for integers:
identifierHere = 5.5019
Strings:
identifierHere = "string"
There are several ways to specify that a sequence of characters is a string. You can enclose the string with single quotes (‘), double quotes (“), three double quotes (“”") or three single quotes (”’).
If your string has multiple lines, you don’t have to use a line continuation character if you use three double or single quotes.
Here are some examples:
a = "a string" b "a multi\ line string" c = """A multi line string"""
Functions
Functions are “subprograms”, which means they are a “subset” of the larger program.
Functions can take input (called parameters), and return output (using the return statement).
Parameters are special variables, that are automatically assigned the value(s) that are passed to them when the function is called.
Arguments are the values that are passed to a function’s parameters when the function is called. Here’s an example:
# Function definition
def foo(parameter1, parameter2):
# pass means do nothing
pass
# Function call
foo(argument1, argument2)
Here’s the definition for a basic Python function:
def add_one(item):
return item + 1
print add_one(5)
On line 1, I defined a function called add_one, that takes a parameter called item.
On line 2, I returned the result of item + 1.
On line 3, I called the function add_one, and passed it the argument 5. When Python enters the function, item will be assigned the value 5. I then print what add_one returns, which is 6 (5 + 1).
Functions can have multiple parameters (separated by commas):
def add(item1, item2):
return item + item2
print add(5, 6)
On line 1, I defined a function called add, that takes a parameter called item1, and a parameter called item2.
On line 2, I returned the result of item1 + item2.
On line 3, I called add, and passed it the arguments 5 and six. When Python enters the function, the parameter item1 will be assigned the value 5, and parameter item2 will be assigned the value 6. I then print what add returns, which is 11 (5 + 6).
Order with parameters is very important. When you call a function, you need to put the parameters in the order that your function expects. For example:
# This function expects a string in item1, and an integer in
# item2
def foo(item1, item2):
print item1
return item2 * 2
# Outputs "string" on the first line, and 10 on the next
print foo("string", 5)
# Outputs 5 on the first line, and stringstring on the next
# That's not what we wanted
print foo(5, "string")
If you don’t have the parameters in the correct order, you can get unexpected results, or an exception (a program error).
There are other ways to pass arguments, which you can read about here.
The main reason for using functions is that you can use the code in a function as many times as you want, just by calling the function. We’ll explore when functions should be created later in this tutorial.
Input and output
The term input means to bring data into your script. Input is stored into variables, and can then be used by your script.
Depending on the script you want to write, your input may come from different places. A database, command line parameters, files, network sockets, etc.
Let’s read a string from the keyboard:
x = raw_input("Enter a string --> ")
Enter a string --> test
On line 1, I call the function raw_input, and I pass it the prompt message I want it to use, and I assign the return value of the function.
On line 2, I enter the string ‘test’ on my keyboard and press enter.
If we look in x, we will find:
x = 'test'
Now what if we wanted to read an integer and do some math with it?
x = raw_input("Enter an integer --> ")
Enter a integer --> 5
Now we have the integer in string form, stored in x. We need to convert it to an integer. It’s pretty simple:
y = int(x)
y now contains the integer 5.
This is all well and good, but there is something to watch out for. If the user entered something like abc, we would get an exception from the int function, and our program would stop executing. We’ll explore how to handle exceptions in a later tutorial.
If you want to output information, it’s really simple:
print "Hello World."
You can replace Hello World with a variable:
print x
Flow control
When you write a program, it will probably make “decisions” on what code should be run, based on the input that it receives, or the result of an operation it performs.
The most basic control flow tool is the if statement. An if statement at it’s core says, if something is true, then do this. If statements can have an else clause, which will get executed if the something in the if statement is false. You can also have something called else if, which is just like an else, except that it has a test of it’s own that must be passed to enter it’s block of code.
Here’s an example:
value = int(raw_input("Enter an integer --> "))
if value > 5:
print "You entered a value greater than five."
else
print "You entered a value less than or equal to five."
In the if statement, I used a comparison operator, “>”. What really happens in the if statement is that the expression “value > 5″ is evaluated, and replaced with a true or false. That value is then tested by the if statement. You can find a list of operators (and the order of operations) here.
Another good thing to keep in mind is that any non zero value is true. This means that:
bool(-20) # True bool(-1) # True bool(0) # False bool(1) # True bool (20) # True
If I want to test that two things are true in an if statement, I can use the and operator.
value = int(raw_input("Enter an integer --> "))
printSomething = raw_input("Print result (y/n)? ")
if value > 5 and printSomething == "y":
print "You entered a value greater than five."
else
print "You entered a value less than or equal to five."
I prefer to enclose the two expressions that I’m comparing with parentheses:
value = int(raw_input("Enter an integer --> "))
printSomething = raw_input("Print result (y/n)? ")
if (value > 5) and (printSomething == "y"):
print "You entered a value greater than five."
else
print "You entered a value less than or equal to five."
A key thing to remember is that Python uses short circuit evaluation with and and or operators (it does NOT with & (a different and operator) and | (a different or operator)). With an and operator, if the first item is false, it won’t even check the second item, since even if it was true, it wouldn’t matter. With an or operator, if the first item is true, it won’t check the second item, since even if false, it doesn’t matter.
Writing your first program
You have enough base knowledge to write a basic script.
When your script is loaded by the Python interpreter, a special variable called __name__ is set to “__main__”. Basically, when __name__ is set to “__main__”, your script is the main script, and isn’t being used as a module. In this case, you want to execute your program’s code.
Before we do anything, we need to import a module from the Python standard library.
import sys
That line will make items in the sys module available to our script, one of which we’ll use later.
We’ll define a main function, and create an if statement to execute it when your script is the main script.
This program will input two strings, convert them to integers, and output the larger value. Let’s write the main function now:
def main():
x = int(raw_input("Enter the first integer --> "))
y = int(raw_input("Enter the second integer --> "))
if x > y
print x
else
print y
# The zero will be passed to the OS as the exit code.
# Returning zero means everything is OK, anything else
# means there was a problem
return 0
Now that we’ve defined the main function, we need to call it when our script is run as the main script.
# Run main
if __name__ == "__main__":
sys.exit(main())
Line 2 is a little tricky. I’m calling the main function, and passing it’s return value to sys.exit(), which exits the python script. It gets the exit code that we return from main, and passes it. If we didn’t import the sys module, we wouldn’t be able to call sys.exit().
Now, you’re probably wondering, how can I do something useful with Python? The answer is by using the huge standard library that’s included with Python.
You’ll probably want to write your Python scripts in an IDE like PyScripter (which we installed in the first tutorial). I’ll let you figure out how to launch the IDE, and create a Python script file. I recommend you turn line numbers on (Tools -> Options -> Editor Options or click the line numbers button on the toolbar).
In the next tutorial, I’ll talk about IDLE (the interactive Python shell and IDE), and how to access an interactive Python shell from PyScripter.