1. Introduction to python programming
Learning outcomes
At the end of this lesson, you will be able to:
- Understand the difference between a compiled and interpreted programming language
- Know how too run a python code at online python servers such as Google Colab, Trinket.io and PythonAnywhere
- Understand the creation and utilisation of variables
- Understand the assignment operator, and how to set multiple variables simultaneously
- Understand the creation of numerical expressions and apply operator precedence
A bit about python
Python is quite a nice and easy language to learn and understand. In fact, it is one of the easiest languages to get you hit the road running. This is because you can virtually run your python code, or script, anywhere: on your laptop or even on your phone. This is thanks to the many online python servers that will allow you to run python code online.
Let me give you an example of how simple it is to run python code.
The print statement
Let's start with the simplest thing you can do in a program: to ask the computer to print out something, such as "Like coffee?"
How do we get the computer to print out this question on the screen? For that, we use the print statement. This statement orders the computer to print something to the screen. That something is called a string, which we will deal with shortly.
Let's write that code, which will be our first ever line of python code in this course:
print('Like coffee?')
Do you notice something in th above line? It looks different from normal text on this page. It is actually an executable line of code! This means that, when you press the play button to the left of the print statement, the program wil actually run! That's without needing to install any software on any computer. This is the power of using Google' Colab: it lets you execute python code on the fly.
So what just happened? We wrote a print statement, in which we called the print function. It is a function because it receives something, the "Like coffee?" text, and then performs some task with the text.
Let's try something else. Let's print two sentences:
print("Like coffee?",'"Yes, with milk please!"')
You notice what happened here? The print statement received two, not one, strings. They are separated by a comma. The print function then prints both sentences one after the other, leaving a space in between.
Now let's try to understand how do we write strings like "Like coffee?"
Strings
A string is any collection of characters, numbers, dots, symbols, or anything else you can access via the keyboard (or beyond!), enclosed between two quotes, or between two double quotes. So, for example, typing "a" is a valid string in python:
"a"
Result:
'a'
Here we just typed the string "a", and python only repeated the value of that string, which again is 'a'. Did you spot the difference?
A string in python is composed of three things: an opening quotation mark, a set of characters, and a closing quotation mark. Python accepts two types of quotation marks: single, and double. So we can also type 'a' up there, and we will get the same result.
The string is an example of a python data type: it is something that represents a value.
Python data types: strings, numbers and boolean values
Python has a number of data types that enable you to perform various types of operations on data. Here we discuss the fundamental three data types of python: strings, which we just discussed above, numbers and logical, or boolean values.
Numbers are just numbers! Type a number in the python interpreter, say 5, and you will just get 5 back.
5
Result:
5
Well you can actually do arithmatic right there, in the python interpreter.
5+6-8*3
Result:
-13
Here I just did a complex arithmetic operation using integers, and python gave me the result of the operations. What I typed up here is called, in programming terminology, an expression: an operation on values that yield a value. Here the value we got is -13, which is the value of the expression.
Numbers in python include all sorts of numbers that can be represented by the computer: integers, decimal numbers with a few decimal places, and also decimals with a very large number of decimal places, and very large numbers. Python sees all of these numbers as one data type, the numeric data type.
For strings, when you typed "a" in the python interpreter, that also was an expression, a string expression. A string can be empty, like "", or can have as many characters as you want.
Another important data type is the boolean data type. This one has only two possible values: True and False. Let's try that.
True
Result:
True
Those two data values represent the two possible outcomes of a yes/no question, such as: is that ball blue? Soon, we will find out that such type of questions is very common in programming.
Variables
A variable in python, as well as in programming language, enables you to store a value in memory. Let us create a variable that will store the string value "I love coffee" in memory.
s = "I love coffee"
We have just created a variable that has two important features: a name, which is s, and a value stored inside it, which is "I love coffee". This memory storage was performed via the = sign. The entire line, s = "I love coffee" is called an assignment statement, and the = is called the assignment operator.
So that was our first operator here, the =. This operator is unique in that it is different from the arithmetic operators we know, such as the + and -, because = does not give you an expresssion. It is rather a statement. A statement orders the computer to perform a task, such as the print statement, while an expression is only meant to return a value.
Remark: Note the difference between expressions and statements.
Multiline strings
What if you would like to store a multiline string in a variable in python? The way to do it is by enclosing your strings between three double quotes, or three single quotes. Here is an example.
a="""Yesterday I ordered coffee from that shop at Flinders. Their coffee really sucks but I loved the little marshmallow that they put next to the cup. And it's kind of cheap too.""" print(a)
Result:
Yesterday I ordered coffee from that shop at Flinders. Their coffee really sucks but I loved the little marshmallow that they put next to the cup. And it's kind of cheap too.
Console input
You can let python collect data from use via the input() function:
a = input()
print(a)
Result:
i can enter stuff here
i can enter stuff here
Arithmetic operations: +, -, *, /, %, //
Back to operators. You can work with the standard maths operators in python, which are +, -, *, / and %. The first four are obvious, but % might need an introduction. The // operator is related to the /: it lets you get the quotient of the division, and therefore it is called the floor operator //. That is, it just removes the decimal part of the division result. For example, 9//4=2.
% is the modulus operator. It is related to the // operator in that: while a//b gives you the integer quotient, % gives the remainder. For example, in the division 9/4=2+1/4, the quotient is 2 and the remainder is 1. Then in python, 9%4=1.
Comparison operations: ==, !=, <,>, <=,>=
Now that we know how to use operators on numbers to create numbers, the above operators create boolean values. This is because they ask questions about the variables they operate on.
- a == b means: is a exactly equal to b?
- a != b means: is a not equal to b?
- a < b means: is a less than b?
- a > b means: is a greater than b?
- a <= b means: is a less than or equal to b?
- a >= b means: is a greater than or equal to b?
Let's evaluate an expression baesd on these operators:
#This code demonstrates operations
a = 3
b = 5
c = a == b
print(c)
d = a > b
print(d)
e = a <= b
print(e)
Result:
True
False
True
Operator precedence and brackets
Remember BODMAS from high school? It stands for: Bracket, Of, Division, Multiplication, Addition and Subtraction. It also applies in python the same way it applied in your math lessons.
Operations on strings
You know you can add strings? Let's say you have two strings 'Hi' and 'there'. Those separate strings can be concatenated together, or added together, to form a larger string: 'Hi'+'there' which gives 'Hithere'. But we need a space here between the two words, so we'd rather add a space character ' ' between them: 'Hi'+' '+'there' which gives 'Hi there'.
Comments
In python, you can add text to your code that the interpreter will ignore. But you have to follow a special syntax to make sure the the text will be ignored. The syntax is: use # before the text, and every thing after it will be ignored by the interpreter.
Let's try that out:
#This text will be ignored. You can use comments to "document" your code
# This is formatted as code
More on data types, and getting and setting a data type
In python, there are three numerical data types, not just one: int, float, and complex. The int is an integer, which are the whole numbers, both positive and negative. Examples: 7, 1023, -2982, etc. A float is a positive or a negative decimal number, such as 4.2, -50.298. Let's worry about complex later in this course.
Retrieving the data type of a variable
If you have some variable, python lets you find out its data type using the function type().
b=45
print(type(b))
Result:
<class 'int'>
Here, class 'int' tells you that b is an integer.
Setting the data type of a variable
In python, you set the data type of a variable by one of two methods:
- By assigning a value to it
- By using a data type constructor function
So when you type a=4, you have set the data type of variable a to an int data type.
Remark: The freedom of setting a variable type in python makes it fundamentally different from other languages such as Java, C and C#. These languages apply strong typing on their variables, which means that you must specify the type of a variable on creation, and cannot change the type of the variable later in the code.
To set the data type using a constructor function, there is a constructor function for each data type that we can choose from. They are:
- For integers: int()
- For floats: float()
- For strings: str()
Before we use a constructor function, we need to think about the purpose of using it to change the data type of a variable. If you have a float, why would you want to turn it into an integer? A simple reason: to get rid of the decimal part!
a = 54.67
b = int(a)
print(b)
Result:
54
Setting multiple variables
In python, you can set values into several variables in the same statement. For example, to set the value of a to 1 and b to 2, we do the following:
a,b=1,2
Python statement termination
In python, as you have noticed already, a statement starts at the start of the line and ends with a new line. So you cannot put two statements in the same line. e.g. typing the following will give you an error: a=3 print(a).
There is another way you can terminate a statement: by using the semicolon, ;, just like in Java, C, C# and other languages. Although it is optional, will need to use it if you want to put two statements on the same line e.g. a=3;print(a).
