def greet(name):
return f"Welcome to this lecture, {name}!"
print(greet("Students"))
Welcome to this lecture, Students!
Programming with Python
def
followed by the function name, parameters and a colon. . .
def greet(name):
return f"Welcome to this lecture, {name}!"
print(greet("Students"))
Welcome to this lecture, Students!
. . .
def greet(name):
= f"Welcome to this lecture, {name}!"
greeting return greeting
print(greeting) # This will cause an error
>Question: Why does this cause an error?
. . .
class Lectures:
def __init__(self, name, length_minutes):
self.name = name
self.length = length_minutes
def duration(self):
return f"Lecture '{self.name}' is {self.length} minutes long!"
= Lectures("4. Data in more than one dimension", 90)
lecture_4 print(lecture_4.duration())
Lecture '4. Data in more than one dimension' is 90 minutes long!
tuple()
function or the ()
syntax. . .
= (1, 2, 3, 4, 5)
my_tuple print(my_tuple)
(1, 2, 3, 4, 5)
+
operator to concatenate tuples*
operator to repeat a tuple. . .
>Question: What will the following code print?
= (1, 2, 3)
my_tuple print(my_tuple[1:3])
print(my_tuple + (4, 5, 6))
print(my_tuple * 2)
(2, 3)
(1, 2, 3, 4, 5, 6)
(1, 2, 3, 1, 2, 3)
count(x)
: Returns the number of times x
appears in the tupleindex(x)
: Returns the index of the first occurrence of x
. . .
>Question: What will this code print?
= (1, 2, 3, 2, 4, 2)
my_tuple print(my_tuple.count(2))
print(my_tuple.index(3))
3
2
= ("Peter", 25, "Hamburg")
my_tuple print(my_tuple)
('Peter', 25, 'Hamburg')
. . .
# This works as well
= "Peter", 25, "Hamburg"
my_tuple print(my_tuple)
('Peter', 25, 'Hamburg')
. . .
We can also create tuples by listing the elements separated by commas.
. . .
def get_student_info(name, age, city):
return name, age, city
= get_student_info("Peter", 25, "Hamburg")
student_info print(student_info)
('Peter', 25, 'Hamburg')
. . .
>Question: How would you access the age from the tuple?
*
operator to assign the remaining elements to a variable. . .
def get_student_info(name, age, city):
return name, age, city
*rest = get_student_info("Peter", 25, "Hamburg")
name, print(f"Name: {name}")
print(f"Other info: {rest}")
Name: Peter
Other info: [25, 'Hamburg']
. . .
The output is positional, so we have to be careful with the order of the variables.
list()
function or the []
syntax. . .
= [1, 2, 3, 4, 5]
my_list print(my_list)
[1, 2, 3, 4, 5]
. . .
>Question: Any idea why lists support more methods?
count(x)
: Returns the number of times x
appears in the listappend(x)
: Adds an element x
to the end of the listinsert(i, x)
: Inserts an element x
at index i
remove(x)
: Removes the first occurrence of element x
index(x)
: Returns the index of the first occurrence of x
pop([i])
: Removes the element at index i
and returns itsort()
: Sorts the list in ascending orderreverse()
: Reverses the list>Task: Solve the following problem using lists:
# Imagine the following shoppping list for this weekend
= ["cider", "beer", "bread", "frozen_pizza"] shopping_list
. . .
. . .
You can use the methods and loops we learned so far to solve the problem.
set()
function or the {}
syntax+
and *
operations like lists and tuples. . .
= {1, 2, 2, 5, 5}
my_set print(my_set)
{1, 2, 5}
add(x)
: Adds an element x
to the setremove(x)
: Removes an element x
from the setdiscard(x)
: Removes an element x
from the set if it is presentpop()
: Removes and returns an arbitrary element from the setupdate(other)
: Adds all elements from other
to the setunion(other)
: New set with elements from both setsintersection(other)
: New set with common elementsisdisjoint(other)
: True
if no elements in commonissubset(other)
: True
if subset of other
. . .
There are more methods for sets! If you are working intensively with sets, keep that in mind.
>Task: Solve the following problem using sets:
# You have a list of friends from two different groups
= ["Neo", "Morpheus", "Trinity", "Cypher"]
friends_group_1 = [ "Smith", "Apoc", "Cypher", "Morpheus"] friends_group_2
. . .
. . .
Notice, there is a small error in the given code that you have to fix.
dict()
function or the {}
syntax. . .
= {"name": "Tobias", "age": 30, "city": "Hamburg"}
who_am_i print(who_am_i)
{'name': 'Tobias', 'age': 30, 'city': 'Hamburg'}
. . .
= {"name": "Tobias", "age": 30, "city": "Hamburg"}
who_am_i print(who_am_i["name"])
Tobias
. . .
Note, how we can use the []
operator to access the value of a key?
Common operations and methods:
in
operation to check if a key is in the dictionary
for
loop to iterate over the dictionary
keys()
method to return a view of the dictionary’s keys
values()
method to return a view of the dictionary’s values
pop(key[, default])
to remove a key and return its value
>Task: Solve the following problem using dictionaries:
# Create a dictionary with the following information about yourself: name, age, city
= {} i_am
. . .
. . .
This impacts your code, the operations you can perform and the speed of your program. Thus, it makes sense to understand the differences and choose the right data type for the task.
. . .
You can convert between the data types using tuple()
, list()
, set()
and dict()
. Note, that this is not always possible, e.g. you cannot convert a list to a dictionary without specifying a key.
import timeit
# Number of elements in each data structure
= 10000000
n
# Setup for each data structure, including the test function
= """
setup_template def test_membership(data_structure, element):
return element in data_structure
data = {data_structure}
"""
= {
setups 'Tuple': setup_template.format(data_structure=f"tuple(range({n}))"),
'List': setup_template.format(data_structure=f"list(range({n}))"),
'Set': setup_template.format(data_structure=f"set(range({n}))"),
'Dictionary': setup_template.format(data_structure=f"{{i: i for i in range({n})}}")
}
# Measure time for each data structure
print(f"Time taken for a single membership test in {n} elements (in seconds):")
print("-" * 75)
for name, setup in setups.items():
= f"test_membership(data, {n-1})" # Test membership of the last element
stmt = timeit.timeit(stmt, setup=setup, number=1)
time_taken print(f"{name:<10}: {time_taken:.8f}")
print("-" * 75)
print("Note, that theses values are machine dependent and just for illustration!")
Time taken for a single membership test in 10000000 elements (in seconds):
---------------------------------------------------------------------------
Tuple : 0.05766171
List : 0.05379279
Set : 0.00000304
Dictionary: 0.00000408
---------------------------------------------------------------------------
Note, that theses values are machine dependent and just for illustration!
(x for x in iterable)
[x for x in iterable]
{x for x in iterable}
{x: y for x, y in iterable}
. . .
The iterable can be any object that can be iterated over, e.g. a list, tuple, set, dictionary, etc.
for
loop to iterate over an iterable. . .
= ["cider", "beer", "bread", "frozen_pizza"]
shopping_list for item in shopping_list:
print(item)
cider
beer
bread
frozen_pizza
. . .
= {"name": "Tobias", "age": 30, "city": "Hamburg"}
who_am_i for key, value in who_am_i.items():
print(f"{key}: {value}")
name: Tobias
age: 30
city: Hamburg
. . .
= [1, 2, 3, 4, 5]
normal_list = ["Hello, World!", normal_list, (1,2)]
nested_list
print(nested_list)
print(nested_list[2])
['Hello, World!', [1, 2, 3, 4, 5], (1, 2)]
(1, 2)
. . .
You can also nest lists within lists within lists, etc.
input()
function from the first lecture?print()
function. . .
= input("Please enter your name: ")
name print(f"Hello, {name}!")
. . .
Thus, we have already worked with I/O in Python!
open(file_name, mode)
to open a file"r"
(read), "w"
(write), "a"
(append)file.read()
file.write(content)
file.close()
file = open("hi.txt", "w") # This creates a file called "hi.txt"
file.write("Hello, World!") # This writes "Hello, World!" to the file
file.close() # This closes the file
print("File successfully written")
File successfully written
. . .
>Question: Any ideas how to read the file?
. . .
file = open("hi.txt", "r") # This opens the file "hi.txt"
= file.read() # This reads the content of the file
content file.close() # This closes the file
print(content) # This prints the content of the file
Hello, World!
. . .
Close files with file.close()
to free up system resources and ensure data is properly saved.
with
statement to open a filewith open("hi_again.txt", "w") as file:
file.write("Hello again, World!")
print("File successfully written")
File successfully written
. . .
>Task: Open the file hi_again.txt
and print its content using with
. . .
And that’s it for todays lecture!
We now have covered the basics of tuples, sets, lists and dictionaries as well as some basic file handling. For now, just remember that advanced reading and writing is possible and that there are libraries that help with this.
Literature {.title}
. . .
Nothing new here, but these are still great books!
. . .
For more interesting literature to learn more about Python, take a look at the literature list of this course.