The Python Language: Basics

Numbers, Arithmetics

Two types of numbers exist,

  1. int
  2. float, 15 digits, other digits are float error

It is worth noting that in Python 2, we have

# will give us float numbers
# 0.333333333333


# will only give us int
# 0

However, this was changed in Python 3.

Variables, Functions, Conditions

A variable name should start with either a letter or an underscore.

Variables defined inside a function is local and there is no way to find it or use it outside the function. It is even possible to reuse an already used global variable inside a function.

# num1 is a global variable

num1 = 1

# num2 is a local variable

def fun():
    num1 = 2
    num2 = num1 + 1


where the first line will give us 1 but the second output is 3. (Code from Coursera course interactivepython-005/lecture/15.)

If we want to use the global variable and change the value of it, the program can be like this,

num = 4

def fun1():
    global num
    num = 5

def fun2():
    global num
    num = 6

# note that num changes after each call with no obvious explanation

from Coursera course interactivepython-005/lecture/15.

Start a function by a comment says what the function does.

def triangle_area(base, height):     # header - ends in colon
    area = (1.0 / 2) * base * height # body - all of body is indented
    return area                      # body - return outputs value

from Coursera course interactivepython-005/lecture/8.

: indicates that a block code is following, which should be indented.

# will return True if a year is a leap year on Mars
def is_leap_year(year):
    if year % 3000 == 0:
        return False
    elif year % 1000 == 0:
        return True
    elif year % 100 == 0:
        return False
    elif (year % 2 == 0) and (year % 10 == 0):
        return True
        return False

Zen Code


Filter, Map, and List Comprehension

filter(), map(), reduce(), and list comprehension: link to code <>_

Super function

In python you can access parent class properties easily.

class MyParentClass(object):
    def __init__(self):

class SubClass(MyParentClass):
    def __init__(self):

To access the sub class properties, we can use super function.

class MyParentClass():
    def __init__(self):

class SubClass(MyParentClass):
    def __init__(self):

Planted: by ;

wiki/programming-languages/python/basics Links to:

L Ma (2018). 'The Python Language: Basics', Datumorphism, 03 April. Available at: