Skip to Content

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 CSCI 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. Another good resource is W3Schools:Python; it has ads, but has nice, accessible content, on Python and many other languages and technologies. A free OpenStax: Intro to Python Textbook is also a good resource.

The official Python3 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 here.

What is a Programming Language?

A programming language is a written language that we use to tell a computer what to do. Internally, computers only understand very simple machine instructions, and we need millions, even billions, of those simple instructions to create meaningful apps that humans can use – so we create much higher level programming languages that we can use to ease the task of creating apps for our computers. Then we rely on compilers and interpreters to translate our high-level programs into the low-level machine instructions.

Our natural human languages have syntax and grammar – rules of the language – and so do programming languages, but programming languages are much more rigid that natural languages. You have to exactly adhere to the syntax and grammar of the language when you write a program. When a Python program fails to run (or a Java program fails to compile), you often have to track down and find a syntax error that is making your program to not be understandable. Programs must exactly adhere to the language’s syntax and grammar!

What is Python?

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 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. A plain text file is not a Word document or even a Notepad document that looks like text; it is a file that has no formatting, only raw ASCII character date. In Unix/Linux, gedit, vim, pico, and other editors are used for plain text files; MacOS has a texteditor application, and (I think) in Windows the Wordpad app can be used if you are careful to “Save As” a plain text document. IDEs and editor apps that are geared towards programming are better. VSCode (Visual Studio Code) is a popular cross-platform IDE. Python comes with the IDLE editor and execution environment, which is easy to use for small programs.

You should always 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!

A Word About IDLE

In CSCI 1110 we use the IDLE application to create and run Python programs. When you first start IDLE it opens up a Python command shell, which is a window in which you have an interactive Python session that lets you type in individual Python statements and see what they do, and where the input and output of any program you run will happen. IDLE also has a File->Open menu option (and File->New) that will open a text editor window and will let you create and edit a Python program file, and will allow you to run the program (using the Run menu).

While reading this page you could, indeed, open IDLE and “play along” with the examples and see what they do. One-line statements could be pasted into the interactive shell, but the larger examples should be pasted into a text editor window and saved as a “.py” Python program file.

The Fundamental Rule of Python Code Execution and Structure

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 always! Now there are some conditions that will arise – loops will repeat some lines, and if-conditions may skip some lines, and function definitions will define things to be used later, but still the fundamental rule applies: start at the top and work your way down.

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 – which is a message to other humans reading this program, and is 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. Comments can be placed at the end of a code line, too, but usually are on their own separate line.

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 in any language is learning how to use 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.

Python Variables, Values, and the Assignment Statement

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. It is called a variable because you can change the value that is in it – but always understand that when you put a new value into a variable, whatever was in there before is gone forever. A variable does not remember its history of values.

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.

The assignment statement is the heart of most programming! It allows us to compute new values from our existing data and then to save that new value into a variable. The right hand side of the assignment statement can be a complicated expression, such as:

x = 54*y + (z**2 - w)

The above line multiplies the current value of the variable y by 54, and adds to that the square of the value of the variable z minus the value of the variable w (assuming variables y, z and w exist). So this is a computation that makes a new value. This new value is then stored in the variable x (and throwing out the old value of x).

When we use a variable in expressions, the current value inside the variable is accessed and then used in the expression.

The *, +, **, and - are all arithmetic operators which perform an arithmentic computation – in these cases, multiply, addition, exponentiation, and subtraction, respectively. All programming languages have lots of operators.

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 named 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.

Programming is Great for Repeating Things: Python Loops

Probably the reason we like computers the most is that they are great for doing repetetive tasks or computations. In programming, repeating code is usually done in loops. The Python for loop is an easy loop to learn.

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!

What is going on here? Well, the two indented lines are being repeated three times, and each time the variable k has a different value. We call the two indented lines the loop body, and we call the line beginning with for the loop header or loop control. The loop control is responsible for repeating the loop body according to the conditions set on the control line. In this case, the loop control says “repeat the loop body while setting the variable k to the integer values from 1 to just less than 4”. This is done in order and the repetition ends when there are no more values to repeat over. We also use the verb iterate (and iteration) to describe repetition, and sometimes just say looping.

The loop uses range, which is a built-in Python operator that creates a sequence of integer values; range(1,4) is the sequence [1,2,3] while just range(4) would be the sequence [0,1,2,3]. (Note: ranges are a bit more complicated than that but this is close enough for now.)

The variable j is assigned using an assignment statement that uses the variable k on the right hand side. 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.

Another Way of Running Python Programs

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”. Cool!

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.

More on 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. In the program above, “range(1,4)” generates the sequence [1,2,3], which is what the loop runs over.

A while loop is simpler: it just has a loop expression that is checked before each repetition of the loop; the loop repeats as long as this expression is true, and then the loop exits when it becomes false.

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. In Python all control lines end with a colon.

The program below takes the example above 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)

Let’s break this code down one step at a time.

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 in the loop body 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.

More and More Operators

All programming languages have many built-in operators that allow data values to be used in computation, comparisons, and other operations. Operators are often represented as symbols, but sometimes are keywords.

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!

Python also has the logical operators and, or, and not, and an identity test called is. Logical operators allow you to combine comparisons. For example

if x < 7 and y == 10:

means “if the value of variable x is less than 7 and the value of variable y is equal to 10, then do whatever indented code follows”.

Python 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.

Probably need to put more in here, but stopping for now…

Python 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.