# Careful here!
one = 1
two = 1
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!
one = 1
two = 1
print(one == two)True
if, elif, elsefor and whilecontinue 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 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}!")
greet("Students")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.
_) instead of spaces in the namesprint)sum and len)> Question: Which of the following is a good name for a function?
myfunctionthatmultipliesvaluesmultiply_two_valuesmultiplyTwoValues# This function has no parameter yet!
def greet():
print("Hello, stranger!")
greet()Hello, stranger!
. . .
> Task: Use the function properly with parameters.
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()
greet("Super Advanced Programming with Python")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!
. . .
> Question: What will be printed here?
def call_parameters(parameter_a, parameter_b):
print(parameter_a, parameter_b)
call_parameters(parameter_b="Hello", parameter_a="World")World Hello
return statement. . .
def simple_multiplication(a,b):
result = a*b
return a
print(simple_multiplication(2,21))2
. . .
def simple_multiplication(a,b):
return a*b # or shorter, but this time a*b!
print(simple_multiplication(2,21))42
. . .
def simple_multiplication(a,b):
return a*b # even shorter!
result = simple_multiplication(2,21)
print(result)42
return, functions will return Nonedef simple_multiplication(a,b):
result = a*b
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.
> Task: Create a recursive function called countdown that prints numbers from n down to 1, then prints “Blast off!”. For example, countdown(5) should print 5, 4, 3, 2, 1, Blast off! (each on a new line). Start with the number 10.
. . .
Use the return statement to stop the recursion.
. . .
def greet(name):
greeting = f"Hello, {name}!"
print(greeting) # This will cause an error. . .
> Question: Any idea how to access greeting?
. . .
greeting = "Hello, Stranger!"
def greet(name):
greeting = f"Hello, {name}!"
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. . .
greeting = "Hello, Stranger!"
def greet(name):
global greeting
greeting = f"Hello, {name}!"
return greeting
print(greet("Students")) # Greet students
print(greeting) # Greet students againHello, 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.")
student = Students() # Object instantiation
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.")
student = Students()
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
smart = True # Class attribute
student_A = Students() # Object instantiation student_A
student_B = Students() # Object instantiation student_B
print(student_A.smart)
print(student_B.smart)True
True
__init__ methodclass Students: # 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 = Students("Buddy",False) # Note, we don't need to call self here!
student.knows_answer()Buddy does not know the answer to the question.
. . .
Don’t worry! It can be quite much right now.
class Students: # Superclass
def __init__(self, name):
self.name = name
def when_asked(self):
pass
class SmartStudents(Students): # Subclass
def when_asked(self):
return f"{self.name} knows the answer!"
class LazyStudents(Students): # 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.
Student class is already using encapsulation!. . .
class Students:
def __init__(self, name):
self.name = name # Data (attribute)
def when_asked(self): # Behavior (method)
return f"{self.name} is thinking..."
alice = Students("Alice")
print(alice.when_asked()) # Data and behavior work togetherAlice is thinking...
. . .
You are already doing encapsulation! Every time you create a class with attributes and methods, you’re bundling related data and behavior together. That’s the core idea!
. . .
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.
. . .
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. . .