Programming with Python
Kühne Logistics University Hamburg - Fall 2024
sequence[start:stop:step]
start
is the index of the first element to includestop
is the index of the first element to excludestep
is the increment between indicesTip
If left out, the step defaults to 1. Else, start defaults to 0 and stop defaults to the length of the sequence. Negative indices can be used to slice from the end of the sequence.
True
or False
)==
, !=
, >
, <
, >=
, <=
if
, elif
, else
for
and while
continue
and break
Note
The statement continue
skips the rest of the current iteration and moves to the next one in a loop while the break
statement exits the loop entirely.
builtin_function_or_method
Important
Remember, methods are functions that are called on an object.
print()
: Print text to consoleinput()
: Read text from consolelen()
: Get the length of a sequencerange()
: Generate a sequence of numbersround()
: Round a number to a specified number of decimal placestype()
: Get the type of an objectint()
: Convert a string to an integerfloat()
: Convert a string to a floating-point numberstr()
: Convert an object to a stringdef
keyword followed by the function nameTip
It is common practice to leave out one line after the definition of a function, although we will not always do that in the lecture to save space on the slides.
print
)sum
and len
)> Question: Which of the following is a good name for a function?
myfunctionthatmultipliesvalues
multiply_two_values
multiplyTwoValues
Hello, stranger!
=
sign and provide it with a valueYou are in lecture 'Programming with Python'!
You are in lecture 'Super Advanced Programming with Python'!
Tip
This is especially useful when we want to avoid errors due to missing arguments!
print("h","i",sep='')
return
statementreturn
, functions will return None
None
> Task: Come up with a function that checks whether a number is positive or negative. It returns "positive"
for positive numbers and "negative"
for negative numbers. If the number is zero, it returns None
.
Tip
You can also use multiple return statements in a function.
8
Note
Recursion can be a powerful tool, but it can also be quite tricky to get right.
> Question: Any idea how to access greeting
?
Hello, Students!
Hello, Stranger!
Important
We don’t change global variables inside a function! The original value can still be accessed from outside the function.
greeting
from inside a function!global
keyword to modify a global variableHello, Students!
Hello, Students!
>Question: This can be confusing. Do you think you got the idea?
self
keywordself
in a method, it refers to the object itselfself
always needs to be included in method definitions>Task: Try it yourself, what is the error?
People
)TallPeople
).py
extensionQuestion: Which of the following is a good class name? smart_student
, SmartStudent
, or SmartStudents
__init__
methodclass Student: # Class definition
def __init__(self, name, is_smart): # Method for initalization
self.name = name
self.smart = is_smart
def knows_answer(self): # Method to be called
if self.smart:
print(f"{self.name} knows the answer to the question.")
else:
print(f"{self.name} does not know the answer to the question.")
student = Student("Buddy",False) # Note, we don't need to call self here!
student.knows_answer()
Buddy does not know the answer to the question.
Tip
Don’t worry! It can be quite much right now. Hang in there and soon it will get easier again!
class Student: # Superclass
def __init__(self, name):
self.name = name
def when_asked(self):
pass
class SmartStudent(Student): # Subclass
def when_asked(self):
return f"{self.name} knows the answer!"
class LazyStudent(Student): # Subclass
def when_asked(self):
return f"{self.name} has to ask ChatGPT!"
>Task: Create two students. One is smart and the other one is lazy. Make sure that both students reaction to a question is printed.
Note
Fortunately, this is an introduction to Python, so we won’t go into details of encapsulation.
Note
And that’s it for todays lecture!
We now have covered the basics of funtions and classes. We will continue with some slightly easier topics in the next lectures.
Literature {.title}
Tip
A fantastic textbook to understand the principles of modern software development and how to create effective software. Also available as a really good audiobook!
For more interesting literature to learn more about Python, take a look at the literature list of this course.
Lecture III - Building Reusable Functions | Dr. Tobias Vlćek | Home
Comment Functions
"""
, it will appear in the help menu