294 KiB
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
)¶
# Integers
a = 2
b = 239
Floating point numbers (float
)¶
# Floats
c = 2.1
d = 239.0
Strings (str
)¶
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:
'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
)¶
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:
2 * 4
2 / 5
3.1 + 7.4
Exponents¶
Exponents are denoted by ** and not ^:
2**3
Floor division¶
Returns integer part of division result (removes decimals after division)
10 // 3
Modulo¶
Returns remainder after divions
10 % 3
Operations on strings¶
Strings can be added (concatenated)
'Bruce' + ' ' + 'Wayne'
Multiplication is also allowed:
'a' * 3
Subtraction and division are not allowed:
'a' / 3 # Division results in error
'a' - 'b' # Subtraction results in error
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.
# 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}')
# 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
Both variables and complex computations can be inserted inside the curly brackets to be printed.
print(f'Computation insde curly bracket: {122**2 / 47}')
Function: len()
¶
The len()
function returns the length of a sequence, e.g. a string:
len('aaa')
len('a and b') # Spaces are also counted
Some string methods¶
A string object can be interacted with in many ways by so-called methods. Some useful methods are shown below:
name = 'Edward Snowden'
string.replace()
¶
Replaces characters inside a string:
string.replace('old_substring', 'new_substring')
name.replace('Edward', 'Ed')
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:
name
In order to save the replacement and retain the name of the variable, we could just reassign it to the same name:
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')
name.endswith('g')
name.endswith('n')
name.endswith('den')
string.count()
¶
Counts the number of occurences of a substring inside a string:
string.count('substring_to_count')
text = 'This is how it is done'
text.count('i')
text.count('is')
The match is case sensistive:
text.count('t')
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.
x = 2
if x > 1:
print('x is larger than 1')
if
/ else
-statements¶
y = 1
if y > 1:
print('y is larger than 1')
else:
print('y is less than or equal to 1')
if
/ elif
/ else
¶
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')
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.