Skip to content

Introduction to Python

1. Basic Python

graph TD
    PY[Python variables] --> PR[1.1 Primitive variables]
    PY[Python variables] --> DS[1.2 Data structures]
    PR --> INT{integer}
    PR --> FLT{float}
    PR --> STR{string}
    PR --> BOL{boolean}
    DS --> LST{list}
    DS --> DCT{dictionary}
    DS --> TPL{tuple}
    DS --> SET{set}

1.1 Variable types

Variable types in Python represent simple, fundamental data types directly supported by the programming language, providing the building blocks for more complex data structures and operations.

Variable Declaration Example
Integer int 128; 1
Float float 1.5; 14.
String str "This is a string."; "126"; ",.$"
Boolean bool True; False

Integer

Example of Integer Variables:

  • a = 1
  • b = -200
  • c = 30000

a = 1
b = -200
c = 399999

print(a)
print(b)
print(c)
1
-200
399999

Float

Example of Float Variables:

  • a = 1.
  • b = -3.5
  • c = 548.36

a = 1.
b = -3.5
c = 548.36

print(a)
print(b)
print(c)
1.0
-3.5
548.36

String

Example of String Variables:

  • a = "The Witcher."
  • b = "12/09/2023"
  • c = "56.1"
a = "The Witcher."
b = "12/09/2023"
c = "56.1"
d = ""

print(a)
print(b)
print(c)
print(d)

The Witcher.
12/09/2023
56.1

Boolean

Example of Boolean Variables:

  • a = True
  • b = False
a = True
b = False

print(a)
print(b)

True
False

1.2 Data structures

Python data structures are essentially containers for different kinds of data.

Variable Declaration Example
List list [1, "Hi", "23", True]
Dictionary dict {"element_a": 3, "other": False}
Tuple tuple (1, "hi", True)
Set set {"a", 4, True, 9}
Example of a combined data structure in real life
song = {
        "title": "Bohemian Rhapsody",
        "artist": "Queen",
        "album": {
            "name": "A Night at the Opera",
            "release_year": 1975,
            "tracks": 12
        },
        "duration": "6:07",
        "genre": ["Rock", "Progressive Rock"],
        "ratings": {
            "five_stars": 3000,
            "four_stars": 2000,
            "three_stars": 500,
            "two_stars": 100,
            "one_star": 50
        },
        "is_explicit": False,
        "featured_artists": ["Freddie Mercury", "Brian May", "Roger Taylor", "John Deacon"]
}

List

A list in Python is a collection of ordered elements that can contain different data types and be modified, allowing you to store and manage multiple values in a single variable.

More about lists

Lists are mutable, allowing you to modify, add, or remove elements after their creation. Lists are ordered, meaning the elements are stored in a specific sequence, and you can access elements using their index.

Example of List Variables:

  • a = [1, 5.2, 3.]
  • b = ["Sara", "Jorge", ""]
  • c = ["Paseo de la Castellana", 136, True, "5º D"]
  • z = []
a = [1, 5.2, 3.]
b = ["Sara", "Jorge", ""]
c = ["Paseo de la Castellana", 136, True, "5º D"]
z = list()

print(a)
print(b)
print(c)
print(z)

[1, 5.2, 3.0]
['Sara', 'Jorge', '']
['Paseo de la Castellana', 136, True, '5º D']
[]

Dictionary

A dictionary in Python is a collection of key-value pairs that allows you to store and retrieve data using unique keys, providing a way to organize and access data based on custom labels or identifiers.

More about dictionaries

Dictionaries are mutable, meaning you can modify, add, or remove key-value pairs after their creation. However, dictionaries are unordered, so the order of items may not be preserved when iterating over the dictionary.

Example of Dictionary Variables:

  • a = {"a": 1, "b": 3.2, "c": }
  • b = {5648: "@rachel", "test": True, "user": [2, 5, 63]}
  • c = {"title": "The Matrix", "year": 1999, "genre": ["Action", "Sci-Fi], "rating": 8.7}
  • z = {}
a = {"a": 1, "b": 3.2, "c": False}
b = {5648: "@rachel", "test": True, "user": [2, 5, 63]}
c = {"title": "The Matrix", "year": 1999, "genre": ["Action", "Sci-Fi"], "rating": 8.7}
z = dict()

print(a)
print(b)
print(c)
print(z)

{'a': 1, 'b': 3.2, 'c': False}
{5648: '@rachel', 'test': True, 'user': [2, 5, 63]}
{'title': 'The Matrix', 'year': 1999, 'genre': ['Action', 'Sci-Fi'], 'rating': 8.7}
{}

Tuple

A tuple in Python is an immutable ordered collection of elements that can contain different data types, separated by commas and enclosed in parentheses, providing a way to group related data together.

Tuples Vs. Lists

Tuples are immutable, meaning their elements cannot be changed or modified after creation, making them suitable for situations where data should not be altered. Tuples are faster than lists, allowing for optimized memory allocation and faster access.

Example of Tuple Variables:

  • a = (1, 2, 3)
  • b = ("apple", 10, True)
  • c = (3.14, "pie", [1, 2, 3], {"name": "John", "age": 30})
a = (1, 2, 3)
b = ("apple", 10, True)
c = (3.14, "pie", [1, 2, 3], {"name": "John", "age": 30})
z = tuple()

print(a)
print(b)
print(c)
print(z)

(1, 2, 3)
('apple', 10, True)
(3.14, 'pie', [1, 2, 3], {'name': 'John', 'age': 30})
()

Set

A set in Python is a collection of unique and unordered elements that allows you to perform various set operations, such as union, intersection, and difference.

More about sets

Sets are defined using curly braces {} or the built-in set() function. Duplicate elements are automatically removed, and the order of elements is not guaranteed in a set.

Example of Set Variables:

  • a = {1, 2, 3}
  • b = {4, 5, 6}
  • c = {True, "hello", 3.14, (1, 2)}
  • z = set()
a = {1, 2, 3}
b = {4, 5, 6}
c = {True, "hello", 3.14, (1, 2)}
z = set()

print(a)
print(b)
print(c)
print(z)

{1, 2, 3} {4, 5, 6} {3.14, True, (1, 2), 'hello'} set()

1.3 Comments

Comments in Python are lines of text that are ignored by the interpreter and are used to provide explanations, clarifications, or notes within the code.

Tip about comments

In Python, it is possible to write comments using the Spanish language, including special characters. However, it is generally recommended to avoid using accents in comments to ensure compatibility and readability across different platforms and text editors.

# This is a comment

# Picture attributes
pic = {"picture_name": "My doggy", "date": "12/02/2023", "likes": 1658}

1.4 Declare variables

Naming convention

The Python naming convention for variables and files is camel case, where punctuation is removed, spaces are replaced by single underscores, and the letters are in lower case.

# variable
this_is_a_variable = "camel case"

# examples
user_name = "Paula"
video_game = "What Remains of Edith Finch"
has_views = True

Assignment methods

Is the process of assigning or storing data to a variable, enabling the programmer to give a meaningful name to the data and easily access and manipulate it throughout the program.

python-variables

  • Direct assignment: content.
    song = "Give it all"
    duration = 3.16
    
  • Multiple assignment:
    song, duration = "Give it all", 3.16
    
  • Multiple variables assignment:

    user = name = "Jorge"
    

  • User input assignment:

    name = input("Enter your name: ")
    age = input("Enter your age: ")
    

1.5 Print

To display output messages or values to the user on the console or terminal.

Tip about print

Remember that print() is an essential tool for beginners and experienced developers alike, making it easier to interact with your programs and see what's happening at each step.

Basic print

print(Hello, World!)

Hello, World!

Variable print

# Declaring variables
movie = "Barbie"
rating = 9.

# Printing variables
print(movie)
print(rating)

Barbie
9.0

In-line print

# Declaring variables
movie = "Barbie"
rating = 9.

# Printing variables
print(movie, rating)

Barbie
9.0

Concat print

# Declaring variables
movie = "Barbie"
rating = 9.

# Printing variables
print("The movie " + movie + " has a rating of: " + str(rating))

The movie Barbie has a rating of: 9.0

Formatted string literals (f-string)

# Declaring variables
movie = "Barbie"
rating = 9.

# Printing variables
print(f"The movie {movie} has a rating of {rating}")

The movie Barbie has a rating of: 9.0

1.6 Type

Is used to determine the data type of a value or variable, such as whether it is an integer, string, boolean, etc.

# Declaring variables
song = "Yeah Yeah Yeah"
duration = 3.25
is_suitable = True

# Get the types
song_type = type(song)
duration_type = type(duration)
is_suitable_type = type(is_suitable)

# Ouput
output = f"""Song: {song} - [{song_type}]
Duration: {duration} - [{duration_type}]
Suitable: {is_suitable} - [{is_suitable_type}]
"""

print(output)
Song: Yeah Yeah Yeah - [<class 'str'>]
Duration: 3.25 - [<class 'float'>]
Suitable: True - [<class 'bool'>]

1.7 Interact with files in Python

Read a text file

text_file = open('/Users/pankaj/filename.txt','r', encoding='utf-8')
# some file operations here
text_file.read()

text_file.close()
When you open a file in Python, it’s extremely important to close the file after you make the changes. This saves any changes that you’ve previously made, removes the file from the memory, and prevents any further reads or writes within the program.

Read a CSV file

import csv
with open('chocolate.csv') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        print(row)

2 Operators

2.1 Numeric operators

Operator Statement
Math operations 1+3 , 5-2 , 10/5, 2*4
Exponent 2**3
String -> integer/float int("24")
Reminder 10%3
Max, min & sum max(lst), min(lst), sum(lst)
Absolute abs(-3)
Round round(3.2153, 1)
Floor Division 12//6

Basic math operations

money = 1258
employees = 3
iva = 1.21

# Add employee
employees += 1  # Is like employees = employees + 1

# Get reminder
print(money/employees)
print(money*iva)

314.5
1522.18

Exponent operations

three_power_three = 3**3
three_sqrt_three = 3**.5

# Exponent operation
print(three_power_three)
print(round(three_sqrt_three, 2))

27
1.73

String to integer/float

age_str = "25"

# Get integer
age_int = int(age_str)
age_float = float(age_str)

# Print types
print(type(age_str))
print(type(age_int))
print(type(age_float))

<class 'str'>
<class 'int'>
<class 'float'>

Reminder

money = 1258
employees = 4

# Get reminder
print(money%employees)

2

Max, min & sum value

scores = [2.2, 3., 5.7, 9.1, 6., 3.2, -3.1, 9.4, -1.5, -3.6]

# Get max and min
print(max(scores))
print(min(scores))
print(sum(scores))

9.4
-3.6
30.4

Absolute value

number = -3.5

# Get max and min
print(abs(number))

3.5

Round value

number = 1.32586

# Round to 2 decimals
number_round = round(number, 2)
print(number_round)

1.32

Floor Division

one, two = 10//7, 12/8

# Output results
print(f"10/7 -> {one} ({10/7})")
print(f"12/8 -> {two} ({12/8})")

10/7 -> 1 (1.4285714285714286) 12/8 -> 1.5 (1.5)

2.2 String operators

Operator Statement
Integer/float to string str(31.2)
Length of a string len("Number of characters")
Concatenate strings "This" + " is" + " concatenation."
Escape characters "\"Hello,\" she said."
Upper, Lower, Title cases "My NaMe iS aLiCIa".lower()
String to list "Welcome to the dark side".split()
Split string by "This;is;a;string".split(";")
List to string " ".join(["Hello", "World"])
New line and tabulator "First line\n Second line"
Check substring "a" in "This is a test"
Check only letters "abcdefghijklmn".isalpha()
Multiply strings "Three"*3
Replace string "Thiz iz a ztring".replace("z", "s")
Strip text " Hi ".strip()
Find index "This is a string".find("s")

Integer/float to string

time_int = 31
time_float = 31.25

# Get integer
time_int_str = str(time_int)
time_float_str = str(time_float)

# Print types
print(time_int_str, type(time_int_str))
print(time_float_str, type(time_float_str))

31 <class 'str'>
31.25 <class 'str'>

Length of a string

song = "Back in Black"
password = "4r236TY5S5F65H6xjt"

# Get lenghts
print(len(song))
print(len(password))

13
18

Concatenate strings

song = "doomsday"
artist = "sad face."

# Concatenate string
message = "The song " + song + " is made by " + artist
print(message)

The song doomsday is made by sad face.

Escape characters

# Escape symbols
message = "Somtimes he goes by \"chuck\""
print(message)

Somtimes he goes by "chuck"

Upper, Lower, Title cases

message = "Hello, world"

# Upper, Lower, Title cases
message_low = message.lower()
message_up = message.upper()
message_title = message.title()

# Print messages
print(f"Low -> {message_low}")
print(f"Up -> {message_up}")
print(f"Title -> {message_title}")

Low -> hello, world
Up -> HELLO, WORLD
Title -> Hello, World

String to list

message = "This is a String"
print(message.split())

['This', 'is', 'a', 'String']

Split string by

message = "This-is-a-long-string"
print(message.split('-'))

['This', 'is', 'a', 'long', 'string']

List to string

message = ['This', 'is', 'a', 'long', 'string']
print(" ".join(message))

This is a long string

New line and tabulator

new_line = "First line\nNew line"
tabulator = "\tTabulator line"

# Print
print(new_line)
print(tabulator)

First line
New line
 Tabulator line

Check substring

code = "The code is: 5223565-K"

# Check K is in code
check = "K" in code
print(check)

True

Check only letters

is_alpha = "AlphaCode"

# Check alphanumeric
check = is_alpha.isalpha()
print(check)

True

Multiply strings

pattern = "-"

# Print
multi = pattern * 5
print(multi)

-----

Replace string

message = "Thiz iz a ztring"

# Replace string
message = message.replace("z", "s")
print(message)

This is a string

Strip text

message = "    Strip message    "

# Strip message
message_strip = message.strip()

# Comparison
print(f"{message} ({len(message)})")
print(f"{message_strip} ({len(message_strip)})")

    Strip message    (21)
Strip message (13)

Find index

message = "This is a string"
letter = "s"

# Find first letter index
idx = message.find(letter)
print(f"{message} (First \"{letter}\" is in position: {idx})")

This is a string (First "s" is in position: 3)

2.3 List operators

Operator Statement
Element at index lst[2]
Get last element lst[-1]
Modify item lst[1] = 'x'
Add item at the end lst.append('a')
Slicing a list lst[1:3]
Order a list sorted(lst)
List length len(lst)
List from range list(range(1, 5))
Reverse a list lst.reverse()
Remove item lst.remove(5)
Count item lst.count('#')
Entwine lists zip(lst_a, lst_b)
Enumerate list enumerate(lst)

Element at index

Indexing in python

Remember that indexing in Python starts from 0, so the first element is at index 0, the second at index 1, and so on.

# List of planets
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]

# Extracting value at index 2 (which is the third element in the list)
value = planets[2]

print(value)

Earth

Get last element

To get the last element from a list in Python, you can use negative indexing. Negative indices count elements from the end of the list, where -1 represents the last element, -2 represents the second-to-last element, and so on.

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]

# Getting the last element using the negative index
last_planet = planets[-1]
penultimate_planet = planets[-2]

print(last_planet)
print(penultimate_planet)

Neptune Uranus

Modify item

Suppose we want to modify the name of a planet, let's say "Mars" to "Red Planet." We can do this by using the index to access the element and then assigning the new name to it.

# Original list of planets
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]

# Modifying the name of a planet
index_of_mars = 3  # Index of "Mars" is 3
new_name = "Red Planet"
planets[index_of_mars] = new_name

# Updated list of planets
print(planets)

["Mercury", "Venus", "Earth", "Red Planet", "Jupiter", "Saturn", "Uranus", "Neptune"]

Add item at the end

If we want to add the planet "Pluto" at the end of the list, we can use the append() method.

# Original list of planets
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]

# Adding "Pluto" at the end of the list using append()
planets.append("Pluto")

# Updated list of planets
print(planets)

["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"]

Slicing a list

Imagine we want to create a new list containing the planets before "Earth," including "Earth," by using slicing.

More about slicing lists

When using slicing in Python lists, the slice includes all elements up to, but not including, the index specified as the end of the slice.

# Original list of planets
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]

# Slicing to include planets before and including "Earth"
sliced_planets = planets[:2 + 1]

# Sliced list of planets
print(sliced_planets)

["Mercury", "Venus", "Earth"]

Advanced code

If we don't want to insert the index of the planet Earth manually we can use the index method.

sliced_planets = planets[:planets.index("Earth") + 1]

Order a list

In this example, the sorted() function is used to sort the list of planets alphabetically, and the sorted result is stored in the sorted_planets variable.

# List of planets
planets = ["Mercury", "Venus", "Mars", "Earth", "Jupiter", "Saturn", "Uranus", "Neptune"]

# Sort the planets alphabetically
sorted_planets = sorted(planets)

# Print the sorted list of planets
print(sorted_planets)

['Earth', 'Jupiter', 'Mars', 'Mercury', 'Neptune', 'Saturn', 'Uranus', 'Venus']

List length

In this example, the len() function is used to count the number of items in a list.

# List of planets
planets = ["Mercury", "Venus", "Mars", "Earth", "Jupiter", "Saturn", "Uranus", "Neptune"]

# Sort the planets alphabetically
n_planets = len(planets)

# Print the sorted list of planets
print(f"There are {n_planets} planets in the solar system.")

There are 9 planets in the solar system.

List from range

# Using range(2, 3) to create a list with a single element
list1 = list(range(2, 4))

# Using range(6) to create a list with numbers from 0 to 5
list2 = list(range(6))

# Print the lists
print(list1)
print(list2)

[2, 3]
[0, 1, 2, 3, 4, 5]

Reverse a list

There are two methods to reverse a list, using the lst.reverse() function and slicing lst[::-1].

Reverse() Vs. [::-1]

The reverse() method modifies the original list in place, while slicing [::-1] creates a new reversed list without modifying the original one.

# List of planets in the solar system
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]

# Method 1: Using reverse()
reversed_planets_1 = planets.copy()
reversed_planets_1.reverse()

# Method 2: Using slicing [::-1]
reversed_planets_2 = planets[::-1]

# Print the reversed lists
print("Reversed using reverse():", reversed_planets_1)
print("Reversed using slicing [::-1]:", reversed_planets_2)

Reversed using reverse(): ['Neptune', 'Uranus', 'Saturn', 'Jupiter', 'Mars', 'Earth', 'Venus', 'Mercury']
Reversed using slicing [::-1]: ['Neptune', 'Uranus', 'Saturn', 'Jupiter', 'Mars', 'Earth', 'Venus', 'Mercury']

Remove item

The remove() method is used to remove the specified element ("Pluto" in this case) from the list planets. After calling remove("Pluto"), "Pluto" is no longer present in the list.

# List of planets in the solar system
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"]

# Remove "Pluto" from the list
planets.remove("Pluto")

# Print the updated list of planets
print(planets)

['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

Count item

In this example, the count() function is used to count the occurrences of the element "Earth" in the planets list. The count is then stored in the variable earth_count and printed to the console. As you can see, "Earth" appears twice in the list, so the count is 2.

# List of planets in the solar system
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto", "Earth"]

# Count the number of occurrences of "Earth" in the list
earth_count = planets.count("Earth")

# Print the count
print("The number of times 'Earth' appears in the list:", earth_count)

The number of times 'Earth' appears in the list: 2

Entwine lists

In this example, the zip() function is used to combine the planets list and the distances list into a new list called planet_distances. Each tuple in the planet_distances list contains a planet name and its corresponding distance from the Sun. The list() function is used to convert the zip object into a list for easy printing.

# Lists of planets and their distances from the Sun (in millions of kilometers)
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter"]
distances = [57.9, 108.2, 149.6, 227.9, 778.3]

# Use zip to combine the two lists into a list of tuples
planet_distances = list(zip(planets, distances))

# Print the combined list
print(planet_distances)

[('Mercury', 57.9), ('Venus', 108.2), ('Earth', 149.6), ('Mars', 227.9), ('Jupiter', 778.3)]

Enumerate list

In this example, enumerate(planets) returns an iterator that produces tuples containing the index and planet from the planets list.

# List of planets
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter"]

# Get an iterator for the planets list along with their indices using enumerate()
enum_planets = enumerate(planets)
print(list(enum_planets))

[(0, 'Mercury'), (1, 'Venus'), (2, 'Earth'), (3, 'Mars'), (4, 'Jupiter')]

2.4 Dictionary operators

Operator Statement
Add key dct['new_key'] = True
Add multiple keys dct.update({'key1' = 1, 'key2' = False})
Overwrite value dct['key'] = False
Extract value dct['new_key']
Delete key and value del dct['key_to_delete']
Keys & values list dct.keys(), dct.values(), dct.items()
Check key "key" in market_value
Pair lists to dict dict(zip(dct_1, dct_2))

Add key

# Dictionary representing market value of stock tech companies
market_value = {
    "Apple": 2345.67,
    "Microsoft": 1765.89,
    "Amazon": 3012.45,
    "Google": 2789.34,
    "Facebook": 1890.56
}

# Add key: Add a new company and its market value
market_value["Tesla"] = 1899.32
print(market_value)

{'Apple': 2345.67, 'Microsoft': 1765.89, 'Amazon': 3012.45, 'Google': 2789.34, 'Facebook': 1890.56, 'Tesla': 1899.32}

Add multiple keys

# Dictionary representing market value of stock tech companies
market_value = {
    "Apple": 2345.67,
    "Microsoft": 1765.89,
    "Amazon": 3012.45,
    "Google": 2789.34,
    "Facebook": 1890.56
}

# Add multiple keys: Add multiple new companies and their market values
market_value.update({"Netflix": 2156.78, "Adobe": 1654.32})
print(market_value)

{'Apple': 2345.67, 'Microsoft': 1765.89, 'Amazon': 3012.45, 'Google': 2789.34, 'Facebook': 1890.56, 'Netflix': 2156.78, 'Adobe': 1654.32}

Overwrite value

# Dictionary representing market value of stock tech companies
market_value = {
    "Apple": 2345.67,
    "Microsoft": 1765.89,
    "Amazon": 3012.45,
    "Google": 2789.34,
    "Facebook": 1890.56
}
print(f"Before: {market_value}")

# Overwrite value: Update the market value of a company
market_value["Apple"] = 2367.98
print(f"After: {market_value}")

Before: {'Apple': 2345.67, 'Microsoft': 1765.89, 'Amazon': 3012.45, 'Google': 2789.34, 'Facebook': 1890.56} After: {'Apple': 2367.98, 'Microsoft': 1765.89, 'Amazon': 3012.45, 'Google': 2789.34, 'Facebook': 1890.56}

Extract value

market_value = {
    "Apple": 2345.67,
    "Microsoft": 1765.89,
    "Amazon": 3012.45,
    "Google": 2789.34,
    "Facebook": 1890.56
}

# Extract value: Get the market value of a specific company
google_value = market_value["Google"]
print("Market value of Google:", google_value)

Market value of Google: 2789.34

Delete key and value

market_value = {
    "Apple": 2345.67,
    "Microsoft": 1765.89,
    "Amazon": 3012.45,
    "Google": 2789.34,
    "Facebook": 1890.56
}

# Delete key and value: Remove a company and its market value from the dictionary
del market_value["Facebook"]

{'Apple': 2345.67, 'Microsoft': 1765.89, 'Amazon': 3012.45, 'Google': 2789.34}

Extract keys & values

# Dictionary representing market value of stock tech companies
market_value = {
    "Apple": 2345.67,
    "Microsoft": 1765.89,
    "Amazon": 3012.45,
    "Google": 2789.34,
    "Tesla": 1899.32,
    "Netflix": 2156.78,
    "Adobe": 1654.32
}

# Using .keys() to get a view of keys
keys_view = market_value.keys()

# Using .values() to get a view of values
values_view = market_value.values()

# Using .items() to get a view of (key, value) pairs
items_view = market_value.items()

# Print the views
print("Keys view:", keys_view)
print("Values view:", values_view)
print("Items view:", items_view)

Keys view: dict_keys(['Apple', 'Microsoft', 'Amazon', 'Google', 'Tesla', 'Netflix', 'Adobe'])
Values view: dict_values([2345.67, 1765.89, 3012.45, 2789.34, 1899.32, 2156.78, 1654.32])
Items view: dict_items([('Apple', 2345.67), ('Microsoft', 1765.89), ('Amazon', 3012.45), ('Google', 2789.34), ('Tesla', 1899.32), ('Netflix', 2156.78), ('Adobe', 1654.32)])

Check key

market_value = {
    "Apple": 2345.67,
    "Microsoft": 1765.89,
    "Amazon": 3012.45,
    "Google": 2789.34,
    "Facebook": 1890.56
}

# Check key: Check if a company is in the dictionary
if "Microsoft" in market_value:
    print("Microsoft is in the dictionary.")
else:
    print("Microsoft is not in the dictionary.")

Microsoft is in the dictionary.

Pair lists to dict

# Lists of tech companies and their market values
tech_companies = ["Apple", "Microsoft", "Amazon", "Google", "Tesla"]
market_values = [2345.67, 1765.89, 3012.45, 2789.34, 1899.32]

# Create a dictionary by pairing tech_companies with market_values
market_value_dict = dict(zip(tech_companies, market_values))

# Print the resulting dictionary
print(market_value_dict)

{'Apple': 2345.67, 'Microsoft': 1765.89, 'Amazon': 3012.45, 'Google': 2789.34, 'Tesla': 1899.32}

3. If, elif, else statements

The if statement in Python is used to make decisions in code by checking whether a condition is true or false, and executing specific blocks of code based on the evaluation of the condition.

Indentation tip

Indentation in an if statement is crucial in Python because it defines the block of code that should be executed if the condition is true.

Operator Condition
True always runs
False never runs
a > b a greater than b
a >= b a greater or equal to b
a < b a smaller than b
a <= b a smaller or equal to b
a == b a equal to b
a != b a not equal to b
a in b string in b
not(a in b) string not in b

reminder

You can add multiple conditions statement like:

if a > b and b != 0:
or even more complex:
if (check is True and temp = 30) or key == "alohomora":

3.1 if else

score = 75

if score >= 60:
    print("Congratulations! You have passed the exam.")
else:
    print("Unfortunately, you did not pass the exam. Better luck next time.")

Congratulations! You have passed the exam.

3.2 if, elif, else

number = 0

# Check the number and provide a corresponding message
if number > 0:
    print("The number is positive.")
elif number < 0:
    print("The number is negative.")
else:
    print("The number is zero.")

The number is zero.

3.3 Nested if, else

Let's consider a scenario where we have a user registration process, and we want to check the age of the user and whether they have provided all the required information.

  1. Check if the user's age is 18 or above using the outer if statement
  2. check if the user has provided both their name and email
age = 25
has_name = True
has_email = False

if age >= 18:
    if has_name and has_email:
        print("User registration successful!")
    else:
        print("Please provide both your name and email to complete the registration.")
else:
    print("Sorry, you must be at least 18 years old to register.")

Please provide both your name and email to complete the registration.

4. Loops

4.1 For loop

A for loop in Python is a way to repeat a set of instructions for each item in a collection (like a list or a string), allowing you to perform the same task on multiple elements one by one.

Iterating a list

# List of planet names
planet_names = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

# Iterating over the list and printing each planet name in capital letters
print("NASA's Planets:")
for planet in planet_names:
    planet_capital = planet.upper()
    print(planet, planet_capital)

NASA's Planets:
Mercury MERCURY
Venus VENUS
Earth EARTH
Mars MARS
Jupiter JUPITER
Saturn SATURN
Uranus URANUS
Neptune NEPTUNE

Iterating a string

# Tweet text
tweet = "Having a great time at the beach with friends. #summerfun #beachlife"

# Iterate over each letter an count the number of hashtags
n_hashtags = 0
for letter in tweet:
    if "#" == letter:
        n_hashtags += 1

print(f"Number of Hashtags found: {n_hashtags}")

Number of Hashtags found: 2

Iterating a range

# DNA sequence as a list of nucleotides
dna_sequence = ['A', 'T', 'G', 'C', 'A']

# Iterate over each position in the DNA sequence using range(10)
for i in range(len(dna_sequence)):
    nucleotide = dna_sequence[i]
    position = i + 1
    print(f"Position {position}: {nucleotide}")

Position 1: A
Position 2: T
Position 3: G
Position 4: C
Position 5: A

Enumerating list

This example is the same from the previous one but using enumerate. Enumerate helps you iterate over a sequence (like a list, tuple, or string) while also keeping track of the index of each element in the sequence.

Enumerate Vs. range

The advantage of using enumerate instead of range in the previous code is that enumerate provides a more concise and expressive way to access both the elements and their corresponding indices in a sequence. It simplifies the code and makes it more readable.

# DNA sequence as a list of nucleotides
dna_sequence = ['A', 'T', 'G', 'C', 'A']

# Iterate over each position in the DNA sequence using range(10)
for i, nucleotide in enumerate(dna_sequence):
    position = i + 1
    print(f"Position {position}: {nucleotide}")

Position 1: A
Position 2: T
Position 3: G
Position 4: C
Position 5: A

Advanced for loop

List comprehension is a concise way to create a new list in Python by performing some operation on each item of an existing list or iterable. It allows you to combine a for loop and an expression in a single line to generate a new list efficiently.

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]

# Example 1: Create a new list with the lengths of each planet name
planet_name_lengths = [len(planet) for planet in planets]

# Example 2: Create a new list with uppercase planet names
uppercase_planets = [planet.upper() for planet in planets]

print(planet_name_lengths)
print(uppercase_planets)
[7, 5, 5, 4, 7, 6, 6, 7]
['MERCURY', 'VENUS', 'EARTH', 'MARS', 'JUPITER', 'SATURN', 'URANUS', 'NEPTUNE']

4.2 While loop

A while loop in Python is a way to repeatedly execute a block of code as long as a certain condition is true. It keeps running the instructions until the condition becomes false, allowing you to perform tasks until a specific condition is met.

While Vs. for loops

A while loop should be used in Python when the number of iterations is not known beforehand, and the loop needs to continue as long as a certain condition remains true. It is ideal for scenarios where the loop's termination depends on real-time or user input conditions.

clothes = ["T-shirts", "Jeans", "Dresses", "Jackets", "Shoes", "Hats"]

# Using a while loop to print the available clothes
choice = "yes"
counter = 0

# Welcome print message
print("Welcome to the Fashion Clothes Store!")

while choice == "yes" and counter < len(clothes):
    print(clothes[index])
    counter += 1
    choice = input("Do you want to see more clothes? (yes/no): ")
    choice = choice.lower()

print("Thank you for visiting our Fashion Clothes Store!")

Welcome to the Fashion Clothes Store! T-shirts Do you want to see more clothes? (yes/no): Yes T-shirts Do you want to see more clothes? (yes/no): No Thank you for visiting our Fashion Clothes Store!

-> Start coding

You can do the exercises in Google Colab or in Jupyter Lab

Google Colab

Open the 11_introduction_to_python.ipynb notebook to start doing the exercises.

reminder

Remember to fork the exercise repository and save your solved notebooks in your forked repo.

Jupyter Lab

WIP