Tag Archives: Python 3 Exercises for Beginners

Sorting an Array of Tuples in Python

In this video I show a nice way to work with Data in Python, by using Tuples.

I also show how to easily and conveniently sort the Data based on your preferred criteria by using lambdas.

What happens if we have accents, ç, Ç etc…

You can download the code from:

https://gitlab.com/carles.mateo/python_combat_guide/-/blob/master/src/arrays_with_tuples.py

A simple example to grab the title of a page using Python and beautifulsoup4

A really simple code I added to my Python 3 Exercises for Beginners book, to grab the title of a Web page.

from urllib import request
from bs4 import BeautifulSoup

s_url = "https://blog.carlesmateo.com/movies-i-saw/"
s_html = request.urlopen(s_url).read().decode('utf8')

o_soup = BeautifulSoup(s_html, 'html.parser')
o_title = o_soup.find('title')

print(o_title.string) # Prints the tag string content

# Another possible way
if o_soup.title is not None:
    s_title = o_soup.title.string
else:
    s_title = o_title.title
print(s_title)

I also included this code in the code repository for Python 3 Combat Guide book.

https://gitlab.com/carles.mateo/python_combat_guide/-/blob/master/src/html_parse_beautifulsoup4.py

Some graphics with matplotlib

Recently I showed you how to generate a Cloud Tag.

You may like some of other graphs that can be easily generated with matlib package.

I’ve been always working on BackEnd and APIs and I don’t work on FrontEnd, although I programmed some videogames by myself and I’ve fixed some huge bugs in JavaScript in some of the companies I work, but they considered myself the last resource, so I would fix a FrontEnd bug when nobody else could. But even if you work 99.9% of your time in BackEnd, Scaling, Architecture… like me, it is useful being able to draw graphics, for example, when you create a tool that shows the number of players per minute, and its evolution over time, or web visitors in real time, etc…

I wrote this article with two simple examples for my book Python 3 exercises for beginners.

You can find this source code here:

https://gitlab.com/carles.mateo/python-classes/-/blob/main/2021-09-10/draw_points.py


import matplotlib.pyplot as plt

a_points1 = [7, 3, 15, 5, 10, 2, 9]
a_points2 = [2, 4, 9, 2, 7, 8, 4]

plt.plot(a_points1)
plt.plot(a_points2)

plt.show()

We can also add customized axis:

https://gitlab.com/carles.mateo/python-classes/-/blob/main/2021-09-10/draw_points2.py

import matplotlib.pyplot as plt

a_points1 = [7, 3, 15, 5, 10, 2, 9]
a_points2 = [2, 4, 9, 2, 7, 8, 4]
a_points3 = [12, 10, 1, 7, 14, 16, 1]

a_days_of_the_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

plt.plot(a_days_of_the_week, a_points1)
plt.plot(a_days_of_the_week, a_points2)
plt.plot(a_days_of_the_week, a_points3)
plt.grid(axis='y', color='black', linestyle='solid')
plt.show()

Draw a pie chart

import matplotlib.pyplot as plt

a_scores = [70, 20, 5, 5]
a_languages = ["Python", "Bash", "Java", "PHP"]
a_colors = ["Red", "Blue", "Green", "Cyan"]

plt.pie(a_scores, labels=a_languages, colors=a_colors)
plt.legend()
plt.show()

This graphic represents in which languages I use my time nowadays, or if I update it by adding HTML and jQuery:

https://gitlab.com/carles.mateo/python-classes/-/blob/main/2021-09-10/draw_circle.py

Python Game Tic Tac Toe

I implemented this very simple game for my book Python 3 Exercises for Beginners.

Source Code available here:

https://gitlab.com/carles.mateo/python-classes/-/blob/main/2021-09-10/game_tic-tac-toe.py


class TicTacToe:

    def __init__(self):
        self.a_a_s_map = []
        self.generate_map()

    def generate_map(self):
        self.a_a_s_map = []

        for i_y in range(3):
            a_s_pos_x = [" ", " ", " "]
            self.a_a_s_map.append(a_s_pos_x)

    def get_map(self):
        s_map = ""

        s_map = s_map + "    1   2   3\n"
        s_map = s_map + "  -------------\n"
        for i_y in range(3):
            s_map = s_map + str(i_y + 1) + " |"
            for s_char in self.a_a_s_map[i_y]:
                s_map = s_map + " " + s_char + " |"
            s_map = s_map + "\n"
            s_map = s_map + "  -------------\n"

        return s_map

    def validate_move(self, s_char, i_x, i_y):
        """
        Validates the movement and updates the map
        :param s_char:
        :param i_x:
        :param i_y:
        :return: bool
        """
        i_x = i_x - 1
        i_y = i_y - 1

        if self.a_a_s_map[i_y][i_x] == " ":
            self.a_a_s_map[i_y][i_x] = s_char
            return True

        return False

    def check_win(self):
        for s_char in ["O", "X"]:

            # check horizontal
            for i_y in range(3):
                i_horizontal_match = 0
                for i_x in range(3):
                    if self.a_a_s_map[i_y][i_x] == s_char:
                        i_horizontal_match = i_horizontal_match + 1
                if i_horizontal_match == 3:
                    return True

            # Check vertical
            for i_x in range(3):
                i_vertical_match = 0
                for i_y in range(3):
                    if self.a_a_s_map[i_y][i_x] == s_char:
                        i_vertical_match = i_vertical_match + 1
                if i_vertical_match == 3:
                    return True

            # Check diagonal
            if self.a_a_s_map[1][1] == s_char:
                if self.a_a_s_map[0][0] == s_char and self.a_a_s_map[2][2] == s_char:
                    return True
                if self.a_a_s_map[0][2] == s_char and self.a_a_s_map[2][0] == s_char:
                    return True

        return False

    def check_stale(self):
        for i_y in range(3):
            for i_x in range(3):
                if self.a_a_s_map[i_y][i_x] == " ":
                    # Is not full
                    return False

        # We checked all and all were full
        return True


def get_from_keyboard(s_question, i_min, i_max):
    i_number = 0
    while True:
        s_answer = input(s_question)
        try:
            i_number = int(s_answer)
        except:
            print("Please, type a number")
            continue

        if i_number < i_min or i_number > i_max:
            print("Invalid value. Values should be between", i_min, "and", i_max)
            continue

        # Validations are Ok
        break

    return i_number


if __name__ == "__main__":
    o_tictactoe = TicTacToe()

    while True:

        s_map = o_tictactoe.get_map()
        print(s_map)

        while True:
            i_x = get_from_keyboard("Your move O for x: ", i_min=1, i_max=3)
            i_y = get_from_keyboard("Your move O for y: ", i_min=1, i_max=3)

            b_valid_move = o_tictactoe.validate_move("O", i_x, i_y)
            if b_valid_move is False:
                print("Invalid move")
                continue

            break

        s_map = o_tictactoe.get_map()
        print(s_map)
        b_check_win = o_tictactoe.check_win()
        if b_check_win is True:
            print("Player O wins!")
            exit(0)

        b_stale = o_tictactoe.check_stale()
        if b_stale is True:
            print("Nobody wins in war")
            exit(0)

        while True:
            i_x = get_from_keyboard("Your move X for x: ", i_min=1, i_max=3)
            i_y = get_from_keyboard("Your move X for y: ", i_min=1, i_max=3)

            b_valid_move = o_tictactoe.validate_move("X", i_x, i_y)
            if b_valid_move is False:
                print("Invalid move")
                continue

            break

        s_map = o_tictactoe.get_map()
        print(s_map)
        b_check_win = o_tictactoe.check_win()
        if b_check_win is True:
            print("Player X wins!")
            exit(0)