Python is a programming language that is easy to read and write. In this notebook, you will learn the basics and then move on to more advanced concepts like functions, lists, and dictionaries.
1. The print() function
It is used to display a message on the screen.
Example:
print("Hello, world!")
Exercise 1: Write a program that prints your name.
2. Variables
A variable is a container that can store a value.
Example:
name = "Luca"
age = 13
Exercise 2: Create two variables, one with your name and one with your age, then print them.
3. Keyboard Input
With the input()
function we can ask the user to enter data.
Example:
name = input("What is your name? ")
print("Hello", name)
Exercise 3: Ask the user for their favorite color and print it.
4. Mathematical Operations
Python can perform calculations:
+
addition-
subtraction*
multiplication/
division**
exponentiation
Example:
a = 5
b = 2
print(a + b)
Exercise 4: Ask the user for two numbers and print the sum.
5. Conditions (if - else)
With if
we can decide what to do depending on a condition.
Example:
age = int(input("How old are you? "))
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
Exercise 5: Ask for a number and print whether it is even or odd.
6. Loops (for - while)
For loop
for i in range(1, 6):
print(i)
While loop
i = 1
while i <= 5:
print(i)
i += 1
Exercise 6: Print numbers from 1 to 10 using for
.
Exercise 7: Print even numbers from 2 to 20 using while
.
7. Comments
Comments explain the code but are not executed.
# This is a comment
Exercise 8: Rewrite one of your programs adding a comment to each line.
INTERMEDIATE LEVEL
8. Lists
A list is a sequence of values enclosed in square brackets.
Example:
fruits = ["apple", "banana", "kiwi"]
print(fruits[0]) # prints "apple"
Exercise 9: Create a list with 5 animals and print the second item.
9. Looping through a list
You can use a for
loop to read each item in the list.
for fruit in fruits:
print(fruit)
Exercise 10: Write a program that prints all the items in a list of sports.
10. Functions
A function is a block of code that can be reused.
Example:
def greet(name):
print("Hello", name)
greet("Julia")
Exercise 11: Write a function that takes two numbers and prints their sum.
11. Dictionaries
A dictionary is a collection of key-value pairs.
Example:
student = {"name": "Anna", "age": 13}
print(student["name"])
Exercise 12: Create a dictionary with information about a city (name, population, country).
12. Final Challenge (optional)
Write a program that:
- Asks the user for two numbers
- Adds them and calculates the average
- Prints a different message if the average is greater or less than 10
Exercise 13: Try using if
, input()
, print()
and math operations.