Skip to main content

Command Palette

Search for a command to run...

Python. Part 2. Functions & Packages

Published
4 min read

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

Built-in functions in Python

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 lowercase

  • upper() – make uppercase

  • capitalize() – first char uppercase, rest lowercase

  • title() – Title Case (each word)

  • swapcase() – swap lower ↔ upper

  • casefold() – aggressive lowercase (best for comparisons)

Trimming / removing characters

  • strip([chars]) – remove leading + trailing whitespace (or given chars)

  • lstrip([chars]) – remove from the left

  • rstrip([chars]) – remove from the right

  • removeprefix(prefix) – remove prefix if present

  • removesuffix(suffix) – remove suffix if present

Searching / checking contents

  • find(sub[, start[, end]]) – index or -1

  • rfind(sub[, start[, end]])

  • index(sub[, start[, end]]) – similar to find but raises error if not found

  • rindex(sub[, start[, end]])

  • count(sub[, start[, end]]) – how many times substring occurs

  • startswith(prefix[, start[, end]])

  • endswith(suffix[, start[, end]])

Replacing / editing

  • replace(old, new[, count])

  • translate(table) – replace via translation map

  • maketrans(...) – helper to build translation tables (called as str.maketrans(...))

Splitting / joining

  • split(sep=None, maxsplit=-1)

  • rsplit(sep=None, maxsplit=-1)

  • splitlines(keepends=False) – split by line breaks

  • join(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 only

  • isalnum() – letters or digits

  • isdecimal() – decimal digits only

  • isdigit() – digits (more broad than decimal)

  • isnumeric() – numeric characters (broadest)

  • isspace() – whitespace only

  • islower() – all cased chars are lowercase

  • isupper() – all cased chars are uppercase

  • istitle() – title-cased

  • isidentifier() – valid Python identifier?

  • isprintable() – printable chars?

  • isascii() – ASCII only?

Working with comparisons / sorting / partitions

  • partition(sep) – split into (before, sep, after) at first sep

  • rpartition(sep) – same, but last sep

  • split() (already above) is often used for tokenizing

Encoding

  • encode(encoding='utf-8', errors='strict')

Integer public methods

  • as_integer_ratio

  • bit_count

  • bit_length

  • conjugate

  • denominator

  • from_bytes

  • imag

  • numerator

  • real

  • to_bytes

Float public methods

  • as_integer_ratio

  • conjugate

  • fromhex

  • hex

  • imag

  • is_integer

  • real