Functions and methods
Variables are fine on their own, but you can’t do much with them by themselves. Add them? Subtract them? That’s fine, but since we want more, we get more: introducing functions and methods!
# A function to get the number of characters in a string
len("butterscotch") # output: 12
# A function to sort a list
sorted([5, 4, 2, 3, 1]) # output: [1, 2, 3, 4, 5]
# A method to capitalize a string
"butterscotch".upper() # output: BUTTERSCOTCH
# A method to replace some text with some other text
"123123123".replace("12", "X") # output: X3X3X3
What’s the difference between functions and methods? Functions wrap around the outside of your variable/data, while methods are at the end of the variable/data. It’s a really stupid and useless difference, but it’s true.
I want to do something: how do I know if I need a function or a method? Google! Methods are more or less functions that are just typed differently. To a degree there’s no rhyme or reason as to which is which.
Remember! Don’t forget the
()
or your functions and methods won’t work.
Common functions
Functions and methods for numbers
# Round to X decimals
round(3.14159, 2)
# Round up and down
# We need to bring in some external libraries - code someone else wrote that isn't automatically included in Python
import math
math.ceil(3.14159)
math.floor(3.14159)
Functions and methods for strings
# Length of a string
len("yourstring")
# Replace content in a string
"yourstring".replace("your", "my")
# Change the case of a string
"Your String".upper()
"Your String".lower()
"Your String".title()
"Your String".swapcase()
# Count the number of something in a string
"Your String".count("r")
# Test if a string ends with something
"Your String".endswith("ng")
# Split into a list based on some character
"Your String".split(" ")
# Join a list into a string based on some character
" ".join(["Your", "String"])
# Reverse a string
"Your String".reverse()
Functions and methods for lists
# Length of a list
len([1, 2, 3, 4])
# Largest in a list
max([1, 2, 3, 4])
# Smallest in a list
min([1, 2, 3, 4])
# Sort a list
sorted([5, 4, 3, 2, 1])
# Add elements in a list together
sum([1, 2, 3, 4])
# Count the number of something in a list
[1, 4, 3, 2, 1].count(1)
# Join a list into a string based on some character
" ".join(["Your", "String"])
Functions and methods for dictionaries
data = { 'name': 'Smush', 'breed': 'cat', 'age': 7 }
# Get the keys from a dictionary
data.keys()
# Get the values from a dictionary
data.values()