# Let's illustrate f-strings with a small example:
= "Mr. Smith"
name = 30
age = 1.826549
height print(f"My name is {name}, I'm {age} years old, and {height:.2f} meters tall.")
My name is Mr. Smith, I'm 30 years old, and 1.83 meters tall.
Programming with Python
{}
. . .
# Let's illustrate f-strings with a small example:
= "Mr. Smith"
name = 30
age = 1.826549
height print(f"My name is {name}, I'm {age} years old, and {height:.2f} meters tall.")
My name is Mr. Smith, I'm 30 years old, and 1.83 meters tall.
. . .
We used the :.2f
format specifier to round the number to two decimal places.
int
, float
, str
, bool
=
operator. . .
> Question: What are the types of y
, z
, w
?
= 2.5
y = "Hello"
z = True
w print(f"y is of type {type(y).__name__}")
print(f"z is of type {type(z).__name__}")
print(f"w is of type {type(w).__name__}")
y is of type float
z is of type str
w is of type bool
Addition
Subtraction
Multiplication
Division
Floor Division
Exponentiation
Modulo
+
-
*
/
//
**
%
Adds two numbers
Subtracts one number from another
Multiplies two numbers
Floating-point division
Integer division
Power of
Remainder of division
. . .
Note, that the /
operator always returns a float, even if the division is even. Furthermore, the +
operator can be used to concatenate strings and that the *
operator can be used to repeat strings.
+=
, -=
, *=
, /=
, //=
, **=
, %=
. . .
> Question: What is the value of x
after the operations?
= 10
x print(f"Initial value of x: {x}")
+= 5 # Equivalent to x = x + 5
x print(f"After x += 5: {x}")
*= 2 # Equivalent to x = x * 2
x print(f"After x *= 2: {x}")
%= 4 # Equivalent to x = x % 4
x print(f"After x %= 4: {x}")
Initial value of x: 10
After x += 5: 15
After x *= 2: 30
After x %= 4: 2
. . .
For most programming purposes, you can treat everything in Python as an object. This means you can assign all types to variables, pass them to functions, and in many cases, call methods on them.
object.method([arguments])
. . .
You can use the dir()
function to list all methods and attributes of an object.
Here are some commonly used string methods:
upper()
: Converts all characters in the string to uppercaselower()
: Converts all characters in the string to lowercasetitle()
: Converts first character of each word to uppercasestrip()
: Removes leading and trailing whitespacereplace()
: Replaces a substring with another substringfind()
: Finds first substring and returns its indexcount()
: Counts the number of occurrences of a substring> Question: What will be the output of the following code?
message = "Hello, World!"
print(message.upper()) # Converts to uppercase
print(message.lower()) # Converts to lowercase
print(message.title()) # Converts to title case
print(message.replace("World", "Python")) # Replaces "World" with "Python"
print(message.find("World")) # Finds "World" and returns its index
print(message.count("o")) # Counts the number of occurrences of "o"
HELLO, WORLD!
hello, world!
Hello, World!
Hello, Python!
7
2
. . .
Note, how replace()
does not modify the original string. Instead, it returns a new string.
> Task: Discuss and implement the following task:
# Change the following message to get the desired output
= " the snake programmer. "
message # Your code here
= "The Python Programmer." output
. . .
Remember, that these methods return a new string. The original string is not modified.
= " the snake programmer. "
message print(message.strip().title().replace("Snake", "Python"))
The Python Programmer.
. . .
Here we chained methods together to perform multiple operations after another in one line.
. . .
= "Hello, World!"
string_to_index print(string_to_index[0]) # Accessing the first character
print(string_to_index[-1]) # Accessing the last character
H
!
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 (default is 1). . .
= "Hello, World!"
string_to_slice print(string_to_slice[7:12]) # Accessing the last five characters from the start
print(string_to_slice[-6:-1]) # Accessing the last five characters from the end
World
World
start
or stop
, it will be replaced by the start or end of the sequence, respectivelystep
, it will be replaced by 1. . .
= "Hello, World!"
string_to_slice print(string_to_slice[::2]) # Accessing every second character
print(string_to_slice[::-1]) # Accessing the string in reverse
Hlo ol!
!dlroW ,olleH
> Task: Discuss and implement the following task:
# Slice the following message to create the described output
= "y6S0-teru89d23e'.n*ut"
message # Your code here
= "Student" output
. . .
Remember, that these methods return a new string. The original string is not modified.
True
or False
). . .
> Question: What will be the output of the following code?
lower_number = 2; upper_number = 9
print(lower_number == upper_number) # Equality
print(lower_number != upper_number) # Inequality
print(lower_number > upper_number) # Greater than
print(lower_number < upper_number) # Less than
print(lower_number >= upper_number) # Greater than or equal to
print(lower_number <= upper_number) # Less than or equal to
False
True
False
True
False
True
and
, or
, not
. . .
> Question: Which of the following expressions is True
?
lower_number = 2; middle_number = 5; upper_number = 9;
print(lower_number < middle_number and middle_number < upper_number) # and
print(lower_number < middle_number or middle_number > upper_number) # or
print(lower_number == lower_number and not lower_number > middle_number) # not
True
True
True
. . .
Note, that and
and or
are evaluated from left to right.
in
, not in
. . .
> Question: Which of these expressions is True
?
= "apple"
an_apple print("a" in an_apple) # Check if "a" is in the string "apple"
print("pp" not in an_apple) # Check if "pp" is not in the string
True
False
. . .
Note, that in
and not in
can be used for strings, lists, tuples, sets, and dictionaries. Don’t worry! We will learn about lists, tuples, sets, and dictionaries later in the course.
if
, elif
, else
, for
, while
, break
, continue
. . .
> Question: What do you think each of the above does?
. . .
Mixing tabs and spaces can cause errors that are difficult to debug. The Python style guide (PEP 8) recommends using 4 spaces per indentation level for consistency and readability.
if
statements execute a block of code if a condition is True
elif
statements execute a block of code if the previous condition is False
and the current condition is True
else
statements execute a block of code if the previous conditions are False
. . .
You can use the and
and or
operators to combine multiple conditions.
= True
condition if condition:
print("The condition is True!") # Code block to execute if condition is True
print("This will always be printed!")
The condition is True!
This will always be printed!
. . .
= False
condition if condition:
print("The condition is True!") # Code block to execute if condition is True
print("This will always be printed!")
This will always be printed!
. . .
Writing if condition:
is equivalent to if condition == True:
= True
condition if condition:
print("The condition is True!") # Code block to execute if condition is True
else:
print("The condition is False!") # Code block to execute if condition is False
The condition is True!
. . .
= False
condition if condition:
print("The condition is True!") # Code block to execute if condition is True
else:
print("The condition is False!") # Code block to execute if condition is False
The condition is False!
= 11
temperature if temperature > 10:
print("The temperature is greater than 10!")
elif temperature == 10:
print("The temperature is equal to 10!")
else:
print("The temperature is less than 10!")
The temperature is greater than 10!
. . .
= 10
temperature if temperature > 10:
print("The temperature is greater than 10!")
elif temperature == 10:
print("The temperature is equal to 10!")
else:
print("The temperature is less than 10!")
The temperature is equal to 10!
> Question: What will be the output of the following code?
= "Harry"
name = "wizard"
profession = 16
age if name == "Harry" and profession == "wizard" and age < 18:
print("You are the chosen one still visiting school!")
elif name == "Harry" and profession == "wizard" and age >= 18:
print("You are the chosen one and can start your journey!")
else:
print("You are not the chosen one!")
You are the chosen one still visiting school!
for
and while
for
loops are used to iterate over a sequence (e.g., list, tuple, string)while
loops execute repeatedly until a condition is False
. . .
Nested control structures through further indentation are allowed as well, we thus can chain multiple control structures together.
for i in range(5):
print(i)
0
1
2
3
4
for i in range(0, 10, 2):
print(i)
0
2
4
6
8
. . .
The range()
function can take up to three arguments: start, stop, and step.
. . .
> Question: What do you expect will be the output?
= "yellow banana"
fruit for letter in fruit:
print(letter)
y
e
l
l
o
w
b
a
n
a
n
a
= 0
i while i < 5:
print(i)
+= 1 i
0
1
2
3
4
. . .
> Question: What could be an issue with poorly written while-loops?
> Question: Anybody an idea what this code does?
= 0
i while True:
if i % 10 == 0:
print(i)
if i > 100:
break
+= 1 i
0
10
20
30
40
50
60
70
80
90
100
. . .
Without control flow, programs would execute linearly from top to bottom, limiting their functionality and flexibility.
> Task: Implement the following task:
# Implement a while-loop that prints all even numbers between 0 and 100 excluding both 0 and 100.
= 0
number # Your code here
. . .
And that’s it for todays lecture!
We now have covered the basics on String methods, Comparisons, conditional statements and loops.
. . .
Nothing new here, but these are still great books to start with!
. . .
For more interesting literature to learn more about Python, take a look at the literature list of this course.