Python Code – Basic Programming

Lists

packages = ['numpy','pandas','scipy']
for i in packages:
  print(i)
import pandas as pd
list_keys = ['a','b']
list_values = [['x','y'],[1,2]]
all = list(zip(list_keys, list_values))

> all
> [('a',['x','y']),('b',[1,2])]
[i for i in range(5) if i > 2]
> [3, 4]
[s.upper() for s in ['hallo','aarde']]
> ['HALLO','AARDE']

 

Dictionaries

d = { 'appel': 1, 'peer': 2, 'kokos': 3 }
d['banaan'] = 4

> d
> { 'appel': 1, 'peer': 2, 'kokos': 3, 'banaan': 4 }
d= {'een': 1, 'twee': 2, 'drie': 3, 'vier': 4} 
> d['twee']
> 2

 

Arrays numpy

import numpy as np
arr = np.array([1,2,3])

> type(arr)
> numpy.ndarray
import numpy as np
x = np.array([1, 2, 3, 4])
y = 3

> x == y
> array([False, False, True, False])
import numpy as np
arr = np.array([1, 2, 3, 4, 5])

> arr[arr >3] 
> [4, 5]

 

Iterators

w = 'python'
w_iterator = iter(w)

> next(w_iterator)
> 'p'

 

Lambda Function

f = lambda x, y: x * y

> f(3,3)
> 9

 

Functions

def add(a, b= 1):
  return a + b

> add(14)
> 15
def double_number(n):
  return n * 2 
double_number(4)
def subtract(n, p=1):
  return n - p

> subtract(4) 
> 3
def to_int(x):
  try:
    return int(x)
  except ValueError:
    print("No conversion possible")

> to_int("")
> No conversion possible
def f():
   """returns two"""
   return 2

> help(f)

Help on function f in module __main__:
f()
   returns two
from pytest import *
import numpy as np

def test_addition():
   assert 1 + 1 == 2

> show_test_output(test_addition)

====== test session starts ========
platform linux -- Python 3.6, ...
rootdir: /tmp/tmpxxxx
collected 1 item
test_file.py .

====== 1 passed in 0.01 seconds ==

 

Object Oriented Programming

class Snoep:
  smaak = 'zoet'
  def __init__(self, name):
    self.name = name

> c = Snoep('Chocolade')
> c.name
> 'Chocolade'
class hond:
  def woef(self):
    return 'woef'

> milou = hond()
> milou.woef()
> 'woef'