Python Tutorial #1: Official Tutorial

Python Tutorial #1: Official Tutorial

Introduction to the Official Python Tutorial

Welcome to the world of Python, a versatile, powerful and easy-to-learn programming language. The Official Python Tutorial is your definitive resource for mastering this language, whether you’re an enthusiastic beginner or an experienced programmer looking to expand your skills.

Why this tutorial?

  • Created by Python developers

  • Covers from basic concepts to advanced techniques

  • Practical examples and clear explanations

  • Regularly updated with the latest features

In this blog, we’ll guide you through key sections of the official tutorial, offering insights, practical tips and examples to help you get the most out of this valuable resource.

Get ready to dive into Python and discover why it is one of the most popular and in-demand languages ​​in the technology industry today. Let’s get started!

Exploring Python

Python is ideal for automating repetitive tasks, creating custom databases, graphical interfaces or simple games. It is useful for both professional and amateur developers due to its ease of use and wide availability on Windows, macOS, and Unix.

It offers a robust structure for large programs and has advanced data types such as lists and dictionaries. Python allows you to write compact, readable programs, and its interactive interpreter saves time by not requiring compilation.

Plus, it’s extensible: you can add new functions or modules in C and use Python as an extension language for applications. Born from the inspiration of the program “Monty Python’s Flying Circus.

Using the Python Interpreter

The Python interpreter is essential for running scripts and testing code interactively. On Unix systems, you can start it by typing python3.12 in the terminal, while on Windows, you can use python3.12 or py if you have the py.exe launcher.

In this interactive mode, identified by the >>> prompt, you can type and execute commands line by line, which is ideal for quickly experimenting with code.

By default, Python source files are encoded in UTF-8, allowing the use of characters from most languages ​​in literals, identifiers, and comments. However, the standard library uses only ASCII characters for identifiers, a convention that is recommended to be followed to ensure code portability.

Comments in Python start with # and extend to the end of the line. They can appear at the beginning of the line or after the code, but not within a string of characters. Comments are for code clarification and are not interpreted by Python.

# Soy un comentario.

Arithmetic

The Python interpreter works like a calculator: you can enter expressions and get the values. Use operators such as +, -, *, and / for arithmetic operations, and () parentheses for grouping. For example:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating-point number
1.6

Integer numbers (e.g. 2, 4, 20) are of type int, while numbers with a fractional part (e.g. 5.0, 1.6) are of type float.

Division / always returns a float point decimal number. To do floor division and obtain an integer as a result, the // operator can be used; To calculate the remainder you can use %:

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # floored quotient * divisor + remainder
17

With Python, it is possible to use the ** operator to calculate powers

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128

The equal sign (=) is used to assign values ​​to variables. For example:

>>> width = 20
>>> height = 5 * 9
>>> width * height
900

If a variable is not “defined” (has not been assigned a value), trying to use it will give an error:

>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

Python has full support for point float; operators with mixed operands will convert integers to floating point. For example:

>>> 5 * 2.0
10.0

In interactive mode, the last printed expression is assigned to the variable _. This makes it easier to continue with calculations. For example:

>>> 10 + 5
15
>>> _ * 2
30

The _ variable should be treated as read-only. Do not explicitly assign a value to it, as this will create a separate local variable that will mask the magic variable.

In addition to int and float, Python supports other number types, such as Decimal and Fraction. It also has support for complex numbers, using the suffix j or J to indicate the imaginary part, for example, 3+5j.

Text Manipulation

In Python, the str type (string) is used to manipulate text, from individual characters like !, to words like conejo, names like París, and complete sentences like ¡Te tengo a la vista!. Texts can be enclosed in single quotes (’…’) or double quotes (”…”), producing the same result.

>>> 'Conejo!'
'Conejo!'
>>> 'París'
'París'
>>> '¡Te tengo a la vista!'
'¡Te tengo a la vista!'

# Para citar una cita, debemos \'escapar\' la cita precediéndola con \\
# Alternativamente, podemos usar el otro tipo de comillas:
>>> 'Para citar una cita, debemos "escapar" la cita precediéndola con'
'Para citar una cita, debemos "escapar" la cita precediéndola con'

In the Python interpreter, the string definition and the output string may look different. The print() function produces more readable output, omitting the surrounding quotes and printing escaped and special characters:

>>> s = 'First line.\nSecond line.'  # \n significa nueva línea
>>> s  # sin print(), los caracteres especiales se incluyen en la cadena
'First line.\nSecond line.'
>>> print(s)  # con print(), los caracteres especiales se interpretan, por lo que \n produce una nueva línea
First line.
Second line.

To prevent characters preceded by \ from being interpreted as special, raw strings can be used with a r before the quotes:

>>> print('C:\some\name')  # aquí \n significa nueva línea
C:\some
ame
>>> print(r'C:\some\name')  # nota la r antes de la comilla
C:\some\name

Literal text strings can contain multiple lines using triple quotes ("""...""" or '''...'''). Ends of line are included automatically, but can be avoided with \ at the end of the line:

>>> print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")

This produces the following output:

Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to

Strings can be concatenated with + and repeated with *:

>>> 3 * 'un' + 'ium'
'unununium'

This is useful for splitting long strings:

>>> text = ('Put several strings within parentheses '
            'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'

This only works with literals, not variables or expressions:

>>> prefix = 'Py'
>>> prefix 'thon'  # no se puede concatenar una variable y una cadena literal
  File "<stdin>", line 1
    prefix 'thon'
           ^^^^^^
SyntaxError: invalid syntax

>>> ('un' * 3) 'ium'
  File "<stdin>", line 1
    ('un' * 3) 'ium'
               ^^^^^
SyntaxError: invalid syntax

To concatenate variables or a variable and a literal, use +:

>>> prefix + 'thon'
'Python'

Text strings can be indexed, starting from index 0. In Python, there is no different data type for characters; A character is simply a string of length one:

>>> word = 'Python'
>>> word[0]  # carácter en la posición 0
'P'
>>> word[5]  # carácter en la posición 5
'n'

Indices can also be negative, starting from the right:

>>> word[-1]  # último carácter
'n'
>>> word[-2]  # penúltimo carácter
'o'
>>> word[-6]  # primer carácter
'P'

Slicing indices have useful default values:

>>> word[:2]   # caracteres desde el inicio hasta la posición 2 (excluida)
'Py'
>>> word[4:]   # caracteres desde la posición 4 (incluida) hasta el final
'on'
>>> word[-2:]  # caracteres desde el penúltimo (incluido) hasta el final
'on'

The start is always included and the end is always excluded, ensuring that s[:i] + s[i:] always equals s:

>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'

Indices point between characters, with the left edge of the first character numbered 0. Negative indices start from -1:

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

The slice from i to j consists of all the characters between the edges labeled i and j.

The length of a slice is the difference of the indices, if both are within limits. For example, the length of word[1:3] is 2.

If you try to use an index that exceeds the length of the string, you will get an error:

>>> word[42]  # la palabra solo tiene 6 caracteres
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

However, out-of-range indexes are handled just fine when using slicing:

>>> word[4:42]
'on'
>>> word[42:]
''

Strings in Python are immutable, meaning they cannot be modified. Trying to assign a value to a specific position in the string will cause an error:

>>> word[0] = 'J'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

>>> word[2:] = 'py'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

To modify a chain, you must create a new one:

>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'

The built-in len() function returns the length of a string:

>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34

Lists

Python has composite data types for grouping values, the most versatile being the list. Lists are written with values ​​separated by commas in square brackets and can contain different types of items, although they are usually of the same type.

squares = [1, 4, 9, 16, 25]
squares
[1, 4, 9, 16, 25]

Like strings, lists can be indexed and segmented:

squares[0]  # primer ítem
1
squares[-1]  # último ítem
25
squares[-3:]  # sublista desde el tercer ítem desde el final
[9, 16, 25]

Lists support operations such as concatenation:

squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Unlike strings, lists are mutable and their content can be modified:

cubes = [1, 8, 27, 65, 125]  # algo está mal aquí
4 ** 3  # el cubo de 4 es 64, no 65!
64
cubes[3] = 64  # reemplaza el valor incorrecto
cubes
[1, 8, 27, 64, 125]

You can add new items to the end of the list with the append method:

cubes.append(216)  # agrega el cubo de 6
cubes.append(7 ** 3)  # y el cubo de 7
cubes
[1, 8, 27, 64, 125, 216, 343]

In Python, list assignment does not copy data; all variables reference the same list. Any changes made to the list through a variable will be reflected in all variables that reference it:

rgb = ["Red", "Green", "Blue"]
rgba = rgb
id(rgb) == id(rgba)  # referencian el mismo objeto
True
rgba.append("Alpha")
rgb
["Red", "Green", "Blue", "Alpha"]

Slicing operations return a new list with the requested elements, as in the following list shallow copy example:

correct_rgba = rgba[:]
correct_rgba[-1] = "Alpha"
correct_rgba
["Red", "Green", "Blue", "Alpha"]
rgba
["Red", "Green", "Blue", "Alpha"]

You can also assign to a slice, which can change the length of the list or empty it:

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
letters[2:5] = ['C', 'D', 'E']  # reemplaza algunos valores
letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
letters[2:5] = []  # ahora los elimina
letters
['a', 'b', 'f', 'g']
letters[:] = []  # vacía la lista completamente
letters
[]

The len() function also works with lists:

letters = ['a', 'b', 'c', 'd']
len(letters)
4

It is possible to nest lists (lists that contain other lists):

a = ['a', 'b', 'c']
n = [1, 2, 3]
x = [a, n]
x
[['a', 'b', 'c'], [1, 2, 3]]
x[0]
['a', 'b', 'c']
x[0][1]
'b'

You can use Python for more complex tasks, such as calculating the Fibonacci sequence:

# Serie de Fibonacci:
# la suma de dos elementos define el siguiente
a, b = 0, 1
while a < 10:
    print(a)
    a, b = b, a + b

This example introduces several new features. Multiple assignment allows the variables a and b to obtain new values ​​simultaneously. The while loop is executed as long as the condition is true. In Python, any non-zero value is true, and empty sequences are false.

The body of the loop is indented, which groups the statements together. The print() function writes the value of the arguments given to it, differing from writing the expression directly, as it handles multiple arguments and formats the output in a readable way.

The end parameter in print() prevents the line feed at the end of the output, allowing custom termination:

a, b = 0, 1
while a < 1000:
    print(a, end=',')
    a, b = b, a + b

This version prints the Fibonacci series up to 1000, separated by commas.

Footnotes

Operator Precedence: In Python, the exponentiation operator (**) has higher priority than the negation operator (-). Therefore, the expression -3**2 is interpreted as -(3**2), resulting in -9. To get 9, you must use parentheses: (-3)**2.

Using quotes: In Python, special characters like \n (new line) have the same meaning in both single quotes ('...') and double quotes ("..."). The difference is that inside single quotes you don’t need to escape double quotes (") and inside double quotes you don’t need to escape single quotes (').

Slogans

We have acquired valuable knowledge and have the necessary resources at our disposal. Now is the time to apply what you have learned and start creating. GitHub repository

Arithmetic(7)

  1. Calculate the area of ​​a rectangle with base 15 and height 8.

  2. Divide 100 by 6 and display the result as a decimal number.

  3. Calculate how many complete groups of 4 can be formed with 30 elements and how many elements are left over.

  4. Cube 3.

  5. Calculate 15% of 80 using basic arithmetic operations.

  6. Add the numbers 1 to 5 and then multiply the result by 2.

  7. Determine if 64 is divisible by 8 using the modulo operator.

Text manipulation(7)

  1. Create a string that includes dialogue, using double quotes for the main string and single quotes for the character’s words.

  2. Defines a text string that represents a short three-line poem, using triple quotes and escape characters for formatting.

  3. Create a raw string that represents a simple regular expression, for example, to find phone numbers.

  4. Combine three different string variables to form a complete email address.

  5. Create a string that repeats an emoji (for example, 😊) five times using string operators.

  6. Defines a long string that represents a paragraph of an article, splitting it into multiple lines of code but displaying as a continuous paragraph when printed.

  7. Demonstrates the difference between using len() on a string with Unicode characters (such as emojis) and on a string with only ASCII characters.

Lists(7)

  1. Create a list called primes with the first 5 prime numbers and then print the third element of the list.

  2. Given the list temperatures = [20, 25, 18, 30, 15], correct the incorrect value (18) by replacing it with the correct temperature of 28.

  3. Create a list named fruits with three fruits, and then add two more fruits to the end of the list using the append() method.

  4. Make a shallow copy of a list of animals and show that adding an item to the copy does not affect the original list.

  5. Create a list of numbers from 1 to 7, then replace the elements in positions 3 to 5 (inclusive) with their squares.

  6. Create a nested list that contains two sublists: one with the days of the work week and one with the days of the weekend. Then, log in and print the first day of the weekend.

  7. Write a program that generates and prints a list of the first 8 triangular numbers (1, 3, 6, 10, 15, 21, 28, 36).

Sections covered today

    1. Opening your appetite
    1. Using the Python interpreter
    • 2.1. Invoke the interpreter
      • 2.1.1. Passing arguments
    • 2.2. The interpreter and his environment
    1. An informal introduction to Python
    • 3.1. Using Python as a calculator
      • 3.1.1. Numbers
      • 3.1.2. Text
      • 3.1.3. Lists
    • 3.2. First steps towards programming
You might also be interested
Python: The Preferred Language for Artificial Intelligence