Python: An Introduction
This is a short introduction to Python 3, with my own focus and purpose. If you want a complete introduction to Python, the official Python Tutorial is a good place to go. For the purposes of CS 111, I would not read past Chapter 4 – the rest will probably just confuse you! Chapters 3 and 4 contain the heart of the Python language. The official documentation also has a language reference which is good for looking up specific operators and syntax when you do things wrong. Note that the links above are all for Python 3; Python 2 has its own set of documentation.
Python is a programming language known as a scripting language. Why scripting? Well, rather than requiring you to compile your source code into some other executable form (native machine code or Java bytecode, for example), you just run a Python interpreter directly on your Python source code and it reads and executes your program. Languages where the program is directly run by an interpreter have often been called scripting languages, partly because such immediate use of a program allows you to rapidly write little “script” programs and then use them quickly. But you can write big programs in Python, too!
Like other textual programming languages, you write your Python code in a text file; you should name your Python code files with a file name that has a “.py” extension on it. This indicates to you that this file is Python source code, and some operating systems will automatically associate the extension “.py” with Python. In addition, most text editors that are used for programming (such as gedit on Linux) will automatically highlight (with color) the keywords and syntax of your Python code when it sees the file extension “.py”. So use it!
Unlike compile-oriented languages like C, C++, and Java, which all start your program in a function called “main”, Python (and many other scripting languages) simply start at the top of the file and go to the end. One big difference with Python that almost no other language has: in Python, whitespace matters! (whitespace is the generic word for spaces, tabs, and newlines (line breaks)). Python uses line-by-line whitespace indentation to determine proper nesting of loops and conditionals and functions. No curly braces for this! So beware!
The following is a valid Python program (in a file named simple.py)
for k in range(1,4):
j = k * 2
print("Hello! k is", k, "and j is", j)
print("Done!")
If we run the above program using the command “python simple.py” it outputs:
Hello! k is 1 and j is 2
Hello! k is 2 and j is 4
Hello! k is 3 and j is 6
Done!
Notice: there are two variables, k and j, and each is created automatically without any need for declaring them; k is automatically assigned consecutive values from 1 to 3 as the loop iterates, while j is assigned using the assignment statement. The two indented lines below the for loop are inside the loop body and execute each time the loop is performed. Instead of always typing the command “python” in front of our program file name, we can make our program self-executable, by adding the first line below and then setting the file properties to include “executable”
#!/usr/bin/python3
import sys
for k in range(1,4):
j = k * 2
print("Hello! k is", k, "and j is", j)
print("Done!")
sys.exit(0)
The first line in the above program is required to tell the operating system (O/S) which program to run in order to run this code. Basically, the O/S reads that line and then runs the Python interpreter for you. You can still do “python simple.py” even with the code above, but you can also just do “./simple.py” and the program will run “all by itself”!
The code above also has two other new lines of code: the “import sys” and the “sys.exit(0)”. The import statement in Python allows you to bring in a library of pre-written functions and then use them in your code. In this case we are bringing in the “sys” library, and then using the function “exit” in our code in order to nicely end our program. A program will always end at the end of the file anyways, but “sys.exit(aNumber)” allows you exit anywhere and will return the number you give it as a code back to the O/S.
Assignment Statements
The most basic statement in many programming languages is the assignment statement. This is equivalent to the “set” block in Snap – it assigns a new value to some variable. In Python and many other textual programming languages, the “=” (equals) symbol is used to indicate assignment. Note that this is different from algebra! The “=” symbol is NOT a declaration of equality, and it is NOT a conditional test to see if the two sides are equal, it is an ACTION that assigns the value on the right hand side as the new value of the variable on the left hand side.
The value on the right hand side might come from a number, another variable, some expression, or a function return value. The expression can even involve the same variable that is on the left – in that case the current value of the variable is used on the right hand side, and then the resulting value of the expression becomes the new value of the variable.
In the above program, the assignment statement
j = k + 2
assigns j a value that is the current value of the variable k, plus 2. It does this each time the assignment statement is executed, and since the statement is in the loop, this happens three times. Variables are called variables because they can hold different values at different points in the program’s execution!
Conditionals and Loops
Python, as with all programming languages, has specific structures for conditional and repetitive execution. In Snap we had the if and if-else blocks for conditional execution, and the various repeat blocks for repetition (looping). Python has an if statement, and you can put an else on it, and even multiple else-ifs (named elif). For looping, Python has a while loop and a for loop. Note two things: the line that begins a conditional block or a loop body end with a colon, and as we said above, the block or loop body is indented in order to signify all the lines that form the block.
The program below takes the above code and adds in some conditional code and changes the for loop to a while loop.
#!/usr/bin/python3
import sys
k = 1
while k < 7:
j = k * 2
print("Hello! k is", k, "and j is", j)
if k % 2 == 0:
print(k, "is even!")
elif k % 3 == 0:
print(k, "is divisible by 3!")
else:
print(k, "is generic!")
k = k + 1
print("Done!")
sys.exit(0)
The initial assignment statement of k, the while loop with its condition, and the last statement in the loop of “k = k + 1” all together do exactly the same thing as if we had “for k in range(1,6)”. Just read it naturally: k is initially 1, then the loop executes as long as k is less than 7, at each time through the loop the last thing that is done is that k is incremented by 1. The output of the program is:
Hello! k is 1 and j is 2
1 is generic!
Hello! k is 2 and j is 4
2 is even!
Hello! k is 3 and j is 6
3 is divisible by 3!
Hello! k is 4 and j is 8
4 is even!
Hello! k is 5 and j is 10
5 is generic!
Hello! k is 6 and j is 12
6 is even!
Done!
Notice how the if-elif-else works: only one of the blocks executes each time through the loop – and it is the first block whose condition is true. So notice that in the last loop execution, when k is 6, only the statement that k is even is printed, not that k is divisible by 3; this is because the if condition is true, so no other “else-if” or “else” conditions are considered.
Operators
Chapter 6 of the language reference has a complete description of how expressions and operators are evaluated in Python. Skip the beginning and go to 5.4 – 5.9 to see the operators. In general, the normal math operators are supported: (+,-,*,/) are addition, subtraction, multiplication, and division. Also, % is the remainder (modulus) operator, which gives the remainder of integer division, and ** is the power operator, which raises something to a power. Python also has // as “floor division” which always yields an integer result.
Comparison operators offer all the necessary comparisons: <, >, <=, >=, ==, and != are the less than, less than or equal, greater than, greater than or equal, equal, and not equal comparisons, respectively. NOTE: the equality comparison is TWO equals signs: one equals sign is ALWAYS the assignment statement. Careful!
Functions
In Snap we were able to create new blocks that embodied some new capability that we wrote code for, and then we could use the block where ever we wanted. This basic idea is the foundation of all programming languages, and in Python it means that we can create new functions. A function is, like a Snap block, a piece of code that we separate from the rest of our program, give it a name and some input parameters, and then use it whenever we need it by calling it by its name.
Functions come in two forms (similar to Snap command and operator blocks): those that do something (e.g., commands) and those that compute something (e.g., operators). For now we will look at an example that does something. The following code shows a function and its use:
#!/usr/bin/python3
import sys
def printStarTriangle (levels):
for k in range(1,levels+1):
for j in range(1,k+1):
print("*",end='')
print("")
print("A small star triangle:")
printStarTriangle(3)
print("A bigger star triangle:")
printStarTriangle(5)
sys.exit(0)
This program prints out:
A small star triangle:
*
**
***
A bigger star triangle:
*
**
***
****
*****
The def statement is what begins the definition of a function. You put the name of the function and then a parenthized list of all the parameters that the function takes, then a colon. Just like the loop and conditional constructs, the code that is the body of the function must be indented, and the end of the indentation marks the end of the function.