Python Functions

Something you can call to do a set of actions.

Defining functions

Functions

def my_function():
    do this
    do that
    do me
 
my_function()

Lambda

my_function = lambda a, b : a + b
print(func(3,4))
 
>> 7

Docstrings

def my_function():
""" This helps to do this and that """
# This helps other users, or yourself, to know what your function does.
# Use of 3 quotation marks.

Recursions

def calculator():
    Blah
    Blah
    calculator()
 
# Basically calling on the function again so that everything can restart

Functions within functions

You can’t take stuff (variables/lists) from outside the function. It will say it is not defined.

# BAD METHOD
def draw_player_card():
    player_hand.append(100)
 
player_hand = []
draw_player_card()
 
# What happens is when they read line 5, they go back up to the function
# When they come across player_hand, they have no fkin clue what it's referring to
# Because you didn't define it BEFORE the function defining.

Calling functions inside an if statement

def my_function():
    do this
    do that
    return 0
 
if my_function() == 0:
    # this calls the function to activate BTW

Functions with inputs

Parameters vs arguments

  • Argument"elkan" — the actual piece of information passed to the function when called (your input).
  • Parametername — the name of that data, used inside the function to refer to it.

Function with inputs

def addition(num1, num2):  # (2) replaces these parameters
    return num1 + num2     # (3) which are then used to perform certain actions
 
addition(1, 2)             # (1) the arguments or inputs here when you CALL the function
addition(num1=1, num2=2)

Same names for parameters & arguments

def my_function(a, b):
    a do this
    b do that
 
my_function(a, b)

Types of arguments

# positional arguments
def my_function(a, b, c):
    blah blah
 
my_function(10, 20, 30)
 
 
# default arguments
def my_function(a, b=20):
    blah blah
 
my_function(10)
my_function(10, 21)        # now b is overwritten by 21
 
 
# keyword arguments
def my_function(a, b, c):
    blah blah
 
my_function(10, c=30, b=20)
 
 
# arbitrary arguments
def average(*args):
    total = 0
    for score in args:
        total += score   # Sum up all the scores in sequence one at a time
 
    avg = total / len(args)
    print('The average score is', avg)
 
my_function(56, 60, 70)

Functions with outputs

def my_function():
    product = 3 * 2
    return product
 
output = my_function()  # which equals to product

When the function returns something, the function call is replaced by what you returned.

return ends the function

def my_function():
    product = 3 * 2
    return product
    print("Hello!")
 
print(my_function())
 
>> 6

Multiple returns

def format_name(f_name, l_name):
    if f_name == "" or l_name == "":
        return "You didn't provide valid inputs."
    formated_f_name = f_name.title()
    formated_l_name = l_name.title()
    return f"Result: {formated_f_name} {formated_l_name}"
 
# you don't need an "else:" — you can just go straight to "return" in the next line.

Ending the function

def my_function():
    do this
    do this
    return
 
# function just stops.

Extended return feature

if a_followers > b_followers:
    if guess == "a":
        return True
    else:
        return False
 
# an easier way to do this is
 
if a_followers > b_followers:
    return guess == "a"
 
# the computer evaluates if guess == "a", and returns True or False

Functions as inputs

Functions as inputs

def function_b():
    something
    something
 
def function_a(function_b):
    something
    something
 
# we ignore the parenthesis when using function_b as an input!

Generic function input

def add(n1, n2):
    return n1 + n2
 
def subtract(n1, n2):
    return n1 - n2
 
def calculate(n1, n2, function):
    return function(n1, n2)
 
calculate(4, 6, add)
>> 10

Others

Calling functions in functions

def func1():
    blah blah
    func2()
 
def func2():
    blah blah

Built-in functions

.title()

"john doe".title()
# John Doe

clear()

from replit import clear
clear()

ASCII art

logo = """
# whatever the art was
"""

print()

print("Hello world")
 
print("Hello world"\n"Second Hello world")
# prints in 2 different lines
 
print("Hello, I'm Elkan")
# use ' and " to switch
 
print("You\'re")
# use \ before quotation marks to ignore them
 
print(f"You are {name}")
# use F-strings to combine variables in strings.

input()

choice = input("What is your choice?")
# output is always a string!
 
choice = input("What is your choice?\n")
# input is prompted on the next line

len()

word = "hello"
len(word)   # gives 5
 
list = ["a", "b", "c"]
len(list)   # gives 3

type()

Checks the data type (str, int, float, etc).

int(), str(), float()
# to change data types

round()

round(the math, x)        # where x is number of decimal places
 
round(8/3, 2) = 2.67
round(45.50) = 46

.format()

"{:.xf}".format(variable)   # where x is the number of decimal places
 
"{:.2f}".format(46.785)     # gives 46.80

.lower()

Turns any string into all lower case.

"Hello".lower()
input("What is your name?").lower()

.count()

Counts number of letters in a string.

"Hello".count()

str.split()

str.split("split character")
 
to_be_split = "Chloe/Elkan/Tom"
to_be_split.split("/")    # gives ["Chloe", "Elkan", "Tom"]

min() / max()

min(list)
max(list)
# gives the min or max value in that list

sum()

sum(list)
# gives the sum of integers in that list

.replace()

str.replace(old, new, count)
 
string = "Hello! World!"
new_string = string.replace("!", "", 1)
 
# new_string = "Hello World!"

eval()

x = "print(55)"
eval(x)
# returns the integers in a string
 
>> 55

See next