# Careful here!
= 1
one = 1
two print(one == two)
True
Programming with Python
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 indices. . .
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
)==
, !=
, >
, <
, >=
, <=
. . .
> Question: Is this True
?
# Careful here!
= 1
one = 1
two print(one == two)
True
if
, elif
, else
for
and while
continue
and break
. . .
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.
# I'm a function.
type(print)
builtin_function_or_method
. . .
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 name. . .
def greet(a_parameter):
print(f"Hello, {a_parameter}!")
"Students") greet(
Hello, Students!
. . .
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
def greet():
print("Hello, stranger!")
greet()
Hello, stranger!
. . .
> Question: What could be the correct arguments here?
def greet(university_name, lecture):
print(f"Hello, students at the {university_name}!")
print(f"You are in lecture {lecture}!")
# Your code here
=
sign and provide it with a valuedef greet(lecture="Programming with Python"):
print(f"You are in lecture '{lecture}'!")
greet()"Super Advanced Programming with Python") greet(
You are in lecture 'Programming with Python'!
You are in lecture 'Super Advanced Programming with Python'!
. . .
This is especially useful when we want to avoid errors due to missing arguments!
print("h","i",sep='')
. . .
> Question: What will be printed here?
def call_parameters(parameter_a, parameter_b):
print(parameter_a, parameter_b)
="Hello", parameter_a="World") call_parameters(parameter_b
World Hello
return
statement. . .
def simple_multiplication(a,b):
= a*b
result return result
print(simple_multiplication(2,21))
42
. . .
def simple_multiplication(a,b):
return a*b # even shorter!
print(simple_multiplication(2,21))
42
. . .
def simple_multiplication(a,b):
return a*b # even shorter!
= simple_multiplication(2,21)
result print(result)
42
return
, functions will return None
def simple_multiplication(a,b):
= a*b
result
print(simple_multiplication(2,21))
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
.
. . .
You can also use multiple return statements in a function.
. . .
def fibonacci(n): # Classical example to introduce recursion
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(6))
8
. . .
Recursion can be a powerful tool, but it can also be quite tricky to get right.
. . .
def greet(name):
= f"Hello, {name}!"
greeting
print(greeting) # This will cause an error
. . .
> Question: Any idea how to access greeting
?
. . .
= "Hello, Stranger!"
greeting def greet(name):
= f"Hello, {name}!"
greeting return greeting
print(greet("Students")) # Greet students
print(greeting) # Greet ????
Hello, Students!
Hello, Stranger!
. . .
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 variable. . .
= "Hello, Stranger!"
greeting
def greet(name):
global greeting
= f"Hello, {name}!"
greeting return greeting
print(greet("Students")) # Greet students
print(greeting) # Greet students again
Hello, Students!
Hello, Students!
. . .
>Question: This can be confusing. Do you think you got the idea?
. . .
class Students: # Class definition
def know_answer(self): # Method definition
print(f"They know the answer to all questions.")
= Students() # Object instantiation
student student.know_answer()
They know the answer to all questions.
self
keywordself
in a method, it refers to the object itselfself
always needs to be included in method definitions. . .
# This won't work as self is missing
class Students: # Class definition
def know_answer(): # Method definition without self
print(f"They know the answer to all questions.")
= Students()
student student.know_answer()
. . .
>Task: Try it yourself, what is the error?
People
)TallPeople
).py
extension. . .
Question: Which of the following is a good class name? smart_student
, SmartStudent
, or SmartStudents
. . .
>Question: What do you think will happen here?
class Students: # Class definition
= True # Class attribute
smart
= Students() # Object instantiation student_A
student_A = Students() # Object instantiation student_B
student_B
print(student_A.smart)
print(student_B.smart)
True
True
__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("Buddy",False) # Note, we don't need to call self here!
student student.knows_answer()
Buddy does not know the answer to the question.
. . .
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.
. . .
Fortunately, this is an introduction to Python, so we won’t go into details of encapsulation.
. . .
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}
. . .
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.
Comment Functions
"""
, it will appear in the help menu. . .