Skip to main content

Notes on python

I'm using the University of Helsinki MOOC to learn python. I have a lot of experience in R and just need to learn the syntax and major function differences.

https://programming-24.mooc.fi

Note: the main block of a Python program must always be at the leftmost edge of the file, without indentation:

Variables, you can have 2 variables reference the same object and both will update. So if you say a = [1,2,3] and b = a, then update the list of a[0] = 2, then both variables will be updated. but if you say a = [1,2,3] then b = [1,2,3]

+= : this is an assignment and addition operator. So you could write sum += sum, which would add sum to itself and save it. They have this operator for other mathematical functions, such is *=

This is how if statements work. Need colon at end and white space, I don't think the amount of whitespace matters but 4 is the standard

if name == "Anna":
	print("Hi!")
elif: this is the else if implementation in python.
if n1 > n2 and n1 > n3 and n1 > n4:
    greatest = n1
elif n2 > n3 and n2 > n4:
    greatest = n2
elif n3 > n4:
    greatest = n3
else:
    greatest = n4
nested ifs with indentation
number = int(input("Please type in a number: "))

if number > 0:
    if number % 2 == 0:
        print("The number is even")
    else:
        print("The number is odd")
else:
    print("The number is negative or zero")
while loop with True. Going to add one with condition.
attempts = 0

while True:
    code = input("Please type in your PIN: ")
    attempts += 1

    if code == "1234":
        success = True
        break

    if attempts == 3:
        success = False
        break

    # this is printed if the code was incorrect AND there have been less than three attempts
    print("Incorrect...try again")

if success:
    print("Correct PIN entered!")
else:
    print("Too many attempts...")
While loop with condition
number = int(input("Please type in a number: "))

while number < 10:
    print(number)
    number += 1

print("Execution finished.")
if you start an infinite loop, you can break out of it with ctrl+c
This is the printf function, allows you to insert variables in the curly braces without added white space. the print function automatically puts a white space in between.
print(f"{x} divided by {y} is {result}")
Operator Purpose
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
** exponent
instead of symbols, you have AND, OR, and NOT
You need to import the fuckin square root function
from math import sqrt
For booleans, it is True and False, you cannot use all caps or just the first letter.
asdfas
From helsinki

Instead of  x >= a and x <= b you can write a <= x <= b to see if a number falls between 2 numbers.

 

String Manipulation

Pasting

words = words + " and python"

words += " and python"

print("word"*3)

Length Function: len() 

Seems like a string works like a vector so "string"[3] will return the letter i. Indexes at 0.

You can think of input_string[-1] as shorthand for input_string[len(input_string) - 1].

In Python string processing the interval [a:b] is half open, which in this case means that the character at the beginning index a is included in the interval, but the character at the end index b is left out.

so "string"[0:2] will just print out "st"

"es" in input_string where the in functions shows if the substring exists inside the input_string variable.

find shows the first index where a string is found.

methods vs functions? didn't make sense to me.

Using the "." operator seems like its called method chaining. Its like the R pipe operator. They don't explain it in the mooc yet.

"continue" command goes to the beginning of the loop

Strings are immutable. So you have to overwrite the entire string, you can't just assign a new letter to the 3rd index.

String method split()

Functions

defined with def

def hello(target):
    print("Hello", target)

you need to use the return function to get a value out of a function. 

You can add "hints" for both the inputs and the return value

def print_many_times(message : str, times : int):
    while times > 0:
        print(message)
        times -= 1
def ask_for_name() -> str:
    name = input("Mikä on nimesi? ")
    return name

 

Lists

lists are like matlab arrays more so than r arrays. Must be homogenous data.

my_list = [1,2,2,4,3,2]

list.append(item) to end of list, list.insert(index, item) to index. this uses the "." to pipe the data into the function. In R, all functions usually need a data, then have the arguments for manipulation after, so you can say mutate(data, new column) or data %>> mutate(new column). Looks like python only gives you the pipe version.

inserts puts a new number at the specified index numbers.insert(2, 20)

my_list[1] = 3, works just like you expect in R or Matlab

pop() removes item at index, remove() removes first of given value

sort() and sorted()

You can give the [] function a step print(my_list[6:2:-1])

 

For Loops

Takes in array. If you place a string after "in", it will turn the string into an array and iterate through the characters.

for i in range(5):

	print i

range produces a range object (I don't know what the fuck this is) from 1 to the input number. range(a,b), goes from a to b-1. range(a,b,c) takes c as a input that changes the step size. range(1,9,2) will produce, 1, 3, 5, 7. wrap range() with the list() function to produce a list. A negative step size makes it a descending list.

Tuples

Immutable lists. Can be defined with nothing or parenthesis. tuple1 = 1,2,3 or tuple2 = (1,2,3) you can use these as keys to a dictionary. 

You can also assign multiple variables at once with a tuple. It seems like it has to match the quantity of items in the tuple exactly. a1, a2, a3 = tuple2 will create 3 variables with the integer data type.

 

asdf

asdf

 

a

 

 

asdf
asdf