Python for Science

Types

Python documentation: Built-in types

Some important types:

  • Boolean: bool
  • Numerical types: int, float
  • Text: str
  • Sequence types: list, tuple, range
  • Dictionary: dict
  • The Null Object: None

Apart from these types there are things called classes and instances of classes called objects.

TODO: Try to give an easy to understand explaination and motivation for why you would want classes.

The official documentation is useful to see what you can do stuff with these types.

Booleans - True or False values

Python documentation: Truth value testing

We learned a bit about booleans in the code example on the previous page. Booleans are either True or False.

foo = False

# Convert to boolean with bool()
bool_four = bool(4)           # True - Positive ints are "truthy"
bool_negative_four = bool(-4) # True - Negative ints are "truthy"
bool_zero = bool(0)           # False - 0 is "falsy"
bool_none = bool(None)        # False - None is also "falsy"

When a non-boolean value is "truthy" it means that if it's used in a boolean context it will implicitly be regarded as True. Vice versa for "falsy". Two examples of boolean context are bool() or if-statements without explicit comparisons (we will see if-statements on the next page).

Numbers - int, float (and complex)

Python documentation: Numbers

Python has three built-in number types: int, float and complex. I have never programmed with complex numbers so I will ignore it.

  • int - Integers. Whole numbers. 3, 7, 1022, 5108081326778123786.
  • float - Numbers with decimals. 3.4, 7.1, 10.22, 51080.81326778123786.

The documentation linked above has a list of operations that can be performed on these numbers. What's a logical operator for adding two numbers? The plus sign. In code: x + y.

The modulo operator represented by a percent sign is interesting x % y. It calculates the remainder of the first number divided by the second number. It turns out that the remainder of division of two integers is useful.

# int - number without decimals (integer)

whole_number = 23 - 4
big_number = 1000000000 # What is this number?
easy_to_read_big_number = 1_000_000_000 # Aha! One billion!

# convert to int with int()
five_int = int("5")

# What about adding the string "5" to the int 7?
# bad_result = 7 + "5"
# TypeError: unsupported operand type(s) for +: 'int' and 'str'
# We get a type error.

good_result = 7 + int("5") # 12 - That's better!

# float - number with decimals

temperature_in_lund = 12.3
# Result of division is float
average_dice_roll = (1 + 2 + 3 + 4 + 5 + 6) / 6  # 3.5
# Even if you think it shouldn't have decimals
bar = 8 / 2  # 4.0

# Convert to float with float()
five_point_four = float("5.4")
always_decimal = float("2") # 2.0
int_to_float = float(4)

# What about float to int?
float_to_int = int(7.9) # 7 - Seems to remove decimals

# What about decimal number string to int?
# decimal_number_string_to_int = int("7.9")
# ValueError: invalid literal for int() with base 10: '7.9'
# We got an error!

One surprising thing in the code above is that Python is able to convert "5" to 5, but in this case Python wants you to convert types explicitly with int(). Otherwise you get an error (TypeError).

Just for fun: Let's see what JavaScript, the programming language of web browser, does:

> 7 + "5"
'75'

> "7" + "5"
'75'

> 7 * "5"
35

Do you think JavaScript makes more sense or less sense than Python?

Text - str

Python documentation: Text sequence type

In computer science, pieces of texts are often referred to as strings, shortened to str in Python. String literals can be written different ways:

  • 'Single "quoted" string' - Allows you to use double quotation marks inside the string.
  • "Double 'quoted' string" - Allows you to use single quotation marks inside the string
  • '''Triple single quoted string''' - Allows the string to span across multiple lines of code.
  • """Triple double quoted string""" - Allows the string to span across multiple lines of code.

The triple quoted strings are generally used for documenation inside the code. There are tools that looks at the code and extracts triple quoted strings to produce files, like HTML-files, with documentation (this explaination is simplified).

# str - string (or text for non-programmers)

hello = "My name is..."
string_multiplication = "he" * 3  # "hehehe"
multi_line_string = """The snake sees its prey
She attacks without mercy
Death is natural

Dylan on repeat
Walking around the city
My mind is roaming
"""

double_quote = "This is a string with double quotation marks"
single_quote = 'This is a string with single quotation marks'
indexing = "abcde"[2] # "c" - is at index 2

Interesting that you can multiply a string by an int (different result than JavaScript). The index example is important. Python has nice features for manipulating lists and strings can be seen as a list of characters. A surprisingly big part of programming is accessing data in lists.

Sequence types - list, tuple, range

Python documentation: Sequence types

Imagine you have 1000 values. To work with those values you could create 1000 variables and assign each variable a value. To sum the values you could write result = v1 + v2 + v3 .... Obviously this would very time consuming and annoying. Even with just 10 values it would be annoying. Thankfully we have ways to structure values.

# list - mutable sequence of objects

numbers = [1, 5, 8, 2]
mixed = ["hello", 8, 5.12, 2, 9]
combine_lists = [1, 2, 3] + [4, 5, 6] # [1, 2, 3, 4, 5, 6]
list_of_lists = [[1, 2], ["a", "b"], numbers]

length_of_string = len([1, 2, 3]) # 3

# Convert to list with list()
character_list = list("abc") # ["a", "b", "c"]

# indexing starts at 0
one_two_three = [1, 2, 3]
first = one_two_three[0]                     # 1
last = one_two_three[len(one_two_three) - 1] # 3 

# tuple - immutable sequence of objects

with_parenthesis = (1, 3)
without_parenthesis = 1, 3

# Convert to tuple with tuple()
one_two_three_tuple = tuple(one_two_three) # (1, 2, 3)

# range - represents immutable list of numbers
# We will use range() in combination with loops later

zero_one_two_range = range(3)
zero_one_two_list = list(zero_one_two_range) # [0, 1, 2]

There's way more to lists than what's shown in the code above. You find out more in the documentation but I think it can be hard to follow. Working with lists is probably more instructive.

Dictionary - dict

Python documentation: Dict

Sometimes you want to a group a collection of data, but unlike the case for lists you still want to use names to refer to the data. In comes dicts!

# dict - Map from key to object

city_data = {
    "date": "2022-11-05",
    "name": "Lund",
    "temperature": 11.2,
    "schools": ["Lund University", "LTH"]
}

city_data["date"]                # "2022-11-05"
city_data.get("date")            # "2022-11-05"
city_data["date"] = "2022-11-06" # I changed the date

list(city_data) # ["date", "name", "temperature", "schools"]

Very practical data structure. Just like you can use lists as values in the dict (as seen above) you can also have a list of dicts.

The Null Object - None

Many programming languages have the notion of a nothing, or null, value. In Python that value is called None.

# Want to name a variable but don't want to set the value?
cool_name = None
bool(None) # False - None is "falsy"

Next: Control flow