Getting Started
Welcome to this Introduction to Python course! I'm happy you've chosen to learn Python programming.
In this course, you will cover the basics of programming with Python. You'll learn about expressions, variables, conditionals, loops, lists, sets, dicts, functions, objects and exceptions.
By the end of the course, you will be able to:
- Store, retrieve and manipulate user-input data using Python
- Understand basic Python decisions, iteration, sequence containers, sets and dicts
- Read and write files using Python
- Define custom functions and call Python's built-in functions
- Import modules and namespaces from the Python Standard Library
- Define classes and instantiate objects using Python's class mechanism
- Handle exceptions and document code
- Build and debug entire programs written in Python
First, here's a little background information to introduce you to Python. A little history helps learners with a more philosophical and academic bent. Plus you'll have a better understanding of your programming tasks if you have a better idea about what makes Python tick.
The Python language was created by Guido van Rossum in the late 1980s. It was intended to be simple to use and easy to understand. The most interesting new feature of the language was its use of indentation to illustrate structure, similar to the way we use indentation in our everyday prose and written language.
Python was built to have a small "core," to keep it accessible, and a large library to make it versatile. Van Rossum was interested in networking. That interest prompted quick development of a useful set of network libraries for the language; many more libraries have been added since then.
Today, Python is used just about everywhere. Major users include YouTube, Google, Yahoo!, CERN, and NASA, and ITA—the company that produces the route search engine used by Orbitz, CheapTickets, c and international airlines. It's paticularly heavily used in data science and artificial intelligence applications.
Python is an interpreted language, which means Python code isn't translated into the binary instructions that computers actually run. Instead, bytecode is created, and the interpreter uses that bytecode to tell it what to do. Python is also a dynamic language. This means that aspects of your program which become fixed early on in some languages, remain available for you to change in Python, even while your program is running.
In this course, we'll be using a recent version of Python (3.14), but the features we use are all available in older versions that you may find other people using. Fortunately, the differences between versions are relatively minor. There aren't many changes you'll need to be aware of in order to work with older versions as well.
| Modern Python | This course was originally written for Python 3.1. It ran without modification on current Python 3.14 (the outputs in this lesson were regenerated on Python 3.14). Most of the language fundamentals taught here are exactly the same in all Python 3 versions, though the material has been brought up to date to teach you modern colloquial Python for currently-available versions. |
It is a tradition when learning a new language in computer programming to print the words "hello world" as a first example. Python can print "hello world" in a single line of code, so that doesn't make for the best example here. Instead, we'll look at a very slightly more complicated example that not only prints "hello" and "goodbye," but also does a little calculation along the way.
Usually you'll enter a Python program in your favorite text editor and then run it by typing a command in a command shell (that's the term for one of those special programs whose job in life is to display a prompt and then let you type in a command that executes when you press Enter). On a Unix or Linux type of system (that includes OS X), the shell is bash, or tcsh, or some other -sh, and the editor is vim or Emacs or one of many other possibilities. On Windows, the shell is the DOS window (what you get by running "cmd") and the editor is Notepad or Wordpad or vim or, again, any of many other possibilities. (You can also run programs on Windows by double-clicking their icons, but then the usual input and output streams are not available.)
Put this in a file called hello_world.py:
print("Hello World")
print("I have", 3 + 4, "bananas")
print("Goodbye, World")
Run it with python3 hello_world.py. You should see:
Hello World I have 7 bananas Goodbye, World
Congratulations! You're officially a Python programmer! Of course this program isn't very complex, but the interpreter has done the calculation you asked it to do. Pat yourself on the back! You're off to a strong start. Experiment with other calculations. As you might expect, the standard arithmetic operators +, -, * (for multliplication) and / are all available. Here are some of the other operations you can use in arithmetic expressions.
| Operator | Explanation | Examples | Results |
|---|---|---|---|
| ** | Exponentiation | 4 ** 3 2 ** 0.5 |
64 1.414215... |
| % | Modulo: remainder after division. The sign of the result is the same as that of the right-hand value |
23 % 5 50 % 7 50 % -7 |
3 1 -6 |
| // | Floor division: the largest integer less than or equal to the result of the division. |
23 // 5 50 // 7 50 // -7 |
4 7 -8 |
In Python, and on Python Anywhere, you can run the interpreter in interactive mode when you want to try things out and see results printed right away. That instant feedback is really handy when you're learning a new language. Learning need never stop in programming, tas here are always new techniques to learn and experiment with. It's fine just to do it for fun, or to achieve a specific goal, though.
The prompt >>> indicates that the interpreter is ready for your input.
If you enter one of the lines from the program you just ran, the output will appear. This interactive interpreter window allows you to enter both statements and expressions (we'll cover those in detail later). Statements are executed pretty much as if they were part of a program; the expressions are evaluated and the resulting value is printed (as long as you're in interactive mode).
Type the commands below in the interpreter window (Remember: when I suggest you TYPE the code, please do it. It's good for you, because it helps retention.). The interpreter prints a result for each expression. (You'll see a different prompt after the fourth line. We'll talk about that in a minute):
>>> "hello" + " world"
'hello world'
>>> 'hello' + ' world'
'hello world'
>>> """hello""" + ''' world'''
'hello world'
>>> """hello
... world"""
'hello\nworld'
>>>
[placeholder — replace with your own words] The +
operator joins the two string literals end to end. However you quote the
inputs, the interpreter echoes the result using single quotes — its
canonical way of displaying a string.
So, what happened here? The first three lines are all examples of string concatenation—a second string is appended to the first, giving a longer string as a result. The same two strings are use in all three examples, but represented in different ways. Strings can have either single (') or double (") quotation marks around them, and either one quotation mark or three at the beginning and end of the string. You must use exactly the same combination at both ends.
The final shows an important difference between the one-quotation mark and the three-quotation mark forms. A string given in one-quotation mark form should begin and end on the same line, unless the line is explicitly continued. Three-quotation mark strings can spread across more than one line, in which case the newline characters become part of the string.
The fourth example actually does extend across two lines, so the interpreter changed its prompt from >>> to ... (an ellipsis) after you entered the first line. The ellipsis lets you know that you've got an incomplete statement or expression, and the interpreter is waiting for you to finish it. When you completed the string with the second line of input, the interpreter then printed the value of the two-line expression, and returned the normal >>> prompt. You can see that the line feed between hello and world is represented by \n, which is known in Python as a string escape sequence.
In Python there are various types of data you can manipulate. The simplest are strings. There are also various numeric data types: integers, floats, and complex numbers. Let's see how to write those values in your programs.
We've seen that Python has several ways of representing strings. For regular strings, we use either of the one-quotation mark forms. Use three-quotation mark strings if, for example, the value you need to represent contains newlines, or contains quotation marks itself. The interpreter represents certain characters using escape sequences. You can put escape sequences into your strings to insert certain literal or non-printing characters. Here's a list of the most common sequences:
You can build a really long string using triple-quotation mark strings and escaping the newlines, or by placing several different strings one after the other in your source code. Usually you'll extend those types of statements across multiple lines using parentheses; the interpreter will assume a statement or expression is incomplete if it runs into the end of a line while there are still unmatched parentheses (or brackets, or braces, as we'll see later). Continue the interpreter session and try these commands:
>>> """One\
... Two\
... Three"""
'OneTwoThree'
>>> ("One" "Two" "Three")
'OneTwoThree'
>>> 'OneTwoThree'
'OneTwoThree'
The interpreter should print the same value back after you enter each of the three strings. The first string you entered spans three lines, but only printed out one.
In Python, numbers are represented as you might expect. Integers are strings of digits. The digits can be preceded by a minus sign (-) for negative numbers. There is no limit on integer values in Python, although the larger they get, the longer it takes you to do anything with them!
| Note | In Python, you cannot use commas to separate groups of digits like you sometimes do in text documents. You can, however, use the underscore character in its place to make reading easier. So 10_000_000 is a valid way to represent an integer literal of ten million. |
A floating-point number is made up of an integer followed by a decimal point and a fractional part. You may also use exponential notation if you like, by placing the letter E followed by an integer after the number, to indicate it should be multiplied by ten raised to the power of the integer.
Complex numbers generally consist of a real part and an imaginary part that's followed by a J; the real part is separated from the imaginary part by a plus or minus sign. The imaginary part followed by the J can comprise be either a floating point number or an integer. (For the mathematicians wondering why i wasn't used, this is standard engineering notation. The rest of us can just carry on.)
Let's try some of this stuff out. Try entering these numbers in the interactive interpreter:
>>> 1 1 >>> -1000 -1000 >>> 12.34 12.34 >>> 1.234E2 123.4 >>> 1+2j (1+2j) >>> 1j 1j
[placeholder — replace with your own words] The interpreter
evaluates the scientific-notation literal 1.234E2 and echoes
its plain decimal value. The literal and its value are the same number,
written two ways.
[placeholder — replace with your own words] Complex numbers are
built into the language: the j suffix marks the imaginary part,
and the REPL shows the value parenthesised to make the two components clear.
As you can see the interpreter doesn't always represent a value the same way you enter it. Further, the floating point numbers Python uses to represent non-integer values aren't always exact, even though the interpreter gets as close as possible. The errors are relatively small, but you need to be careful not to let them accumulate in long strings of calculations. (more on that later). If some of this isn't quite clear to you yet, don't worry. We're just getting started. We'll be talking about it all lots more and you'll have many chances to try things out and improve your understanding.
You've seen that you can concatenate strings using the + operator. There are many more operations you can perform on your numbers in Python:
| Escape Sequence | Is translated into |
| \" | Double quote |
| \' | Single quote (apostrophe) |
| \\ | Backslash |
| \r | Carriage return |
| \n | Line feed (newline) |
| \{newline} | Ignores the newline, allowing you to run a string across multiple program lines |
| \0nn | Character whose value in octal is nn |
| \xnn | Character whose value in hexadecimal is nn |
| Symbol | Operation |
| + | Addition |
| - | Subtraction |
| * | Multiplication |
| / | Division |
| ** | Exponentiation |
Put this in a file called calculations.py:
print("""--------------------
Some Calculations
--------------------""")
print(314159E-5)
print(10**6, 1j**2)
print(3 + 2 * 4, 1 / 3)
print("-" * 20)
print((3.14159 * 16) ** 2)
print(3.14159 * 16 ** 2)
print(20 * "-")
print("--------------------\nEnd of Calculations\n--------------------")
Run it with python3 calculations.py:
-------------------- Some Calculations -------------------- 3.14159 1000000 (-1+0j) 11 0.3333333333333333 -------------------- 2526.6144583935998 804.24704 -------------------- -------------------- End of Calculations --------------------
| Modern Python | The original course output showed 0.333333333333 for 1/3 and
2526.61445839 for (3.14159 * 16)**2. Python 3 now prints floats using
the shortest representation that round-trips back to the same value, so you will see more digits in some
cases. The values are correct either way. |
| Modern Python | Python 3 also supports f-strings as a concise alternative to multi-argument
print() calls. For example, print(f"I have {3 + 4} bananas")
does exactly the same job as print("I have", 3 + 4, "bananas") and scales more cleanly when
you have several values to interpolate. |
Take a minute to ponder. Think deeply and make sure you understand all of your results before going further. For example, you might wonder, why does 3 + 2 * 4 give 11, and not 20? Hmm... something to think about!
The answer is that Python interprets arithmetic expressions in the same way we are taught ot at school. (It's a long time since I was at school, I hope they do still teach this). First, it computes the values of any sub-expressions in parentheses. Next it does the multiplications and divisions, in the order they occur, and finally the additions and subtractions. If you're interested in the precise gory details you will find them here in the Python documentation.
That was quite a lot of introduction there. Thanks for sticking with it. In the next lesson!
