#9 Introduction to Python
Alex Flückiger
Faculty of Humanities and Social
Sciences
University of Lucerne
5 May 2022
enter the shiny world of Python 😎
think about mini-project
Programming can be absolutely captivating! ✌️
# define variables
x = "at your service"
y = 2
z = ", most of the time."
# combine variables
int_combo = y * y # for numbers any mathematical operation
str_combo = x + z # for text only concatenation with +
# show content of variable
print(str_combo)
Name | What for? | Type | Examples |
---|---|---|---|
String | Text | str | "Hi!" |
Integer, Float | Numbers | int, float | 20 , 4.5 |
Boolean | Truth values | bool | True , False |
⋮ | ⋮ | ⋮ | ⋮ |
List | List of items (ordered, mutable) | list | ["Good", "Afternoon", "Everybody"] |
Tuple | List of items (ordered, immutable) | tuple | (1, 2) |
Dictionary | Relations of items (unordered, mutable) | dict | {"a":1, "b": 2, "c": 3} |
# check the type
type(YOUR_VARIABLE)
# convert types (similar for other types)
int('100') # convert to integer
str(100) # convert to string
# easiest way to use a number in a text
x = 3
mixed = f"x has the value: {x}"
print(mixed)
=
vs. ==
contradicts the intuition# assign a value to a variable
x = 1
word = "Test"
# compare two values if they are identical
1 == 2 # False
word == "Test" # True
tab
for autocompletionMake sure that your local copy of the Github repository KED2022
is up-to-date with git pull
.
Open the Visual Studio Editor.
Windows User only: Make sure that you are connected to
WSL: Ubuntu
(green badge lower-left corner, see image on
the next slide). If not, click on the badge and select
New WSL Window
.
Create a new file with the following content, save it as
hello_world.py
. Then, execute it by a right click on the
code and select Run current file in interactive window
.
# print out a message
msg = "Hello World!"
print(msg)
Does the output looks like the screenshot on the next slide? If the execution doesn’t work as expected, ask me or your neighbour. There might be a technical issue.
do something with each element of a collection
sentence = ['This', 'is', 'a', 'sentence']
# iterate over each element
for token in sentence:
# do something with the element
print(token)
condition action on variable content
sentence = ['This', 'is', 'a', 'sentence']
if len(sentence) < 3:
print('This sentence is shorter than 3 tokens')
elif len(sentence) == 3:
print('This sentence has exactly 3 tokens')
else:
print('This sentence is longer than 3 tokens')
tab
to intend✅
if 5 > 2:
print('5 is greater than 2')
❌
if 5 > 2:
print('5 is greater than 2')
sentence = 'This is a sentence'
# split at whitespace
tokens = sentence.split(' ')
# check the variables
print(sentence, type(sentence), tokens, type(tokens))
# add something to a list
tokens.append('.')
# concatenate elements to string
tokens = ' '.join(tokens)
print(tokens, type(tokens))
function_name(arg1, ..., argn)
# define a new function
def get_word_properties(word):
"""
My first function to print word properties.
It takes any string as argument (variable: word).
"""
# print(), len() and sorted() work also as functions
length = len(word)
sorted_letters = sorted(word, reverse=True)
print(word, 'length:', length, 'letters:', sorted_letters)
get_word_properties('computer') # call function with any word
sentence = ['This', 'is', 'a', 'sentence']
# element at position X
first_tok = sentence[0] # 'This'
# elements of subsequence [start:end]
sub_seq = sentence[0:3] # ['This', 'is', 'a']
# elements of subsequence backwards
sub_seq_back = sentence[-2:] # ['a', 'sentence']
materials/code/python_basics.ipynb
is a
from the list using the right index.Write a Python script that
Go to the next slide. Start with some of the great interactive exercises out there in the web.
Comments