print("Hello, world!")Fundamentals Variables
Module 1: Python Fundamentals
Fundamentals: Getting Started with Python
Hello, World!
Below is the code for the “Hello, World!”, your very first line in Python!
To run the code, click anywhere into the cell (the box with the code inside), and then type Shift + Enter (Shift + Return on a Mac) to execute.
The print() function is how our machine comunicates with us. Anything inside the parenthesis will be shown to the user.
Let’s create python code to say hello to you, instead of the world.
# My name is Daniel
print("Hello, Daniel!")Write the code that displays your favourite food.
Debugging
It is normal to make mistakes!
When the code is not properly written, it will raise errors. You should read the error carefully to understand what is causing it.
Debugging is the process of identifying and fixing errors in our code.

Fix the following lines of code.
print("Hello, world!)print("Hello, world!"Strings in Python
Strings are used to store and manipulate text. As you see here, strings are written inside of quotes and can contain letters, numbers, punctuation marks, and other special characters. A string is contained within two quotes " or single quotes '.
Run the following cells to print these four different strings.
print("This string is only text")print("This -string- has $pecial characters...")print("¯\_(ツ)_/¯")print("2.99")If you use triple quotation marks, you can store a multiline string. These strings can span more than one line. When you run the following cell, you will see how the spaces in the second line are actually read as characters for the string.
print("""Hello, World!
It's great to be here!""")Fix this code.
print("Why is this
not working?!")Arithmetic Operations in Python
We can use Python as a calculator.
print(5 + 8 + 3)Note that the extra spaces are added to make the code more readable. 5 + 8 + 3 works just as well as 5+8+3. And it is considered good style. Use the extra spaces in all your Notebooks.
Below are all the possible arithmetic operations you can do:
# Sum
print(5 + 2)# Subtraction
print(5 - 2)# Multiplication
print(5 * 2)# Division
print(5 / 2)# Exponentiation
print(5 ** 2)# Quotient
print(5 // 2)# Remainder
print(5 % 2)You store 10K euros in a bank account. Compute the compound interest after 10 years at a rate of 5%.
print(10000 * (1 + 0.05) ** 10)The order of operations in Python is the same as in arithmetic. First, you compute parentheses, then exponents, then you multiply and divide (from left to right), and finally, you add and subtract (from left to right).
Convert 32 degrees Celsius into Farenheit.
\[(F - 32) \cdot 5/9 = C\]
print(32 * 9/5 + 32)Fix this code to compute a square root.
print(4 ** 1/2)Mixing strings with computations or data: f-Strings
In Python, you can utilize f-strings, which stand for formatted string literals. These allow you to seamlessly insert expressions into string literals by enclosing them with curly braces {} and adding an ‘f’ prefix to the string. F-strings offer an easily readable method for string formatting as they calculate expressions and incorporate their results directly into the string.
print(f"Louis is {23} years old.")We can perform arithmetic operations inside f-strings.
print(f"Louis is {23 / 7} dog years old.")We can avoid decimals by specifying the format of the number.
print(f"Louis is {23 / 7:.0f} dog years old.")In f"{23 / 7:.0f}", the :.0f part tells Python to display the result of 23 / 7 without any decimal places. The f in :.0f indicates that the number is a floating-point number and should be formatted accordingly. This means it will be rounded to the nearest whole number and displayed without any decimal part.
Compute a cubic root inside a f-string and display the result with three decimal digits.
print(f"The cubic root of 23 is {23 ** (1/3):.3f}.")Fix the following lines of code.
print(f"There are {365/7 weeks in a year")Complete this line of code.
print(f"The area of a square with side 5 cm is {} cm squared.")Variables in Python
In computer programming, variables are used to store, process, and manipulate data.
Let’s say we want to store 4 in the variable x, and 9 in the variable y. This is what we would do:
x = 4
y = 9Both x and y are now variables. If we look at the value of x, it should return 4.
print(x)We can write expressions with variables. Take the example \[y = f(x) = a \cdot x + b\] with \[\begin{cases} a=2 \\ b=3 \end{cases}\] We want to know the value of \(y\) when \(x = 4\), i.e. \(f(4)\).
We use \(f(x)\) to better understand what parameters are used.
a = 2
b = 3
x = 4
y = a * x + b
print(y)Given x = 1/2, compute:
\[y = \sqrt{\frac{3x - 1}{x^3}}\]
x = 0.5
y = ((3 * x - 1) / x ** 3) ** (1/2)
print(y)We can repeat the example of dog years using variables.
name = "Louis"
age = 23print(f"{name} is {age / 7:.0f} dog years old.")Remember: a variable stores the most updated score value. See what happens when we reassign the variable name. Run the cell bellow and then re-run the cell above you!
name = "Tina"In a new cell, enter your favorite number and store it in a variable called fav_num. Print out a message telling you what your favorite number plus 10 is.
fav_num = 42
print(f"My favorite number plus 10 is {fav_num + 10}.")Complete the code below to perform this Math’s “party trick”: - Pick a number between 20 and 100. - Now add your digits together. - Now subtract the total from your original number. - Finally, add the digits of the new number together. - Your answer will always be 9
my_number =
print(f"Now add your digits together: {}")
print(f"Now subtract the total from your original number: {}")
print(f"Finally, add the digits of the new number together: {}")
print("Your answer is 9.")Operations with Strings
We can concatenate or combine strings by using the addition symbols +, and the result is a new string that is a combination of both:
s = "Hello"
w = "World"
print(s + w)How would we form the sentence “Hello World”, including the space?
s = "Hello"
w = "World"
print(s + " " + w)However, you cannot concatenate strings and numbers.
print(2 + "3")However, we can multiply strings and whole numbers! This will replicate the string

print(4 * "Hello")Replicate the word “Hello” leaving a space between each word.
s = "Hello"
print(4 * (s + " "))String Methods
Strings are not just simple variables, they are objects. Objects in Python come with built-in functions, called methods. We can think of methods as special tools that objects have, and these tools allow us to perform various operations on strings, such as manipulating, searching, or formatting text. We are going to use some basic string methods.
Case Conversion
Let’s try the method s.upper(), that returns a copy of s with all alphabetic characters converted to uppercase.
A “copy” means that the original variable remains the same.
s_old = "hello" # original variable
s_new = s.upper() # new variable
print(s_old) # original variable remains unchanged
print(s_new) # new variable created with `upper`Here are some other methods for case conversion. All methods return a copy of the original string.
s = "Hello world"
print(s.lower()) # Turns all characters to lower case
print(s.capitalize()) # Turns uppercase the first letter only
print(s.swapcase()) # Swaps lowercase with uppercase and viceversa
print(s.title())Find and Replace
These methods offer different ways to search for a specified substring within the target string.
Some methods require us to input arguments. For instance, the method s.replace(<old>, <new>) takes two arguments, <old> and <new>. This method replaces a segment of the string, i.e. a substring with a new string. - The first argument <old> defines the part of the string we would like to change. - The second argument <new> is what we would like to exchange the <old> segment with.
The result is a new string with the segment changed:
s_old = "Hello world"
s_new = s_old.replace("world", "amigo")
print(s_new)If the optional <count> argument is specified, in the form of s.replace(<old>, <new>, <count>) a maximum of <count> replacements are performed, starting at the left end of s.
s_old = "foo bar foo baz foo qux"
s_new = s_old.replace("foo", "grault", 2)
print(s_new)The method s.count(<sub>) returns the number of non-overlapping occurrences of substring <sub>.
s = "pizza pizza pizza"
n = s.count("pizza")
print(n)The method s.startswith(<sub)> returns True if our string starts with the specified <sub> and False otherwise.
s = "football"
s_starts = s.startswith("foot")
s_ends = s.endswith("ball")
print(s_starts)
print(s_ends)The method s.find(<sub>) finds a sub-string <sub>. The argument is the substring you would like to find, and the output is the first index of the sequence.
s = "I am Daniel and I am your teacher"
index = s.find("am")
print(index)s = "I am Daniel and I am your teacher"
index = s.find("am")
print(s[index])If the sub-string is not in the string then the output is a negative one.
s = "Hello world"
index = s.find("Waldo")
print(index)s.rfind(<sub>) returns the highest index in s where substring <sub> is found.
s = "I am Daniel and I am your teacher"
index = s.rfind("am")
print(index)Character Classification
Methods within this category classify a string according to its character composition.
s.isalnum() returns a Boolean value, True, if s is not empty and comprises solely alphanumeric characters (which can be either letters or numbers); otherwise, it returns False.
s = "hello123"
b = s.isalnum()
print(b)s.isalpha() returns a Boolean value, True, if s is not empty and consists entirely of alphabetic characters; otherwise, it returns False.
s.isdigit() returns a Boolean value, True, if s is not empty and consists entirely of numeric digits; otherwise, it returns False.
String Formatting
The methods in this category are used to alter or improve the formatting of a string.
The s.center(<width>, <fill>) method generates a string where the content of s is centered within a field of specified total width <width>. The <fill> argument is optional, and if provided, it’s used as the padding character.
s = "hello"
s_centered = s.center(10, "-")
print(s_centered)The s.strip() method removes any leading and trailing whitespace characters from a string.
w = " hey you "
w_stripped = w.strip()
print(w_stripped)We can use the optional argument <chars> in the form s.strip(<chars>). This argument should be a string that specifies the set of characters to be removed from the leading and trailing ends of the string s.
s = "eeeeeeh Macarena"
print(s.strip("e"))Alternatively, we can use s.lstrip() to remove leading whitespaces or s.rstrip() to remove trailing whitespaces from the string s.
w = " hola amigos "
print(w.lstrip())
print(w.rstrip())Finally, the method split(<sep>) returns a list of the substrings in the string, using <sep> as the separator value.
s = "How are you doing today?"
ls = s.split(" ")
print(ls)What is a list? We will learn about them later in the course. List are sequences, just like strings, meaning we can index them.
s = "How are you doing today?"
ls = s.split(" ")
print(ls[1])Chaining Methods
Methods can be chained one after the other!
What would this do?
s = "cHaNgE Me"
print(s.lower().upper())s = "This statement is false."
print(s.upper().replace("false", "true"))s = "This statement is false."
print(s.replace("false", "true").upper())Too many methods?!

Don’t worry, you won’t need to memorize them all - AI and Google have you covered!
Need Help?
If you have any questions, feel free to reach out via email at dprecioso@faculty.ie.edu
I’m happy to help!
You can also explore the custom GPT I created for this course:
👉 Python IE Tutor
It’s tailored specifically to support your learning throughout the course.
Comments in the Code
You may be wondering what the text is in the cells above that starts with the
#hash or pound symbol. This is a comment line. It tells Python that it can ignore anything that follows on that line after the#symbol. Comments are used to help other humans understand what your code does.Try running the next cell by pressing
Shift+Enter- what do you think will happen?You can have multiple comment lines in your code, including one after another, and dispersed throughout your code:
It is good practice to include comments to make your code more understandable for yourself and others.