Python Basics

Numbers, Arithmetics

Two types of numbers exisit,

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


print 1.0/3

will give us float numbers, while

print 1/3

will only give us int.

Variables, Functions, Conditions

Variable name should start with either a letter or a 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


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
return False

Zen Code

  2. Try filter(), map(), reduce().