Functions structure in Python

Function is a dedicated block of code, which only runs when it is called.
It is also an essential element of the DRY (Don’t Repeat Yourself) methodology, i.e.
where a functionality will be used many times, we can use the function.
In Python a function is defined using the def keyword:

1 example – def simple ops

def adding(a,b):
    return a+b

print(adding(1,2))
print(adding(2,3))
print(adding(-1,2))
results
def add_numbers(a:int,b:float):
    return a+round(b,2)

print(add_numbers(1,2))  #3
print(add_numbers(3,4.8)) #7.8
print(add_numbers(9,0.33)) #9.33
print(add_numbers(2,math.pi)) #5.1419999999999995


def add_numbers(a:int,b:float):
    return round(a+b,3)
print(add_numbers(2,math.pi)) #5.142

2 example – if statement included

def expon_positiv (x,y):
    if x < 0:
     return '---'
    elif x > 0:
     return x**y

print(expon_positiv(0.1,2))
print(expon_positiv(2,2))
print(expon_positiv(-2,2))
print(expon_positiv(2,-2))
results
def even(a:int):
    if a % 2 == 0:
        return a
    else:
        return a-1

print(even(1))
print(even(2))
print(even(7))
print(even(8))
results

3 example – with global param

acum_base = 0
def accumulate(x):
    global acum_base
    acum_base +=x
    return acum_base

print(accumulate(3))
print(accumulate(2))
print(accumulate(7))

results

4 example – *args, *kwargs

*args collects any number of positional arguments and packs them into a tuple.
**kwargs collects named arguments (keyword arguments) into a dictionary (dict).

def function1(*args):
  return sum(args)
print(function1(1,4,5))

# *args + loop
def function1(*args):
  total = 0
  for i in args:
    total += i
  return total

print(function1(1,2,3))

results
#**kwargs
def function2(**names):
  print("My name is " + names["fname"])
  print("My last name is " + names["lname"])
  print("My full name: " + names["lname"], names["fname"])

function2(fname = "Agnieszka", lname = "Szczep")
result

5 example – def const value then change it

def function3(music = "Rock"):
  print("I love " + music + " music")

function3()
function3("Hip-hop")
function3("Trance")
result

7 example – math recursion model

def function4(k):
  if(k > 0):
    result = k + function4(k - 1)
    print(result)
  else:
    result = 0
  return result

print("Recursion Example Results")
function4(4)

8 example mutability revisited

numbers = [[0,1,2],[3,4,5],[6,7,8]]
def numbers_board(your_number = 0, row = 0, column = 0):
        print("   A  B  C")
        numbers[row][column] = your_number
        for count, row in enumerate(numbers):
                print(count,row)
print(numbers)
numbers_board(your_number=9, row=2, column=1)
print(numbers)

''' ouput1 numbers: 
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
output2 numbers_board:
   A  B  C
0 [0, 1, 2]
1 [3, 4, 5]
2 [6, 9, 8]
output3 numbers:
[[0, 1, 2], [3, 4, 5], [6, 9, 8]]'''
value = "set a number"
print(id(value)) #output: 1909035942960
def numbers():
        global value
        value = "0-9"
        print(id(value)) #output: 1909035390448
        print(value) #output: 0-9

numbers() 
print(value) #output: 0-9
print(id(value)) #output: 1909035390448

def numbers_board(numbers, your_number = 0, row = 0, column = 0, just_show = False):
        print("   A  B  C")
        if not just_show:
                numbers[row][column] = your_number
        for count, row in enumerate(numbers):
                print(count,row)
        return numbers

numbers_board(numbers, your_number=9, row=2, column=1)

Loops, Ranges and If statements

RANGE

is used to generate a sequence of numbers according to given parameters. Really seful in loops declarations, lists or sets of numbers.

nums1 = range(3)
print(nums1)
print(type(nums1))
if we only print range result will show us declared function not list of objects inside.
for x in range(3):
    print(x)

for x in range(1,4):
    print(x)
Range declarion begins with 0, if we want to start with 1 we might use type with stop and stop: range(start,stop) –> f.e. range(1,6)
nums2 = range(1,10,2)
for x in nums2:
    print(x)
nums3 = list(nums2)
print(nums3)
nums2 = list(range(10))
print(nums2)

IF STATEMENTS

Simple expressions

if expr1 < expr4:
    print("ok")

if expr1 % 2 == 0:
    print(expr1,"is disivible by 2")

if expr4 % 2 == 0:
    print(expr4,"is even")
else:
    print(expr4,"is odd")

Comparing conditions

if expr1 < int(expr3):
    print(expr3,"is greater than",expr1)
elif expr1 == int(expr3):
    print(expr3, "is equal", expr1)
else:
    print(expr3, "is smaller than", expr1)

One line statement

#one line statement
if expr4 > int(expr3): print(expr4,"is greater than",expr3)
print(expr4) if expr4 > expr1 else print(expr1)
Results

LOOPS

While Loop

# WHILE simple one
x = 0
while x < 4:
  print(x)
  x += 1
#output: 1 2 3 

# WHILE with BREAK
x = 0
while x >= 0:
  print(x)
  if x == 10:
    break
  x += 1 #output: 1 2 3 4 5 6 7 8 9 10

x = 0
while x >= 0:
  print(x+2)
  if x == 10:
    break
  x += 1 #output:  2 3 4 5 6 7 8 9 10 11 12

x = 0
while x >= 0:
  print(x)
  if x == 10:
    break
  x += 2 #output:  0 2  4  6  8  10 

# WHILE YIELD in range def as function 
#1)
def xRange(start, stop, step):
    i = start
    while i < stop:
        yield i
        i += step

for i in xRange(0.0, 0.3, 0.1):
    print(i) # output: 0.0 0.1 0.2

#2)
def xRange(start,stop, step):
    i = start
    while i < stop:
        yield i
        i += step + 2

for x in xRange (0,10,2):
    print(x) # output: 0 4 8

For Loop

#FOR simple one
words = ["Love", "Music", "Passion"]
for x in words:
  if x == "Love":
    continue
  print(x)
Resilt for loop with contine statement
#FOR in range with decimal example
from decimal import *
for i in xRange(0.0, 0.3, 0.1):
    print(Decimal(i))

#statements
print((0.1 + 0.2) == 0.3) 
print(round((0.1 + 0.2), 2) == round(0.3, 2)) 
print((Decimal(0.1) + Decimal(0.2)) == Decimal(0.3))
print((Decimal('0.1') + Decimal('0.2')) == Decimal('0.3'))

COMPREHENTIONS

# lists comprehensions
x = [i for i in range(5)]
print(x)
y = [i for i in range(10) if i % 2 == 0]
print(y)
# numbers as characters
numsA = ["8", "6", "4", "2", "0","-2"]
nums = [int(i) for i in numsA]
print(nums)

results
# with statement
L1 = [1,4,3,2,0,6,5,7,8,9
n = [i > 5  for i  in L1]
print(n)
#output: 
#[False, False, False, False, False, True, False, True, True, True]
# mix - error!
numsB = ["a", "6", "b", "2"]
nums = [int(i) for i in numsB]
print(nums)

We cannot mix values: numbers and letters
vec_of_vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
single = [num for elem in vec_of_vec for num in elem]
print(single)
# dict comprehensions - reverse the order
Dict1 = {1: "Green", 2: "Yellow", 3: "Orange"}
print({value: key for key, value in Dict1.items()})
# comprehensions in sets
List1 = [1, 1, 3, 3, 3, 5, 7, 5]
Set1 = {i for i in List1}
print(Set1)
results for dict, lists and sets