2  Introduction to Python

2.1 Instructions

Along this tutorial, try to complete the proposed Tasks to understand the concepts (search for the Task keyword).
If you find them easy, or have previous experience, try the Advanced Tasks for more difficulty (search for the Advanced Task keyword).

2.2 Python Basics

Variables

One of the most important components when programming is variables. They are used for showing, storing, and manipulating information. For instance, try the following, either by pressing (the play button at the top) or selecting the part of the code and pressing shift + enter.

Variables can be seen as boxes to store values. In Python, you can define variables whenever you want in your code with the condition that they must start with a letter and use only alphanumeric characters. In addition, some words are reserved in Python, so it is not a good idea to name variables using reserved Python keywords such as int, float or print (to name a few). Lastly, you do not have to declare (i.e., define) a variable type in Python. The declaration happens automatically when you assign a value to a variable. Now let’s define a variable.

Boxes have different sizes, forms, and types. Likewise, variables can have different types. The most commonly used variable types are integers, floats (i.e., floating-point numbers), and strings. If an operation includes both floats and integers, then the answer will be expressed as a float.

If you run your previous code, you will see that the console (at the right) displays no output. This is because we have to indicate to the computer that it has to print it. Before that, check the variables explorer to see if the variable has been incorporated. It already shows the type of the variable (i.e., integer) as well as its size (in this case, 1, since we are just storing 1 number). Now try:

In this case, the variable p contains a string (a sequence of characters), while z holds a number that is a float. If you want to transform a float into an int, you have to use the function int. It will consider only the integer part of the input. The print function outputs values to the screen/console. In the example below, we assign a value to the variable a using the equals sign and afterward we print it.

As previously mentioned, Python automatically determines the variable type when you assign a value to a variable. In case you want to know the type of a variable, you have to use the type function with the variable as the argument inside the parentheses.

Arithmetic Operations

Arithmetic operators are used in Python to perform mathematical operations such as addition, subtraction, multiplication, division, among others. Below are the most commonly used ones:

Operations between strings and number types are generally not permitted:

Strings can be concatenated using the plus symbol.

Another option is to define the number within the string (using placeholders such as %d or %f) and then indicate the number afterward. For example:

Finally, there is an improved version for formatting strings in Python called f-Strings. The syntax is similar to the previous cases but less verbose. Below are some examples:

Comparison Operators

These operators are used to compare values and return either True or False depending on the condition. Table 1 shows the most common ones.

Operator Description Code
> Greater than x > y
< Less than x < y
Greater than or equal to x >= y
Less than or equal to x <= y
== Equal to: True if both operands are equal x == y
!= Not equal to x != y

Relational operators are useful when you need to compare values and manage the flow of operations in your algorithm or procedure.

Note: At the beginning of the code, we used #. This character indicates that a comment is being written. Commenting your code is important not only for you but also for those who are going to use or evaluate your code. You can comment/uncomment a block of code using ctrl + /.

Logical Operators

Logical operators allow you to perform logical operations such as OR, AND, and NOT.

Operator Description Code
and True if both operands are true x and y
or True if either of the operands is true x or y
not True if operand is false not x

Lists

Lists are a data type commonly referred to as sequences. They are one of the most frequently used data types due to their versatility, as they allow you to store multiple values. Since lists are just another type of variable, they must be defined in the same way as variables.

As you can see, lists are defined using square brackets, and the values inside must be separated by commas. Moreover, when you want to print a specific value or a subsequence of a list, you can do so as shown in the example:

In the example, you can see that Python starts indexing from 0 and, when working with a subsequence [x:y], the element at index y is not included. This is a common practice in Python. If you want to include the last element, you have to use [x:y+1].

Task: The first print command returns a 5, why does it happen? Why does the second print only return two values?

If you want to add items to an existing list, you have to use the append command. This command is a method of lists (which is why we use the . operator in the example below) and directly acts on the list by appending the item to the end.

Another useful function in combination with lists is range. It is used to generate sequences of numbers between two specified values. The default step size is 1, but this can be changed by supplying an additional step parameter.

Task: What happens in the second case?

Notice how the bounds of the range function work: the first value (3) is included, but the last value (6) is not.

Anywhere you use a value in your code, you may assign it to a variable of an appropriate type:

Tuples

Tuples are similar to lists but with some differences. For example, tuples are defined using parentheses instead of square brackets. Also, they are immutable while lists are mutable, which means that you cannot use functions such as append or extend on tuples. Finally, tuples cannot be modified after they have been created. It is a good idea to use tuples for information that you do not want to change (e.g., constants, customers’ relative distances, etc.).

Here, you get an error because once you have defined a tuple, you cannot change its elements.

Dictionaries

A dictionary is a data structure in Python with special characteristics that allow you to store any type of value such as integers, strings, lists, and even other functions. Dictionaries also allow you to identify each element by a key.

Getting Input from the User

In some cases, you might want to obtain information from the user. This can be achieved with the input command.

In this case, all inputs are treated as text. If the input needs to be interpreted as a number, it should be explicitly converted to an integer or float using int or float.

Task: Ask the user to provide a lower and upper limit to use in a range, and then print a list of integers between the two values. This requires that you use the input, range, int, and print functions.

Flow Control Structures

Flow control structures allow you to evaluate one or more conditions and control the flow of program execution based on the results.

If Statements

The if statement is the simplest flow control instruction. As the name suggests, it evaluates whether a condition is met. If the condition is true, the program executes the code inside the if block. The instructions inside the if block are determined by their indentation (i.e., the placement of text farther to the right).

Notice how the program flow is controlled by indentation. Also, note the syntax: first the if statement, followed by the condition and a colon (:). The colon indicates the start of the block. If the if condition is True, then the indented instructions are executed and the else block is skipped. If the if statement evaluates to False, the indented code is skipped and the else block is executed. After the if statement is fully evaluated, the program flow returns to the next unindented statement. In this example, the last sentence is always printed since it is outside of the if block.

If you want to handle nested or complex cases, you can use the elif statement. The elif block is executed only if the previous if (or elif) conditions were not met.

Like the if statement, both the elif and else statements must be followed by a colon.

Task: Change the above code so that the number of trucks is an input given by the user when the program is running.

Task: Write a new program where the user inputs two numbers, stores each in a variable, and then checks whether the numbers are equal. Regardless of whether they are equal or not, display a message indicating the result.

Task: Write a program that asks for a customer’s name, compliments them if it begins with the letter “C”, rejects them if the name is “Ashton”, and if neither condition is met, simply repeats the name back.

For Loops

The for loop allows you to iterate until a condition is met. This permits you to repeat a command multiple times.

Task: What would happen if the print line was also indented?

Each time the for loop iterates, the next value in the sequence is stored in the loop variable. Notice that this loop variable is defined solely for use as an index, and in this case, for counting. That is, the loop variable will take on the values in the range 0 to 5. Once it reaches 5, the loop stops.

The example above shows that the number of iterations in a for loop is determined by the number of elements in the list, not by the values of the elements. This means you can loop over any arbitrary list, even a list of strings, as shown below.

As you can see, we defined two ways of traversing the customers’ list. In the first case, we define a variable that iterates over the list, storing each element in that variable. Another approach, similar to the previous example, is to create a variable i that counts from 0 to 4 (which corresponds to the indices of the list). Then, we retrieve each element of the list using its index.

Task: Write a program that asks the user for a number n and prints the sum of the numbers 1 to n.

Task: Modify the previous program so it only sums odd numbers from 1 to n.

While Loops

Sometimes it is useful to have a conditional loop that repeats a process until a condition is met.

As you can see, the while loop uses the comparison operator != to check whether values are not equal. However, other conditions can be used such as ==, <, <=, etc. In the example above, the loop repeats until the two values are equal. When they become equal, the loop stops and the next command is executed. Note that a while loop can become infinite if the end condition is never met. When debugging your code, be extra cautious to avoid cases where the loop never terminates.

Advanced Task: Create a program that determines how many times an integer must be repeated so that the resulting number is the closest to your s-number (without surpassing that number). For example, given a student with s-000004 and a user input of 3, the output of the program will be 1—that is, the number 3 must be repeated 1 time to produce the closest number to your s-number digit. Another example: if the s-number is s-000012 and the input is 6, then the program should output 2 (6 has to be repeated 2 times). In the case of an input larger than the s-number digit, then return 0 (e.g., s-000004 and input 9). Provide the code for such a program as well as the output of your program using your student number and an input equal to the last digit of your s-number (e.g., if your s-number is s-452123, then the last digit is 3).

Imports

Python comes with a large number of modules and packages (collections of modules) that contain diverse functions. They are used when you need functions that are not part of Python’s basic set of functions. These functions can be imported using modules and packages. For instance, imagine that you want to generate random numbers. In that case, you can import the random function from the random package and then use it.

Packages only need to be imported once per script and are usually placed at the top of the file. Additionally, you can import everything from a package or module by using an asterisk, e.g., from random import *.

The random function imported from the random package returns a random decimal number between 0 and 1. On the other hand, the constant π is imported from the math module. Notice that you can also import an entire module with all its functions. For example:

In this case, you must use the module name followed by a dot to indicate the function you want to use.

Task: Make a program that uses a for loop to print out a random number between 0 and 5, 10 times.

Task: Write a program that uses a for loop to print out a random integer between 4 and 10 (including both 4 and 10) 5 times.

Task: Write a program for a game of higher or lower. Generate a random integer between 1 and 100, allow the user to input a guess, and inform them whether the guess is too high or too low until they guess correctly.

Bear in mind that for some specific libraries, you might have to download and install them separately.

Subroutines or Functions

When programs begin to grow larger, it can be convenient to split the program into smaller subsections, as this makes the program logic easier to follow and the code easier to maintain. A subroutine, also commonly called a function, is a collection of code grouped under a name that can be invoked from anywhere. Python has many built-in functions like input and print, but you can also create your own functions.

In this example, we create a simple subroutine:

Line 1 defines the subroutine, but the code inside the subroutine does not run until it is called on line 7. Additionally, notice that the routine accepts a parameter (i.e., n), which is commonly referred to as an argument. You can define functions wherever you prefer. When running the program, Python will read all the subroutines and store them in memory. Later, it will execute the rest of the code in sequence.

It is a common convention to create a subroutine called main as the principal entry point of the code. This means that the program starts by running main and then calls other subroutines as needed. Note that you must remember to call main (as seen on line 8); if you do not, Python will load all the subroutines into memory and then finish execution without running any code.

You can define as many subroutines as you like. Subroutines can call other subroutines (e.g., recursion). It is important to have a clear structure for your subroutines, as a convoluted arrangement can make your code difficult to read. If you have subroutines calling other subroutines in a complex manner, it might be better to reconsider your code structure.

Subroutines can serve many purposes. For instance, they can process and return information using the return statement.

We pass each value of list_numbers into the subroutine adding_five, which adds five to the value and then returns the result, replacing the original value in list_numbers.

Advanced Task: Create a function that calculates the customer service cost as \(3.5*n\) when \(n \leq 10\), \(2.5*n\) when \(10 < n \leq 100\), and \(1.25\) for the other cases, where n is the number of customers. The number of customers is generated randomly (between 1 and x) in the main function, and the parameter x is provided by the user. Try different values for x like 5, 10, 100, and 200. In the end, the program should display the randomly generated number of customers and the corresponding service cost.

Advanced Task: Given the code:

Create a function that, given 2 points (e.g., representing customers), calculates the Euclidean distance between their coordinates. For example, calculate the distance between point 1, which is (0,1), and point 15, which is (1,5). Note that you must implement the mathematical function yourself and cannot use an external module or package for this.