Section 6: Methods and Functions

  Python Bootcamp 0 to Hero

Section 6 Menu

< Section 5
Section 7 >

    1. Methods and Python Documentation
    2. Functions in Python
    3. Overview of Quick Function Exercises #1 – 10
    4. *args and **kwargs in Python
    5. Function Practice Exercises – Overview
    6. Function Practice Exercises – Solutions
    7. Function Practice – Solutions Level One
    8. Function Practice – Solutions Level Two
    9. Function Practice Solutions – Challenge Problem
    10. Lambda Expressions, Map, and Filter Functions
    11. Nested Statements and Scope
    12. Functions and Methods – Homework Assignment
    13. Hints and Tips for Functions and Methods Assignment
    14. Functions and Methods Homework – Solutions

Methods and Python Documentations

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9442554?start=0#content

Methods: Functions built into objects

To find methods available for an object

* Jupyter Notebook specific
List all methods:

  • object.[Tab] *

Help on a method:

Functions

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9442630#content

Functions all you to reuse blocks of code without rewriting or copy/pasting it.

  • function name should be all lower case with snake_case
def function_name(name):
    '''
    DOCSTRING: Information about the function
    INPUT: name
    OUTPUT Hello name
    '''    
    # enter code here
    print("Hello "+ name)

Returning Values

Use the ‘return’ keyword to ‘pass back’ the result of the function.  This can then be assigned to a new variable

def add_function(num1, num2):
    return num1 + num2
result = add_function(1, 2)
print(result)

3

Defining default values to parameters

define the function

def say_hello(name):
    print("Hello "+name)

Call the function without parameters

say_hello()

TypeError: say_hello() missing 1 required positional argument: ‘name’

Redefine with a default parameter

 

def say_hello(name = "Sofia"):
    print("Hello "+name)

Call the function without parameters

say_hello()

Hello Sofia

Now pass another name

 

say_hello('Thomas')

Hello Thomas

Pig Latin Word Translator

 

def pig_latin(word):
    if word[0].lower() in 'aeiou':
        translate = word + 'ay'
    else:
        translate = word[1:] + word[0].lower() + 'ay'
    # Check capitalization
    if word[0] != word[0].lower():
        translate = translate[0].upper() + translate[1:]
    return translate
pig_latin('hello")

ellohay

pig_latin('Sofia")

Ofiasay

pig_latin('apple")

appleay

Overview of Quick Function Exercises #1 – 10

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9532168#content

Okay so you now know functions!

A big part of this section of the course will be testing your new skills with exercises. We have 3 main parts of exercises.

Part 1: 10 In Course Coding Exercises 

We’re going to start off with just the basics with a series of 10 problems. These problems should feel relatively easy, just some quick exercises to get you comfortable with the syntax of functions. If you feel uncomfortable with these, check out lecture 26 for some useful links for warm-up problems from codingbat.com , but hopefully these exercises should feel relatively easy.

These are in-course coding exercises. Solutions can be found linked here:

https://docs.google.com/document/d/181AMuP-V5VnSorl_q7p6BYd8mwXWBnsZY_sSPA8trfc/edit?usp=sharing

In between these in-course coding exercises we’ll have a quick lecture on *args and **kwargs.

Part 2: Function Practice Exercises

Here we’ll have a jupyter notebook with some exercises for you to answer, we’ll have a quick overview lecture, and then have you attempt problems, afterwards we’ll have an explanatory solutions video. These problems are ranked WarmUp, Level 1, Level 2, and Challenge. You should feel comfortable with Warmup and Level 1 and Level 2. Challenge problems here are very difficult, so don’t feel bad if you don’t want to attempt them yet! 🙂

After this we’ll cover a few more topics through some videos.

Part 3:  Function and Methods Homework

We finish off this section with even more exercises! Here we have various function word problems for you to solve, again in a notebook and we will cover the solutions in a video afterwards.

Best of luck! If you have any questions, post to the QA forums and we’ll be happy to help you out!

*args and **kwargs

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9442732#overview

*args

Arbitrary number of arguments as a tuple
Note: Recommended to use ‘args’ although could be some other variable name!

def myfunc(*args):
    return sum(args) *0.05
myfunc(1,2,3,4)

10

**kwargs

Arbitrary number of arguments as a dictionary

def myfunc(**kwargs):
    for x in kwargs.item():
        print(x)
myfunc(a='apple', b='banana')

(‘a’, ‘apple’)
(‘b’, ‘banana’)

Mixing *args and **kwargs

Note: The arguments / key word arguments must be entered in the order they are accepted in the function!
In this case, you must first enter the list of arguments, then keyword arguments.

def myfunc(*args, **kwargs):
    print(f"I would like {args[0]} {kwargs['fruit']}")
myfunc(4,5,6, animal='dog', cheese='cheddar', fruit='bananas')

I would like 4 bananas

Functions Practice Problems

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9442634#overview

Lambda Expressions, Map, and Filter Functions

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9442692#overview

map

Applies a function to a list

def first_letter(word):
    return word[0]
words = ['Hello', 'Goodbye', 'Farewell', 'So Long']
for l in map(first_letter,words):
    print(l)
letterlist=list(map(first_letter,words))
print(letterlist)

H
G
F
S
[‘H’, ‘G’, ‘F’, ‘S’]

filter

Similar to map, but function must only return a boolean

def starts_with_s(word):
    return word[0].lower()=='s'
words = ['Hello', 'Goodbye', 'Farewell', 'So Long']
for l in filter(starts_with_s,words):
    print(l)
letterlist=list(filter(starts_with_s,words))
print(letterlist)

lambda

lambda parameter : expression

Often used with Maps and Filters, lambda functions are functions you’ll only use once and do not wish to define

Instead of:

def first_letter(word):
    return word[0]

Use:

lambda word: word[0].lower()

Example with map and filter:

words = ['Hello', 'Goodbye', 'Farewell', 'So Long']
for l in map(lambda word: word[0], words):
    print(l)
letterlist=list(filter( lambda word: word[0].lower()=='s',words))
print(letterlist)

H
G
F
S
[‘So Long’]

Nested Statements and Scope

In the following example, what do you exect to print, 25 or 50

x = 25
def new_x():
    x = 50
    return 50
print(x)

25

L.E.G.B

This is the order Python will use to look for variable names

  • Local: names assigned in any way within a function (def or lambda) and not declared global in that function.
  • Enclosing function locals – Names in the local scope of any and all enclosing functions def or lambda) from inner to outer.
  • Global (module) – Names assigned at the top-level of a module file or declared global in a def within the file.
  • Built-In (Python) – Names preassigned in the built-in names module : open, range, SyntaxError, …

Local Example

name = 'global'
def hello():
   name = 'enclosed'
   def hi():
      name = 'local'
      print("Hello "+name)
   hi()
hello()

Hello local

Enclosed example:

Note: #name = ‘local’

name = 'global'
def hello():
   name = 'enclosed'
   def hi():
      #name = 'local'
      print("Hello "+name)
hi()
hello()

Hello enclosed

Global example:

Note: #name = ‘enclosed’

name = 'global'
def hello():
   #name = 'enclosed'
   def hi():
      #name = 'local'
      print("Hello "+name)
hi()
hello()

Hello global

global keyword example

name = 'Thomas'
def hello():
   global name
   print(f"global 'name' = '{name}'")
   name = 'Sofia'
   print(f"I just changed 'name' to: '{name}'")
hello()
print(name)

global ‘name’ = ‘Thomas’
I just changed ‘name’ to: ‘Sofia’
Sofia

Course 35% Complete

LEAVE A COMMENT