Resources for Python

by Fredrik Daneby

Useful links

Python.org[ https://www.python.org ]

Snippets

Basics

Data types

#!bin/python3

my_int      = 1
my_float    = 1.25
my_string   = "Hello"
my_bool     = True

print(f"my_int is {my_int} and of type {type(my_int)}")
print(f"my_float is {my_float} and of type {type(my_float)}")
print(f"my_string is {my_string} and of type {type(my_string)}")
print(f"my_bool is {my_bool} and of type {type(my_bool)}")

my_tuple    = tuple(("A", "B", "C"))        
my_list     = list(["D", "E", "F"])         
my_set      = set({"G", "H", "I"})          
my_dict     = dict({"J":1, "K":2, "L":3})   

print(f"my_tuple is {my_tuple} and of type {type(my_tuple)}")
print(f"my_list is {my_list} and of type {type(my_list)}")
print(f"my_set is {my_set} and of type {type(my_set)}")
print(f"my_dict is {my_dict} and of type {type(my_dict)}")
			

Scope

#!bin/python

## Indentation is used instead of brackets to define a block of code
def function_alpha():
    variable_alpha = 10 


## Scope is by default local to a block

a_string = "aaaa"

# Trying to change a_string in a function	
def string_changer():
    a_string = "bbbb"
    
string_changer()
print(f"string_changer did not change the global string. a_string is {a_string}")


## Keyword "global" can be used to change the global variable
def string_changer2():
    global a_string
    a_string = "cccc"

string_changer2()
print(f"string_changer2 did change the global string. a_string is {a_string}")


## In nested functions, using the keyword "nonlocal" changes outer function 
## variable
def my_function():
    letters = "abcdef"

    def my_inner_function():
        nonlocal letters
        letters = "ghijklm"
    
    my_inner_function()
    return letters

my_function()
letters = my_function()
print(f"my_inner_function changed the letters to {letters}")

			

Loops and iterables

#!bin/python

# Simple for-loop
print(f"For-loop: ")
for i in range(0,10):
    print(f"{i}", end=' ')
print()

# Simple while-loop
print(f"While-loop:")
while(i > 0):
    print(f"{i}", end=' ')
    i -= 1

# Iterators are used for iterating all iterables.

values = [10, 20, 30, 40, 50]
iterator_values = iter(values)
print(f"\nFirst iterator ({type(iterator_values)}) value: {next(iterator_values)}")
print(f"Second iterator ({type(iterator_values)}) value: {next(iterator_values)}")

print("\nAll values: ")
for v in values:
    print(f"Values value: {v}")
			

Functions

#!bin/python

## A function is defined when it is declared
def a_function():
    print("A function was called")

# A function is called
a_function()

# Another function is defined, accepting two parameters/arguments
def another_function(a_string, a_second_string):
    print(a_string)
    print(a_second_string)

# Call another_function with two parameters
print("Calling another_function...")
another_function("string 1", "string 2")


## Call a function with a list (or any other class/type)
numbers = [1,2,3,4]
def a_list_function(a_list):
    print("a_list_function got: ")
    for n in a_list:
        print(n)
		
a_list_function(numbers)            # A named list
a_list_function([5,6,7,8])          # An anonymous list


## Immutable classes/types are passed by value, otherwise by reference

# Function to add 1 to int (immutable = not changeable)
def add(n): 
    n += 1
    print(f"Number inside is {n}")

number = 1
add(number)
print(f"Number outside is {number}")

# Function to add an element to list (mutable) of ints
def add_to_list(n_list):
    print(f"List in function before append is: {n_list} ")
    n_list.append(10)
    print(f"List in function after append is: {n_list} ")

list_of_numbers = [1,2,3,4]
add_to_list(list_of_numbers)
print(f"List outside of function after call is: {list_of_numbers}")
		

Lambdas

#!bin/python

add = lambda number : number + 10
print( add(5) )


add_two = lambda number1, number2 : number1 + number2
print( add_two(10, 20) )

File I/O

Reading and writing to files

#!bin/python
import os                           # For safe filepath operations

## An output file will be created in the current working directory

output_folder   = os.getcwd()       
output_filename = "python_output.txt"
output_file     = os.path.join(output_folder, output_filename)

## Write output to file. Overwrite file if it exists

string_to_write = "I am a string, written to a file.\n" # note line feed (\n)

with open(output_file, "w") as file_handle:
    file_handle.write(string_to_write)
    file_handle.close()


## Write output to file. Append to file

string_to_append = "I am a string, appended to an existing file."

with open(output_file, "a") as file_handle:
    file_handle.write(string_to_append)         
    file_handle.close()


## Read the file line per line

with open(output_file, "r") as file_handle:
    file_lines = file_handle.readlines()        
    file_handle.close()

# Print read data, line by line
for line in file_lines:
    print(f"Line = {line}", end='') 
print()                           


## Read the whole file at once

with open(output_file, "r") as file_handle:
    file_data = file_handle.read()              
    file_handle.close()

# Print read data, whole file
print(f"File content: \n{file_data}")

## Read whole file at once in binary mode
    with open( input_file, 'rb' ) as file_handle:
        file_data = file_handle.read()
        file_handle.close()

String operations

String length

#!bin/python

a_string = "ABCD"
a_string_length = len(a_string)
print(f"a_string length is {a_string_length}

String concatenation

#!bin/python

# + operator can be used on strings
firstname = "Harald"
lastname = "Blåtand"
fullname = firstname + ' ' + lastname

print(f"Firstname: {firstname}, lastname: {lastname}, full name: {fullname}")

# Another way (f-strings), similar to the print statement above
color = "blue"
animal = "cat"
pet = f"A {color} {animal}"
print(pet)

# A third way (format %)
car = "Volvo"
type = "sedan"
vehicle = '%s %s' % (car, type)
print(vehicle)

Searching in strings

#!bin/python

# find() character. Returns -1 if character/string is not found
characters = "ABCDEF"
C_position = characters.find("C")
print(f"C is found at index {C_position}")
print(f"The character at index {C_position} is {characters[C_position]}")

# find() string
ABC_position = characters.find("ABC")
print(f"ABC is found at index {ABC_position}")

Counting occurences of a character in a string

#bin/python

# Count occurences of a character in a string
binary_string = "101100001111"
nr_of_zeros = binary_string.count("0")
print(f"Found {nr_of_zeros} \"0\" in string")

Replace character/string in a string

#bin/python

# Replace occurences of a character/string in a string
words = "A cat went to school"
correct_words = words.replace("cat", "person")
print(correct_words)

# Removes first and last occurences of a set of characters in a string
statement = "  -This is not a good way and not the method to use "
print(f"[{statement}]")
reverse_statement = statement.strip(" -")
print(f"[{reverse_statement}]")

Split a string and join a list to string

#bin/python

# Split a string into a list
csv_data = "field_1;field_2;field3"
fields = csv_data.split(";", 3)
print(fields)

# Join a list into a string
tsv_data = "\t".join(fields)
print(tsv_data)

List operations

Adding and removing elements of a list

#!bin/python

# append()
list_of_numbers = [1,2,3,4,5,6,7,8,9]
print(f"List before append: {list_of_numbers}")
list_of_numbers.append(10)
print(f"List after append: {list_of_numbers}")

# insert()
list_of_numbers.insert(0, 0)
print(f"List after insert: {list_of_numbers}")

# pop() 
list_of_numbers.pop(4)
print(f"List after pop: {list_of_numbers}")

# remove()
list_of_numbers.remove(5)
print(f"List after remove: {list_of_numbers}")

Sorting a list

# sort()
list_of_numbers.insert(0, 11)
print(f"List after insert(11,0): {list_of_numbers}")
list_of_numbers.sort()
print(f"List after sort: {list_of_numbers}")

# reverse sort()
list_of_numbers.sort(reverse=True)
print(f"List after reverse sort: {list_of_numbers}")

# sorting criteria
list_of_animals = ["Aardvark", "Zebra", "Cod"]
list_of_animals.sort(key=len)
print(f"List after length sort: {list_of_animals}")

Slicing a list

#bin/python

# Return a slice object from list
letters = ["A", "B", "C", "D"]
print(letters[slice(1, 3)])
print(letters[slice(2, 4)])

# Slice using the slice operator [:]
slice_of_letters = letters[2:4]
print(slice_of_letters)

Dictionary operations

#!bin/python

# Create a dictionary
legs = {"spider":8, "human":2, "cat":4, "dog":4}
print(legs)

legs_keys   = legs.keys()
legs_values = legs.values()

print(f"Keys is of type {type(legs_keys)} and is printed as {legs_keys}")
print(f"Values is of type {type(legs_values)} and is prited as {legs_values}")

# Iterate keys
print(f"\nString values of keys and values:")
for key in legs_keys:
    print(f"{key}={legs[key]}")

# dict_keys and dict_values class can explicitly be cast to list
legs_keys_list      = list(legs_keys)
legs_values_list    = list(legs_values)

# Remove dog from dictionary (by key)
legs.pop("dog")
print(f"legs after pop: ")
for key in legs_keys:
    print(f"{key}={legs[key]}")

# Remove cat from dictionary
del legs["cat"]
print(f"legs after del: ")
for key in legs_keys:
    print(f"{key}={legs[key]}")

# Add ant
legs["ant"] = 6
for key in legs_keys:
    print(f"{key}={legs[key]}")

Classes

A simple class

#!bin/python

class animal:
    def __init__(self, name, color, weight):
        self.name = name 
        self.color =  color
        self.weight = weight

    def __str__(self):
        return f"a {self.color} {self.name} of {self.weight} kg"
    
    def set_color(self, new_color):
        self.color = new_color

def main():

    my_animal = animal("cat", "blue", 25)
    print(my_animal)
    
    my_animal.set_color("red")
    print(my_animal)

main()