Learning

A Python and Jupyter primer.

Shortcuts:

  • Shift+Enter - run cell, select new cell (if no cell after, inserts)
  • more here
  • also quick shortcuts here:
    • S - saving the notebook

Example 1 : Hello World


In [1]:
language = 'Python'
name = input('Type your name here: ')
if name:
    helloStatement = 'Hello, ' + language + ' !' + ' Signed, ' + name
    print(helloStatement, '\n')
else:
    print('No name was typed')


Type your name here: Dan
Hello, Python ! Signed, Dan 

Obs: Since it's a Python 3 notebook, input() is raw_input() from Python 2.x (so it takes the raw data, it doesn't evaluate the content; so, you don't need to use double quotation on entering a value for the input). source


Python

Key points

  • being interpreted (high-level), Python is very flexible:
    • you don't need to declare the data types
  • identation is very important in Python - the enclosing of various instructions are made by identation (eg: for, if ...)
  • there are curently 2 types of Python: 2.7.x and 3.x - first is legacy, second is the future of Python

Data types

Reference:

Example 2: Data types examples


In [2]:
#Data types
truth = False
number = 3
floatnum = 3.14
message = 'sth'
#messageList = ['s','t','h'] #this is a list, not a string
#print('is messageList a str ? : ', isinstance(messageList, str)) #check with this
#print('is message a str ? : ', isinstance(message, str)) 
array = [2, 3, 4]

#print()

print('truth\t'   , type(truth))
print('number\t'  , type(number))
print('floatnum', type(floatnum))
print('message\t' , type(message))
print('array\t'   , type(array))


#Data structures
my_long_sentence = 'This is a very very very very long sentence'
parts = my_long_sentence.split(' ')

#print(parts)
print('parts\t', type(parts)) #, ',', len(parts)

set_parts = set(parts) #unique contraint
#print(set_parts)
print('set_parts ', type(set_parts)) #, ',', len(set_parts)

dictionary = {
    'word': 'definition'
}
print('dictionary', type(dictionary)) #also called maps


truth	 <class 'bool'>
number	 <class 'int'>
floatnum <class 'float'>
message	 <class 'str'>
array	 <class 'list'>
parts	 <class 'list'>
set_parts  <class 'set'>
dictionary <class 'dict'>

Example 3 : Operators


In [3]:
pi = 3.14

radiusCircle = 2 + 2*2
diameterCircle = 2 * radiusCircle
message = "Consider a radius of " + str(radiusCircle) #str() - equivalent to JS toString()

areaOfCircle = pi * (radiusCircle ^ 2)  #needs paranthesis
circumferenceCircle = pi * diameterCircle

print(message)
print('  Circumference of circle', circumferenceCircle)
print('  Area of circle', areaOfCircle)


Consider a radius of 6
  Circumference of circle 37.68
  Area of circle 12.56

Example 4: List

"A string is a list of characters"-like statement => array vs list in Python

official docs - here alternate docs (tutorialspoint) - here

Obs: By default, strings in lists are single-quotation, but if they contain a single-quote character, that specific element will be double-quoted.


In [4]:
#Lists
list1 = [False, 3.14, 25, "Hello"];
#print(type(list1))
#print(list1)

print(list1[0]) #first element
print(list1[-1]) #last element
print()

list1.append([2, 3, 4]) #add to the end of the list
list1.insert(0, True) # add to specific position of the list (doesn't replace the pre-existing element ...)
#list1.remove(True) #first matching value - O(n)
#del list1[0] #removes element - O(1)
#list1.pop(0) #remove and return - O(1)

#slicing list
slice1 = list1[0:4] #elements with index >= 0 && index < 4 => so 0, 1, 2, 3
print("slice1 = ", slice1)

slice2 = list1[:4] #slice2 === slice1 ; left limit is start of list
#print("slice2 = ", slice1)

slice3 = list1[4:] #elements with index >= 4 && index < len(list1) ; right limit is end of list
print("slice3 = ", slice3)


#for ... in iterator

print("list1 = [", end=" ")
for elem in list1:
    #if i == len(list1) - 1: #classical approach, with counter
    #if list1.index(elem) == len(list1) - 1: #similar, without counter
    #if elem == list1[len(list1)-1]:
    if elem == list1[-1]:
        print(elem, type(elem), end=" ")
    else:
        print(elem, type(elem), end=", ")
print("]", end=" ")


False
Hello

slice1 =  [True, False, 3.14, 25]
slice3 =  ['Hello', [2, 3, 4]]
list1 = [ True <class 'bool'>, False <class 'bool'>, 3.14 <class 'float'>, 25 <class 'int'>, Hello <class 'str'>, [2, 3, 4] <class 'list'> ] 

Example 5 : Dictionary

Data structure based on key-value (eg: "age" : "21")

Obs: When you try any operation on a key that doesn't exist, you get a "Key Error".

Obs: To access the last element in a dictionary - dictionary.keys()[-1] is ok in Python 2.7, but triggers an indexing error in Python 3.x:

  • workaround seems to be => sorted(dictionary.keys())[-1]

In [5]:
dictionary = {
    "age"  : 21,
    "name" : "Dan",
    10     : True
}
print(type(dictionary))
print(dictionary)

dictionary["language"] = "python" #insertion
#lookup / find value - find a value for that key
#del dictionary[10] #remove
#dictionary.pop(10)

#safe delete - if key doesn't exist, it won't trigger a Key Error
keyToDelete = 10
if keyToDelete in dictionary:
    dictionary.pop(keyToDelete)
    print("  Deleted key", keyToDelete)

print(dictionary)
print()


#special functions
print("No of tuples: ", len(dictionary.keys())) #no(keys)==no(values), so you can use dictionary.values() just as well
print(dictionary.keys()) #list of all the keys
print(dictionary.values()) # --//-- values

#iterate through dictionary
print("\ndictionary keys:", end=" ")
for key in sorted(dictionary.keys()):
    if key == sorted(dictionary.keys())[-1]:
        # you can always take a 
        #break
        print(key, end=" ")
    else:
        print(key, end=", ")


<class 'dict'>
{'age': 21, 10: True, 'name': 'Dan'}
  Deleted key 10
{'age': 21, 'language': 'python', 'name': 'Dan'}

No of tuples:  3
dict_keys(['age', 'language', 'name'])
dict_values([21, 'python', 'Dan'])

dictionary keys: age, language, name 

In [ ]: