Python101/Session 1 - Data Types/Session 1 - Data Types.html

294 KiB

<html> <head> </head>

Session 1

Use a locally installed editor like Spyder or Visual Studio Code. If you want to try out coding without installing anything, try this online editor: https://www.onlinegdb.com/online_python_compiler

Code comments

In order to explain the code, comments in Python can be made by preceding a line with a hashtag #. Everything on that particular line will then not be interpreted as part of the code:

# This is a comment and will not be interpreted as code

Data Types

The basic data types in Python are illustrated below.

Integers (int)

In [1]:
# Integers
a = 2
b = 239

Floating point numbers (float)

In [2]:
# Floats
c = 2.1
d = 239.0

Strings (str)

In [3]:
e = 'Hello world!'
my_text = 'This is my text'

Both " and ' can be used to denote strings. If the apostrophe character should be part of the string, use " as outer boundaries:

"Barrack's last name is Obama"

Alternatively, \ can be used as an escape character:

In [4]:
'Barrack\'s last name is Obama'
Out[4]:
"Barrack's last name is Obama"

Note that strings are immutable, which means that they can't be changed after creation. They can be copied or manipulated and saved into a new variable though.

Boolean (bool)

In [5]:
x = True
y = False

Extra Info: Python is dynamically typed language

As you might have noticed, Python is a dynamically typed language. That means that one does not have to declare the type of a variable before creating it.

To create a variable a in a statically typed language, it would go something like (C++):

int a
a = 5

You might also have seen this when using VBA with Option Explicit enabled, where it would be Dim a As Integer and then a = 5. If the variable type is not declared beforehand in such languages, an error wiil be thrown. In Python, this is all abstracted away. It automatically figures out which type to assign to each variable in the background.

This also means that variables can change types throughout the program, so somthing like this is valid:

a = 5
a = 'Hi'

Which can be both a blessing and a curse. The flexibility is nice, but it can lead to unexpected code behavior if variables are not tracked.

Calculations with data types

Standard calculator-like operations

Most basic operations on integers and floats such as addition, subtraction, multiplication work as one would expect:

In [6]:
2 * 4
Out[6]:
8
In [7]:
2 / 5
Out[7]:
0.4
In [8]:
3.1 + 7.4
Out[8]:
10.5

Exponents

Exponents are denoted by ** and not ^:

In [9]:
2**3
Out[9]:
8

Floor division

Returns integer part of division result (removes decimals after division)

In [10]:
10 // 3
Out[10]:
3

Modulo

Returns remainder after divions

In [11]:
10 % 3
Out[11]:
1

Operations on strings

Strings can be added (concatenated)

In [12]:
'Bruce' + ' ' + 'Wayne'
Out[12]:
'Bruce Wayne'

Multiplication is also allowed:

In [13]:
'a' * 3
Out[13]:
'aaa'

Subtraction and division are not allowed:

In [14]:
'a' / 3    # Division results in error
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-18a27a45574d> in <module>
----> 1 'a' / 3    # Division results in error

TypeError: unsupported operand type(s) for /: 'str' and 'int'
In [33]:
'a' - 'b'    # Subtraction results in error
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-33-f52d61c1bb56> in <module>
----> 1 'a' - 'b'    # Subtraction results in error

TypeError: unsupported operand type(s) for -: 'str' and 'str'

Printing strings with variables

There is quite often a need for printing a combination of static text and variables. This could e.g. be to output the result of a computation. Often the best way is to use the so-called f-strings. See examples below.

In [15]:
# Basic usage of f-strings
a = 2
b = 27
print(f'Multiplication: a * b = {a} * {b} = {a*b}')
print(f'Division: a / b = {a} / {b} = {a/b}')
Multiplication: a * b = 2 * 27 = 54
Division: a / b = 2 / 27 = 0.07407407407407407
In [16]:
# f-strings with formatting for number of decimal places
print(f'Division: a / b = {a} / {b} = {a/b:.3f}')   # The part ':.xf' specfifies 'x' decimals to be printed 
Division: a / b = 2 / 27 = 0.074

Both variables and complex computations can be inserted inside the curly brackets to be printed.

In [17]:
print(f'Computation insde curly bracket: {122**2 / 47}')
Computation insde curly bracket: 316.6808510638298

Function: len()

The len() function returns the length of a sequence, e.g. a string:

In [18]:
len('aaa')
Out[18]:
3
In [19]:
len('a and b')   # Spaces are also counted
Out[19]:
7

Some string methods

A string object can be interacted with in many ways by so-called methods. Some useful methods are shown below:

In [20]:
name = 'Edward Snowden'

string.replace()

Replaces characters inside a string:

string.replace('old_substring', 'new_substring')
In [21]:
name.replace('Edward', 'Ed')
Out[21]:
'Ed Snowden'

Recal that strings are immutable. They can be copied or manipulated and saved to a new variable, but they can't be changed per se. This concept transfers to other more complex concstructs as well. Thus, the original string name is still the same:

In [22]:
name
Out[22]:
'Edward Snowden'

In order to save the replacement and retain the name of the variable, we could just reassign it to the same name:

In [23]:
name = name.replace('Edward', 'Ed') 

Internally, the computer gives this new name variable a new id due to the immutability, but for us this does not really matter.

string.endswith()

This method might be self explanatory, but returns a boolean (True of False) depending on whether or not the strings ends with the specified substring.

string.endswith('substring_to_test_for')
In [24]:
name.endswith('g')
Out[24]:
False
In [25]:
name.endswith('n')
Out[25]:
True
In [26]:
name.endswith('den')
Out[26]:
True

string.count()

Counts the number of occurences of a substring inside a string:

string.count('substring_to_count')
In [27]:
text = 'This is how it is done'
text.count('i')
Out[27]:
4
In [28]:
text.count('is')
Out[28]:
3

The match is case sensistive:

In [29]:
text.count('t')
Out[29]:
1

Code indendation

In Python, code blocks are separated by use of indentation. See e.g. ine the defintion of an if-statement below:

if some_condition:
    # Code here must be indented
    # Otherwise, IndentationError will be thrown

# Code placed here is outside of the if-statement

Note the : as the last character of the if condition. This : must be present and requires an indentation in the line immediately after. This is how Python interprets the code as a block. the if-statement is exited by reverting the indentation as shown above.

All editors will automatically make the indentation upon hitting enter after the :, so it doesn't take long to get used to this.

Comparison to other languages

In many other programming languages indentation is not required. It is however still used as good practice to increase code readability. Instead of indentation, code blocks are denoted by encapsulating code in characters like (), {} etc.

Conditional statements

if-statements

An if-statement has the following syntax

In [1]:
x = 2
if x > 1:
    print('x is larger than 1')
x is larger than 1

if / else-statements

In [31]:
y = 1
if y > 1:
    print('y is larger than 1')
else:
    print('y is less than or equal to 1')
y is less than or equal to 1

if / elif / else

In [32]:
z = 0
if z > 1:
    print('z is larger than 1')
elif z < 1:
    print('z is less than 1')
else:
    print('z is equal to 1')
z is less than 1

An umlimited number of elif blocks can be used in between if and else.

Exercises

Exercise

Find the length of the following string:

s = "Batman's real name is Bruce Wayne"

Exercise

Test if s from above has "Wayne" as last characters (should return True or course)

Exercise

Print the following sentence using an f-string:

The string s has a length of <insert_length_of_s>

Use s from above.

Exercise

Use the count() method to print the number of e's in the string s form above.

Exercise

Use the replace() method to replace Ø with Y in the following string:

string1 = '33Ø12'

Save the new string in a variable string2 and print the following sentence:

The string <insert_string1> was replaced by <insert_string2>

Exercise

If the string below has more 100 characters, print "String has more than 100 characters", otherwise print "String has less than 100 characters".

dummy_string = 'Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups.'

Exercise

Print the number of space characters in dummy_string from above.

</html>