Programming fundamental concepts: flow

Programming fundamental concepts: flow#

This assignment is not obligatory

Components of code#

  1. Variables: Used to store data values. In Python, you don’t need to declare the type of a variable beforehand.

    x = 5
    y = "Hello"
    
  2. Data Types: Python has various data types including integers, floats, strings, lists, tuples, and dictionaries.

    a = 10          # Integer
    b = 3.14        # Float
    c = "Hello"     # String
    d = [1, 2, 3]   # List
    e = (1, 2, 3)   # Tuple
    f = {"key": "value"}  # Dictionary
    
  3. Operators: Used to perform operations on variables and values. Python supports arithmetic, comparison, logical, and bitwise operators.

    sum = x + y
    is_equal = (x == y)
    
  4. Control Structures: Used to control the flow of execution in a program. This includes conditional statements (if-else) and loops (for, while).

    if x > y:
        print("x is greater than y")
    else:
        print("y is greater than or equal to x")
    
    for i in range(5):
        print(i)
    
  5. Functions: Blocks of reusable code that perform a specific task. Functions can take inputs (parameters) and return outputs.

    def add(a, b):
        return a + b
    
  6. Modules: Files containing Python code that can be imported and used in other Python programs. This allows for code reusability and organization.

    import math
    result = math.sqrt(16)
    
  7. Comments: Used to explain code and make it more readable. Comments are ignored by the Python interpreter.

    # This is a single-line comment
    

\(\text{Task 8.1:}\)

We will first take a look at the list object. We will explore its properties and methods. First, we start by creating a list with the numbers 1 to 5 and then we will perform some basic operations on it and briefly discuss indexing and slicing.

# Create a list and print it
my_list = [1, 2, 3, 4, 5]
print(my_list)

# Access an item and print it
print(my_list[0])

# Access last item with an index other than [4] and print it
print(my_list[-1])

# Slice the list and print the result
print(my_list[1:4])

# Append an item and print the updated list
my_list.append(6)
print(my_list)

# Remove an item and print the updated list
my_list.remove(3)
print(my_list)

# Sort the list in descending order and print it
my_list.sort(reverse=True)
print(my_list)

# Get the length of the list and print it
print(len(my_list))
[1, 2, 3, 4, 5]
1
5
[2, 3, 4]
[1, 2, 3, 4, 5, 6]
[1, 2, 4, 5, 6]
[6, 5, 4, 2, 1]
5

\(\text{Task 8.2:}\)

The second task involves exploring the dictionary object. We will create a dictionary to store the names and ages of some people (Alice (20, female), Bob (25, male) and Charlie (35, male)). Then, we will perform some basic operations on the dictionary and discuss key-value pairs.

# Create a dictionary of the names and ages
ages = {
    "Alice": 30,
    "Bob": 25,
    "Charlie": 35
}

# Add gender information to the dictionary
ages_gender = {
    "Alice": {"age": 30, "gender": "female"},
    "Bob": {"age": 25, "gender": "male"},
    "Charlie": {"age": 35, "gender": "male"}
}

        
        

\(\text{Task 8.3:}\)

if/elif/else statements. Write a program that checks the age of a person (20, male) and prints whether they are a boy or girl (age < 13), teenager (13 <= age < 20), or adult (age > 20).

# Use conditional statements
my_age = 20
my_gender = "male"


if my_age < 13:
    if my_gender == "male":
        print("You are a boy.")
    else:
        print("You are a girl.")
elif my_age < 20:
    print("You are a teenager.")
else:
    print("You are an adult.")
You are an adult.

\(\text{Task 8.4:}\)

The final structure we will investigate is the for loop. For loops allow us to iterate over a sequence (like a list or a string) and perform an action for each item in that sequence.

list = [1, 2, 3, 4, 5]

# iterate through the list and print each element

# iterate through the list and print each element multiplied with 2

hello = 'hello'
# iterate through the string and print each character

my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
# iterate through the list to find the maximum value and print the final maximum value
# iterate through the list and print each element
for i in [1, 2, 3, 4, 5]:
    print(i)


# iterate through the list and print each element multiplied with 2
for i in [1, 2, 3, 4, 5]:
    print(i*2)

hello = 'hello'
# iterate through the string and print each character
for i in hello:
    print(i)

# iterate through the list to find the maximum value and print the final maximum value

my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
current_max = my_list[0]
for num in my_list:
    if num > current_max:
        current_max = num
print(f"The maximum value in the list is {current_max}")
1
2
3
4
5
2
4
6
8
10
h
e
l
l
o
The maximum value in the list is 9

\(\text{Task 8.5:}\)

Finally, let’s apply loops and if statements on our dictionary with Alice, Bob and Charlie.

# Iterate through the dictionary with a loop printing the name and age

# Iterate through the new dictionary printing both name, ages and gender

# Iterate through the dictionary and print all males younger than 30
# Iterate through the dictionary with a loop printing the name and age
for name in ages:
    print(f"{name} is {ages[name]} years old.")


# Iterate through the new dictionary printing both name, ages and gender
for name in ages_gender:
    print(f"{name} is {ages_gender[name]['age']} years old and is {ages_gender[name]['gender']}.")
    
# Iterate through the dictionary and print all males younger than 30
for name in ages_gender:
    if ages_gender[name]['gender'] == 'male' and ages_gender[name]['age'] < 30:
        print(f"{name} is a male younger than 30.")
Alice is 30 years old.
Bob is 25 years old.
Charlie is 35 years old.
Alice is 30 years old and is female.
Bob is 25 years old and is male.
Charlie is 35 years old and is male.
Bob is a male younger than 30.

By Berend Bouvy, Delft University of Technology. CC BY 4.0, more info on the Credits page of Workbook.