Two types of numbers exist,
- float, 15 digits, other digits are float error
It is worth noting that in Python 2, we have
print(1.0/3) # will give us float numbers # 0.333333333333
print(1/3) # 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 print(num1) # num2 is a local variable def fun(): num1 = 2 num2 = num1 + 1 print(num2) fun()
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 print(num) fun1() print(num) fun2() print(num)
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 else: return False
Filter, Map, and List Comprehension
reduce(), and list comprehension:
link to code <https://repl.it/@emptymalei/Python-filter-map-reduce>_
In python you can access parent class properties easily.
class MyParentClass(object): def __init__(self): pass class SubClass(MyParentClass): def __init__(self): MyParentClass.__init__(self)
To access the sub class properties, we can use super function.
class MyParentClass(): def __init__(self): pass class SubClass(MyParentClass): def __init__(self): super()
Lei Ma (2018). 'The Python Language: Basics', Datumorphism, 03 April. Available at: https://datumorphism.leima.is/wiki/programming-languages/python/basics/.
Table of Contents