Python. Part 2. Functions & Packages
Function is a piece of reusable code, aimed at solving a particular task. Call Function instead of writing code yourself.
Function max shows in output the maximum number from the list 'fam' -> max(fam)
Assign a function to the variable: tallest = max(fam)
Function round():
round(1.68, 1) -> output 1.7
round(1.68) -> output 2
Get more info on function in Python: help(round) or ?round
Exercise 1
# Create variables var1 and var2
var1 = [1, 2, 3, 4]
var2 = True
# Print out type of var1
print(type(var1))
# Print out length of var1
print(len(var1))
# Convert var2 to an integer: out2
out2 = int(var2)
print(out2)
<script.py> output:
<class 'list'>
4
1
Functions with multiple arguments
Exercise 2
# Create lists first and second
first = [11.25, 18.0, 20.0]
second = [10.75, 9.50]
# Paste together first and second: full
full = first + second
# Sort full in descending order: full_sorted
full_sorted = sorted(full, reverse=True)
# Print out full_sorted
print (full_sorted)
<script.py> output:
[20.0, 18.0, 11.25, 10.75, 9.5]
Additional information: Sorting Techniques in Python
Methods
In Python, everything is an object.
- There are different functions in Python, like type, max and round.
- Methods are functions that are specific to Python objects.
- Depending on the type of an object (string, int, etc), methods behave differently.
Some methods can change the objects they are called on.
# string to experiment with: place place = "poolhouse" # Use upper() on place place_up = place.upper() # Print out place and place_up print(place) print(place_up) # Print out the number of o's in place place_count = place.count('o') print(place_count) <script.py> output: poolhouse POOLHOUSE 3
# Create list areas
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
# Print out the index of the element 20.0
print(areas.index(20.0))
# Print out how often 9.50 appears in areas
print(areas.count(9.5))
<script.py> output:
2
1
# Create list areas
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
# Use append twice to add poolhouse and garage size
areas.append(24.5)
areas.append(15.45)
# Print out areas
print(areas)
# Reverse the orders of the elements in areas
areas.reverse()
# Print out areas
print(areas)
<script.py> output:
[11.25, 18.0, 20.0, 10.75, 9.5, 24.5, 15.45]
[15.45, 24.5, 9.5, 10.75, 20.0, 18.0, 11.25]
Strings (str) public methodS
Case / letter changes
lower()– make lowercaseupper()– make uppercasecapitalize()– first char uppercase, rest lowercasetitle()– Title Case (each word)swapcase()– swap lower ↔ uppercasefold()– aggressive lowercase (best for comparisons)
Trimming / removing characters
strip([chars])– remove leading + trailing whitespace (or given chars)lstrip([chars])– remove from the leftrstrip([chars])– remove from the rightremoveprefix(prefix)– remove prefix if presentremovesuffix(suffix)– remove suffix if present
Searching / checking contents
find(sub[, start[, end]])– index or-1rfind(sub[, start[, end]])index(sub[, start[, end]])– similar tofindbut raises error if not foundrindex(sub[, start[, end]])count(sub[, start[, end]])– how many times substring occursstartswith(prefix[, start[, end]])endswith(suffix[, start[, end]])
Replacing / editing
replace(old, new[, count])translate(table)– replace via translation mapmaketrans(...)– helper to build translation tables (called asstr.maketrans(...))
Splitting / joining
split(sep=None, maxsplit=-1)rsplit(sep=None, maxsplit=-1)splitlines(keepends=False)– split by line breaksjoin(iterable)– join list/iterable into one string
Formatting
format(*args, **kwargs)format_map(mapping)zfill(width)– pad with leading zeros
Alignment / padding
center(width[, fillchar])ljust(width[, fillchar])rjust(width[, fillchar])
Character-type checks (return True/False)
isalpha()– letters onlyisalnum()– letters or digitsisdecimal()– decimal digits onlyisdigit()– digits (more broad than decimal)isnumeric()– numeric characters (broadest)isspace()– whitespace onlyislower()– all cased chars are lowercaseisupper()– all cased chars are uppercaseistitle()– title-casedisidentifier()– valid Python identifier?isprintable()– printable chars?isascii()– ASCII only?
Working with comparisons / sorting / partitions
partition(sep)– split into(before, sep, after)at first seprpartition(sep)– same, but last sepsplit()(already above) is often used for tokenizing
Encoding
encode(encoding='utf-8', errors='strict')
Integer public methods
as_integer_ratiobit_countbit_lengthconjugatedenominatorfrom_bytesimagnumeratorrealto_bytes
Float public methods
as_integer_ratioconjugatefromhexheximagis_integerreal