# This is a comment in Python
print("Hello, my name is [YOUR NAME HERE]!")
Hello, my name is [YOUR NAME HERE]!
Programming with Python
. . .
I really appreciate active participation and interaction!
.py
files). . .
I’d encourage you to start and submit your solution early
. . .
But you should not simply use them to replace your learning.
. . .
Great resources to start are books and small challenges. You can find a list of book recommendations at the end of the lecture. Small challenges to solve can for example be found on Codewars.
=
applicationuv
uv
to install and manage Python versionsuv
and Python. . .
Not all packages available in Python are available in Pythonista, thus you might need a computer to solve certain problems.
Task: Open the directory you created for the course and create a new file called hello.py
with the following code:
# This is a comment in Python
print("Hello, my name is [YOUR NAME HERE]!")
Hello, my name is [YOUR NAME HERE]!
. . .
Run it by executing the following command in your terminal:
uv run python hello.py
. . .
Task: Create a new file called message_world.py
file. Assign the string "Hello, World!"
to a variable called message
and print the variable.
. . .
. . .
# Here we assign the string "Hello, World!" to variable message and print it
= "Hello, World!"
message print(message)
Hello, World!
We can also mix "
and '
in a string, if we are consistent:
# This code works
= 'I shout "Hello, World!"'
message print(message)
I shout "Hello, World!"
. . .
# This code does not!
= 'I shout 'Hello, World!""
message print(message)
. . .
Try it yourself! What does happen, if you try to run it?
SyntaxError: invalid syntax
. . .
We will cover these concepts in more detail later in the course.
Let’s go back to our first program:
# Our first program
= "Hello, World!"
message print(message)
. . .
#
message
print
. . .
Task: Try this code in Python:
# Try this code in Python to see the Zen of Python
import this
=
= 2 # Variable a assigned the value 2
a = "Time" # Variable b assigned the value "Time"
b = print # Variable c assigned the print function
c # Now we can call the print function with c c(b)
Time
. . .
But there are certain rules to variable names!
_
a
and A
are different!for
, if
, def
, etc. . .
Question: Which of the following fulfill these conditions?
a, _duration, 1x, time_left, 1_minute, oneWorld, xy4792
function([arguments])
None
. . .
# Print is such a function
print("Hello, World!") # It takes an argument and prints it to the console
print("Hello","World!", sep=", ") # It can also take multiple arguments
Hello, World!
Hello, World!
. . .
We will cover functions in more detail later in the course.
type()
is a function that returns the type of a valueBack to our example of “Hello, World!”
Hello, World! is a <class 'str'>
. . .
Result: “Hello, World” is a string - in short ‘str’.
. . .
But what about the f”?
f
. . .
In older code bases, f strings were not available. Here, interpolation could be done as shown below with print()
and .format()
. But this method is less concise and arguably less readable.
. . .
print("{} is a {}".format(message, message_type))
Hello, World! is a <class 'str'>
{<to_print>:<width>.<precision>f}
width
can be a number specifying the output width<
, ^
, >
can be used before the width to align the textprecision
can be used to specify the decimals.f
can be used to format floats= "hello"
x print(f"{x:<10} has {len(x):>10.2f} characters.")
hello has 5.00 characters.
= 1 # Statement that assigns the value 3 to x
x = x + 2 # Expression on the right side assigned to a variable y
y print(f"Great, the result is {y}")
Great, the result is 3
"Hello"
, 'World'
, "123"
, '1World23'
= "Hello"
hello = 'World!'
world print(hello,world,sep=", ") # We can specify the separator with the argument sep
Hello, World!
. . .
Strings are immutable, we can’t change characters in them once created.
= "Hello" + ", " + "World!" # String concatenation
two_strings print(two_strings)
Hello, World!
. . .
print(two_strings[0]) # Indexing starts at zero!
H
. . .
print(len(two_strings)) # With len we can find the length of our string
13
. . .
print("--x--"*3) # We can also repeat strings
--x----x----x--
True
and False
1
and 0
, respectivelyif
, while
, for
, elif
, `else. . .
= True
x = False
y print(x)
print(type(y))
True
<class 'bool'>
. . .
> More on them in our next lecture!
1
, -3
, 0
or 100
-4.78
, 0.1
or 1.23e2
. . .
= 1; y = 1.2864e2 # We can separate multiple operations in one line with semicolons
x print(f"{x} is of type {type(x)}, {y} is of type {type(y)}")
1 is of type <class 'int'>, 128.64 is of type <class 'float'>
. . .
The interpreter will automatically convert booleans to integers to floats when necessary, but not the other way around!
= 1 + 2; print(f"Result: addition is {addition}")
addition = 1 - 2; print(f"Result: substraction is {substraction}")
substraction = 3 * 4; print(f"Result: multiplication is {multiplication}")
multiplication = 7 / 4; print(f"Result: division is {division}")
division = 7 // 4; print(f"Result: floor_division is {floor_division}")
floor_division = 9 ** 0.5; print(f"Result: exponentiation is {exponentiation}")
exponentiation = 10 % 3; print(f"Result: modulo is {modulo}") modulo
Result: addition is 3
Result: substraction is -1
Result: multiplication is 12
Result: division is 1.75
Result: floor_division is 1
Result: exponentiation is 3.0
Result: modulo is 1
. . .
# Operator precedence works as on paper
= 2 + 3 * 4
combined_operation print(f"2 + 3 * 4 = {combined_operation}")
2 + 3 * 4 = 14
. . .
# Parentheses change precedence as expected
= (2 + 3) * 4
parentheses_operation print(f"(2 + 3) * 4 = {parentheses_operation}")
(2 + 3) * 4 = 20
input([userprompt])
. . .
= input("What's your name? ")
name print(f"Hello, {name}!")
. . .
The function always returns the input as string!
Task: Solve the following task:
# TODO: Ask the user for their age and print a compliment
. . .
Solution
= int(input("How old are you? "))
age print(f"You look great for {age}!")
Use type conversion for other data types
int(input())
float(input())
bool(input())
str(input())
. . .
# Converting to Integer
= int(input("Enter your age: "))
age = age + 1
next_year print(f"Next year, you'll be {next_year}")
# Hence, we can use the int() function to convert a float into an int
= 1.789
soon_int print(f"{soon_int} converted to {int(soon_int)} of type {type(int(soon_int))}")
1.789 converted to 1 of type <class 'int'>
. . .
# We can also use `round()` to round a float to an int
= 1.789
soon_int print(f"{soon_int} converted to {round(soon_int)} of type {type(round(soon_int))}")
1.789 converted to 2 of type <class 'int'>
. . .
# Or to a float with a certain number of decimals
= 1.789
no_int print(f"{no_int} converted to {round(no_int,1)} of type {type(round(no_int,1))}")
1.789 converted to 1.8 of type <class 'float'>
. . .
That’s it for todays lecture!
We now have covered the basics on the Python syntax, variables, and data types.
. . .
Think Python is a great book to start with. It’s available online for free here. Schrödinger Programmiert Python is a great alternative for German students, as it is a very playful introduction to programming with lots of examples.
. . .
For more interesting literature to learn more about Python, take a look at the literature list of this course.