Skip to content

Introduction to Python

commenting

#single line comment

""" Multi-line comment If multiline comments are placed directly after a function or class signature, then these turn into docstrings.

Docstring is an in-built feature of Python, which is used to associate documentation that has been written with Python modules, functions, classes and methods. It is added right below the functions, modules, or classes to describe what they do. In Python, the docstring is then made available via the doc attribute. """

"ctrl" + "/" - comment and uncomment multiple lines of code

# example of single line comment
"""example of multi-line comment"""
def multiply(a, b):
    """Multiplies the value of a and b"""
    return a*b
     
     
# Print the docstring of multiply function
print(multiply.__doc__)

mathematical calculations


+ addition
- subtraction
* multiplication
/ division (e.g. 50/20 = 2.5)
// division without decimal point (e.g. 50//20 = 2)
% modulo - reminder of division (e.g. 50%20 = 10)
** exponentiation

print() - function needed to print the results in the shell

print(50+20)
print(50-20)
print(50*20)
print(50/20)
print(50//20)
print(50%20)
print(50**20)

strings and operations on strings

" " or ' ' - speech marks (e.g. "string", 'string')

operations on strings:
concatenation e.g. "string" + "pink" -> stringpink
multiplication e.g. "string" * 3 -> stringstringstring

\' - does not identify ' as a speech mark
e.g. don't -> "don't" or 'don\'t'

\n - breaks text into 2 lines

print("string" + "pink")
print("string" * 3)
print(str(10)+"5")

print('don\'t')
print('don\nt')

variables

INTEGER int - number without decimal points (e.g. 5)
FLOAT float - number with decimal points (e.g. 5.25)
STRING str - text (e.g. data)
BOOLEAN bool - True or False
LIST list - a list of values or other lists, a list is a compound data type, that means it can contain other variables within

type() - checks variable type

= assignes value to a variable

str() - function converting value into a string
int() - converting value into an integer
float() - converting value into a float
bool() - converting value into a boolean

integerr = 1
floatt = 1.2
stringg = "pink dog"
booleann = True

print(type(integerr))
print(type(floatt))
print(type(stringg))
print(type(booleann))

print(str(booleann))
print(int(floatt))
print(bool(floatt))

lists

[ , ] - list of values e.g. ["paulina", "buba", "rick"]
list within a list [[1, "paulina"], [2, "buba"], [3, "rick"]]

Python lists are zero indexing, meaning the first element has index 0
list_name[0] - selects the 1st element of the list_name

the last element has index -1
list_name[-1] - selects the last element of the list_name

slicing is selecting more elements of the list
list_name[first_element:last_element]

selecting an element of a sublist list_name[list_index][sublist_index]

changing elements in the list
list_name[index:index] = [new_element, new_element, ...]

adding elements to the list
list_name + [new_element, new_element, ...] or list_name.append([sublist, sublist]) to add a sublist

deleting elements from the list
del(list_name[index:inedx])

copying list
new_list = old_list - this will create a new reference to the same list, so changes to new_list will modify old_list
new_list = old_list[:] or new_list = list(old_list) - those will create duplicated lists

list_name = [[1, "mom"],
             [2, "Buba"],
             [3, "dad"]]

print(list_name[1])
print(list_name[-1])

# selects the 1st and 2nd element of the list, index 0 is included, index 2 is not included 
print(list_name[0:2])

# starts at index 0 (1st element) and finishes at index 1
print(list_name[:2])

# starts at index 1 (2nd element) and finishes with the last element of the list
print(list_name[1:])

# prints the whole list
print(list_name[:])

#prints the 1st element of sublist of the last element of the list
print(list_name[-1][0])

# changes 2nd element of first sublist
list_name[0][1] = "Paulina"
print(list_name)

# adding elements to the list
list_name.append([4, "Rick"])
print(list_name)

# deleting elements
del(list_name[2])
print(list_name)

# creating a copy reference to the list - changes to any of the list will occure in both
new_list = list_name
new_list[2][0] = 3
print(new_list); print(list_name)

# creating a copied list
different_list = list_name[:]
another_list = list(list_name)

del(different_list[0])
another_list[-1][:] = [3, "dad"]
print(list_name); print(different_list); print(another_list)

dictionaries

Dictionary items are ordered, changeable, and does not allow duplicates. Dictionary items are presented in key:value pairs, and can be referred to by using the key name. Duplicate values will overwrite existing values. The values in dictionary items can be of any data type. Keys need to be unique.

dict = {"key1": "value1", "key2": "value2"}
dict = dict(key1 = "value1", key2 = "value2")
dict['new_key'] = new_value - adds new pair to the dictionary
dict['key'] = new_value - updates the value
del(dict['key']) - delates the key-value pair

dict["key1"] - calling value1
.keys() - method checking key values of the dictionary
len(dict) - counting number of items in a dictionary
type(dict) - objects with the data type 'dict'

dictio = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

print(dictio["brand"])
print(dictio.keys())


x = dict(name="John", age=36, country="Norway")
print(x['name'])
x["height"] = 1.87
print(x)
del(x['age'])
print(x)

functions

piece or reusable code that solves a particular task

print() - prints the message to the shell
type() - to check a type of data
max() - to find the biggest number
round(number, precision) or round(number) - for the whole integer
help(function_name) or ?function_name - to get help on a function
len() - check a lenght of a variable
pow(base, power, modulo)

defining own functions
name - identifier by which the function is called
arguments - values passed to the function
function code - is executed everytime the function is called
return value - the value that is passed outside of the function to the porgram

def name(arguments) :
function code
return value

def hello(name = 'NAME') : #default argument when name is missing
    print("Hi " + name.capitalize() + ", nice to see you!")

hello("paulina")
hello(name = "lina")
hello()

def circle_area(radius) :
    area = 3.14 * (radius ** 2)
    return area

area = circle_area(2)
print(area)
      
def hours_in_days(days) :
    hours = days * 24
    return hours
      
print(hours_in_days(2))