Python Zero to Heros

Online Absolute Beginner Python Tutorials 

Every Sunday 1pm (UK time/ BST)

Get this slide deck: bit.ly/PyFunction

Recap

Python objects - int, float, str, list, dict, bool

Control flows - if-else, for loop, while loop

 

Any Questions?

Functions

sometime we do the same thing with a different input

e.g. with a different basket print the checkout sum

checkout_sum = sum([catalog[item] for item in shop_list])
print(f"Thank you, the total is £{checkout_sum}")

Take some inputs, return an output

def some_func(parameter1, parameter2):
  # do something
  return result

Functions

Example: let's write the checkout program as a function

def checkout(shop_list, catalog):
	checkout_sum = sum([catalog[item] for item in shop_list])
	print(f"Thank you, the total is £{checkout_sum}")
    return checkout_sum
  
my_shop_list = ['toilet paper', 'banana']
shop_catalog = {'toilet paper': 10,
           'banana': 0.8,
           'coffee beans': 3}
to_pay = checkout(my_shop_list, shop_catalog)

Functions

Let's try to find out:

what if we skip the return?

what if we skip a parameter?

Defaults?

def checkout(shop_list, catalog):
	checkout_sum = sum([catalog[item] for item in shop_list])
	print(f"Thank you, the total is £{checkout_sum}")
    return checkout_sum
  
my_shop_list = ['toilet paper', 'banana']
shop_catalog = {'toilet paper': 10,
           'banana': 0.8,
           'coffee beans': 3}
to_pay = checkout(my_shop_list, shop_catalog)

Functions

Documentation by docstrings:

def checkout(shop_list, catalog):
      """This function calculate how much a customer need to pay.

    Parameters
    ==========
    shop_list, list
    catalog, dict

    Returs
    ======
    checkout_sum, float"""
	checkout_sum = sum([catalog[item] for item in shop_list])
	print(f"Thank you, the total is £{checkout_sum}")
    return checkout_sum
  
my_shop_list = ['toilet paper', 'banana']
shop_catalog = {'toilet paper': 10,
           'banana': 0.8,
           'coffee beans': 3}
to_pay = checkout(my_shop_list, shop_catalog)

Scopes

It's important to know what variable you are refering to.

 

Let's do a little experiment

y = 10

def my_func(x):
  print(f"inside func, before assign y: {y}")
  y = x
  print(f"inside func, after assign y: {y}")

print(f"before calling func y: {y}")
my_func(99)
print(f"after calling func y: {y}")

Args and Kwargs

Sometimes we are not sure how many parameters

For example:

def total(*args):
  return sum(args)

print(total(1,4,10))

Args and Kwargs

similar to args, but you can pass parameters in pairs

For example:

def create_catalog(**kwargs):
  result = {}
  for key, value in kwargs.items():
    result[key] = value
  return result

print(create_catalog("toilet paper"=10, "banana"=0.8, "coffee bean"=3))

Modules

Simply speaking a module is a file consisting of Python code

Standard modules e.g.: copy, random, math, os, path

Or add more by installing via pip

Or you can write your own

import other .py file into anothe .py file

Do it by: import / from _ import _  / import _ as

import copy
import pandas as pd
from random import randint

Let's write some programs using funcs

 

1. I randomly pick a fruit from the baskets, I put anything I got in my shopping bag except oranges. I really need some bananas, don't stop till I got one. (random_fruit.py)
 

2. Tom and Matt both have a shopping list, we want to combine them and remove the redundant items, then calculate how much they spend in total at the end. (combine_checkout.py)

 

https://github.com/Cheukting/python02hero/tree/master/2020-05-03-python-functions

Homework 📝

Can you using funciton on last weeks homework?

 

1. one_number_bingo.py: I can buy a ticket for £3 with one number assigned to me at random. It could be any number from  1 to 999. How much do I have to pay to win the game in one situation?

2.  one_number_bingo.py (bonus): do Monte Carlo similation to get the average money sepnd instead)

 

https://github.com/Cheukting/python02hero/tree/master/2020-05-03-python-functions

Next week:
Classes and Instances

Sunday 1pm (UK time/ BST)

There are also Mid Meet Py every Wednesday 1pm

Python Functions and Modules

By Cheuk Ting Ho

Python Functions and Modules

  • 983