Overview
This chapter reviews the basic Python data structures and tools that will be used in future discussions. These concepts will allow us to refresh our memory regarding Python's most fundamental and important features, while simultaneously preparing us for advanced topics in later chapters.
By the end of this chapter, you will be able to use control flow methods to design your Python programs and initialize common Python data structures, as well as manipulate their content. You will solidify your understanding of functions and recursion in Python algorithm design. You will also be able to facilitate debugging, testing, and version control for Python programs. Finally, in the activity at the end of this chapter, you will create a Sudoku solver.
Introduction
Python has enjoyed an unprecedented increase in popularity and usage in recent years, especially in mathematics, which is the main topic of this chapter. However, before we delve into the advanced topics in mathematics, we will need to solidify our understanding of the fundamentals of the language.
This chapter will offer a refresher on the general concepts of Python; the topics covered will allow you to be in the best position for later discussions in this book. Specifically, we will be reviewing elementary concepts in general programming such as conditionals and loops, as well as Python-specific data structures such as lists and dictionaries. We will also discuss functions and the algorithm design process, which is an important part in any medium or large Python project that includes mathematics-related programs. All of this will be done through hands-on exercises and activities.
By the end of this chapter, you will be well positioned to tackle more complex, interesting problems in later chapters of this book.
Control Flow Methods
Control flow is a general term that denotes any programming syntax that can redirect the execution of a program. Control flow methods in general are what allow programs to be dynamic in their execution and computation: depending on the current state of a program or its input, the execution of that program and thus its output will dynamically change.
if Statements
The most common form of control flow in any programming language is conditionals, or if statements. if statements are used to check for a specific condition about the current state of the program and, depending on the result (whether the condition is true or false), the program will execute different sets of instructions.
In Python, the syntax of an if statement is as follows:
if [condition to check]:
[instruction set to execute if condition is true]
Given the readability of Python, you can probably already guess how conditionals work: when the execution of a given program reaches a conditional and checks the condition in the if statement, if the condition is true, the indented set of instructions inside the if statement will be executed; otherwise, the program will simply skip those instructions and move on.
Within an if statement, it is possible for us to check for a composite condition, which is a combination of multiple individual conditions. For example, using the and keyword, the following if block is executed when both of its conditions are satisfied:
if [condition 1] and [condition 2]:
[instruction set]
Instead of doing this, we can use the or keyword in a composite condition, which will display positive (true) if either the condition to the left or to the right of the keyword is true. It is also possible to keep extending a composite condition with more than one and/or keyword to implement conditionals that are nested on multiple levels.
When a condition is not satisfied, we might want our program to execute a different set of instructions. To implement this logic, we can use elif and else statements, which should immediately follow an if statement. If the condition in the if statement is not met, our program will move on and evaluate the subsequent conditions in the elif statements; if none of the conditions are met, any code inside an else block will be executed. An if...elif...else block in Python is in the following form:
if [condition 1]:
[instruction set 1]
elif [condition 2]:
[instruction set 2]
...
elif [condition n]:
[instruction set n]
else:
[instruction set n + 1]
This control flow method is very valuable when there is a set of possibilities that our program needs to check for. Depending on which possibility is true at a given moment, the program should execute the corresponding instructions.
Exercise 1.01: Divisibility with Conditionals
In mathematics, the analysis of variables and their content is very common, and one of the most common analyses is the divisibility of an integer. In this exercise, we will use if statements to consider the divisibility of a given number by 5, 6, or 7.
Perform the following steps in order to achieve this:
- Create a new Jupyter notebook and declare a variable named x whose value is any integer, as shown in the following code:
x = 130
- After that declaration, write an if statement to check whether x is divisible by 5 or not. The corresponding code block should print out a statement indicating whether the condition has been met:
if x % 5 == 0:
print('x is divisible by 5')
Here, % is the modulo operator in Python; the var % n expression returns the remainder when we divide the var variable by the number, n.
- In the same code cell, write two elif statements to check whether x is divisible by 6 and 7, respectively. Appropriate print statements should be placed under their corresponding conditionals:
elif x % 6 == 0:
print('x is divisible by 6')
elif x % 7 == 0:
print('x is divisible by 7')
- Write the final else statement to print out a message stating that x is not divisible by either 5, 6, or 7 (in the same code cell):
else:
print('x is not divisible by 5, 6, or 7')
- Run the program with a different value assigned to x each time to test the conditional logic we have. The following output is an example of this with x assigned with the value 104832:
x is divisible by 6
- Now, instead of printing out a message about the divisibility of x, we would like to write that message to a text file. Specifically, we want to create a file named output.txt that will contain the same message that we printed out previously.
To do this, we can use the with keyword together with the open() function to interact with the text file. Note that the open() function takes in two arguments: the name of the file to write to, which is output.txt in our case, and w (for write), which specifies that we would like to write to file, as opposed to reading the content from a file:
if x % 5 == 0:
with open('output.txt', 'w') as f:
f.write('x is divisible by 5')
elif x % 6 == 0:
with open('output.txt', 'w') as f:
f.write('x is divisible by 6')
elif x % 7 == 0:
with open('output.txt', 'w') as f:
f.write('x is divisible by 7')
else:
with open('output.txt', 'w') as f:
f.write('x is not divisible by 5, 6, or 7')
- Check the message in the output text file for its correctness. If the x variable still holds the value of 104832, your text file should have the following contents:
x is divisible by 6
In this exercise, we applied the usage ...