Estimated time: 10 minutes

Python: the basics


Python is a general purpose programming language that supports rapid development of scripts and applications.

Why Python?

  • Open Source software, supported by Python Software Foundation
  • Available on all major platforms (ie. Windows, Linux and MacOS)
  • It is a general-purpose programming language, designed for readability
  • Supports multiple programming paradigms ('functional', 'object oriented')
  • Very large community with a rich ecosystem of third-party packages

How to get started?

Using interpreter or interactive notebook, like this one. (We will not cover on how to install in your local machine)


Let's get started!

To learn a new language, is to start with printing out random string! In Python, we just call print("some strings"). Note that in Python, we can use "" or '' to represent a string.

print('Hi! I am hongvin')
Hi! I am hongvin
message = 'Hi! I am hongvin'
print(message)
Hi! I am hongvin

Variables and data types


Integers, floats, strings

Let's see some example straight away!

a = 10
b = 5.5
c = "hi"
a,b,c
(10, 5.5, 'hi')
type(a),type(b),type(c)
(int, float, str)

Operators


We can perform mathematical calculations in Python using the basic operators:

Symbol Operation
+ Addition
- Minus
* Multiplication
/ Division
% Modulus
** Power
2+2
4
6*7
42
6**7
279936
6%3
0

Boolean operations


We can also use comparison and logic operators: <, >, ==, !=, <=, >= and statements of identity such as and, or, not. The data type returned by this is called a boolean.

3 > 5
False
True and False
False

Lists and sequence types


myList = [1, 2, 3, 4, 5]
myList
[1, 2, 3, 4, 5]

Get the length of the list thru len()

len(myList)
5

Lists can contain multiple data types, including other lists

complexList = [1, 3.0, "hi", [1, 4, 5, "gg"], "MESA", myList]
complexList
[1, 3.0, 'hi', [1, 4, 5, 'gg'], 'MESA', [1, 2, 3, 4, 5]]

But how to get the element in the list? Remember that Python is 0-indexed, therefore the first element is indexed as 0.

complexList[0]
1
complexList[4]
'MESA'

How to add to the list? You can append items to the end of the list with append(). You can also add multiple items to the end of a list with extend().

myList.append(6)
myList.extend([7,8,9])
myList
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Loops


A for loop can be used to access the elements in a list or other Python data structure one at a time.

for num in myList:
    print(num)
1
2
3
4
5
6
7
8
9

Indentation is very important in Python. Note that the second line in the example above is indented, indicating the code that is the body of the loop.