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, and so is W3Schools:Python. For the purposes of CS 1110, 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 plain 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. Remember this!
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!
Hello World: The Simplest Program
The best place to start learning a new programming language is with the most simple program, which throughout world history has been the “hello world” program. All the program does is print “hello world!”. In Python this is:
# let's print something
print("hello world!")
The first line is a comment – a message to other humans reading this program, and not part of the program’s executable statements. Comments are very useful and should be part of your programming. Python comments start with a ‘#’ symbol and end at the end of the line. They can be placed at the end of a code line, too.
The line that prints “hello world!” uses a built-in function named print that outputs the string it is given to the display window so that the user sees it. Part of programming is using all the built-in stuff, and libraries, that make up the programming language.
“hello world!” is a string – a sequence of printable characters. We use strings in many ways in programming, both inside our program and as messages to a user who runs our program. Strings in Python can either be in “double quotes” or ‘single quotes’; good practice is to use single quotes for strings used inside your program, and double quotes for strings that are used for messages to a user.
Variables and Values
Other than the trivial program above, real programs operate on data. To use the data we use variables in our program.
A variable is a named container that holds a value. Always remember this.
We put a value into a variable by using an assignment statement, such as:
x = 42
This puts the integer value 42 into the variable named x. If x already existed, its previous value is thrown away and gone forever and the new value is placed into it. If x did not previously exist, it is created as a new variable and this value is placed inside it.
When we use variable in expressions, the current value inside the variable is accessed and then used in the expression.
In Python, values are always of some type, but variables can be assigned different types of values; the type of the variable is simply the type of the value that is currently inside it. Many other programming languages force you to declare that a variable only can hold one type of value, but Python does not do this; so be careful!
Python has a built-in function type that will tell you the type of a value or variable. So type(42) is int and so is type(x) if we do the assignment above.
Another Sample Program
The following is a valid Python program (in, say, a file named simple.py)
for k in range(1,4):
j = k * 2
print(f"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. The print inside the loop uses a formatting string (with an ‘f’ in front of it), and Python recognizes the curly braces in it and prints the variable’s value instead of its name; in fact, whole expressions could be placed inside curly braces in a formatting string.
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. It assigns, or puts, a new value into 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, times 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.
Python has an if statement, and you can put an optional else on it. If the condition expression is true, the code for the if-part is executed, otherwise the code for the else-part is executed (if it exists). You can create cascading multiple condition tests using the elif keyword (short for “else if”).
A for loop repeats over a sequence of values and uses a loop variable that is assigned the successive values in the sequence, one value per loop repetition. A while loop is simpler: it just has a loop expression that is checked before each repetition of the loop; the loop repeats until this expression becomes false, and then the loop exits. In the program above, “range(1,4)” generates the sequence [1,2,3], which is what the loop runs over.
Note two things: the line that begins a conditional block or a loop body must end with a colon, and as we said before, the block or loop body must be 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, and W3Schools:PythonOperators is good, too. In the official reference, 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 programming any non-trivial program, we must use decomposition to organize our code. The most basic mechanism for this is the function. This idea is the foundation of almost all programming languages, and also in Python. A function is a named 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 and providing parameter values.
Functions come in two forms: 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
# define new function named printStarTriangle
def printStarTriangle (levels):
for k in range(1,levels+1):
for j in range(1,k+1):
print("*",end='')
print("")
# main program execution starts here
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.
Summary
Below is a list of the important (mostly bold) statements above:
- Python is a kind of programming language known as a scripting language;
- We write a Python program in a plain text file with a “.py” extension;
- To run a Python program we use the Python interpreter;
- Python programs execute from the top to the bottom of the file;
- Python uses line-by-line whitespace indentation to determine proper nesting of loops and conditionals and functions; whitespace matters!
- Python comments start with a ‘#’ symbol and end at the end of the line;
- A variable is a named container that holds a value
- In Python, values are always of some type, and a variable’s type is just the type of the value currently in it;
- We can use formatting strings (with a ‘f’ in front) and curly braces in the string to created formatted output;
- Python uses the import statement to import libraries we want to use in our code
- The assignment statement is how we put new values into variables
- The Python if statement enables conditional execution, and can have optional else and elif parts;
- Basic Python loops are the for loop and the while loop;
- A function is a named 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 and providing parameter values.