Appendix B: Python Refresher
Python is a powerful and versatile open source programming language with a standard library packed with built-in modules, from providing access to system functionality such as file I/O to Internet data handling, to development tools, and much more. On top of the standard library, Python is also host to an extensive number of third-party modules which can be found in the
Python Package Index (PyPI)
repository. No matter what your project may be, you can almost be guaranteed to find a module to fit your needs. Of course, you could also create your own module and share it with the Python community.
Some of the
uses
for Python include
Web and Internet development
Database access
GUI development
Scientific and numeric applications
Network programming
Software and game development
The Python language also has many other noteworthy
features
, such as follows:
- 1.
Python is an interpreted programming language. Aninterpreted language
is
one
in which the code does not need to be compiled before it is run. The compiling step turns the code into machine language where the instructions can be directly executed by a computer’s
central processing unit (CPU)
. Since Python does not have a compilation step, the process to edit, test, and debug code is much faster.
- 2.
Python is a language well-suited for creating dynamic applications. This is because Python is both adynamically typed
language – type checking occurs only as the
code
is being run and variables can change types over time – and allows fordynamic binding
– where methods that are called on objects are only checked during runtime.
- 3.
While it is an object-oriented programming language, it does also support other programming paradigms such as procedural programming.
First, let’s get started by seeing if you have an updated version of Python on your computer. If not, take a moment to install it.
Installing Python
As of this writing, the current version of Python 3 is version 3.8, but the code in this book is also capable of being run on Python 3.6 or later.
Python is a cross-platform programming language and is therefore able to run on a number of different hardware platforms and operating systems. Whether you are using Windows, MacOS, or some form of Linux, the simplest way to download the latest version of Python is to go to
https://python.org/downloads/
and find the installer for your platform.
Getting Python for Windows
To first check if
Python
is installed on your system, open up a Command window and enter the commandpython3
(all lowercase). If Python is already installed, you will get a notice telling you the current version that is on your system and a chevron,>>>
, prompting you to enter a Python command. Otherwise, you will get an error message sayingpython3
is not a recognized command.
If Python is not already on your computer, then downloading Python for Windows is fairly easy. Select the installer right for your system from
python.org
, download it, and follow along with the instructions in the dialog that appears. Be sure to include Python in your PATH by checking the box like in Figure
B-1
.
Once installation is complete, try entering the
python
command into the Command window again to make sure Python 3 is installed properly.
Getting Python for MacOS
Python already comes installed on
MacOS
, but will probably need to be updated. To check out which version of Python 3 you already have installed on your computer, open up the Terminal application and enterpython3
. Similar to Windows, if you get an error message, Python 3 is not installed on your system.
Doing some research online to find out what method works best for you is a good idea. Otherwise, you could end up with multiple versions of the Python interpreter on your computer.
Downloading Python directly and installing the interpreter from
https://python.org/
is one option. After the file downloads, simply run the installer. Once the installer is complete, check to make sure Python is installed by opening up the Terminal window and enteringpython3
on the command line.
Another option is to download the Homebrew package manager. A package manager can be useful for maintaining, updating, and organizing the different software on your computer. If you are interested in using a package management system, first open a Terminal window on your Mac. To get Homebrew, go to
https://brew.sh
and copy and paste the code into Terminal to install it. Once the installation is complete, enter the following code (without the
$
symbol) into the terminal window to download Python using Homebrew:
Once the downloading
process
is complete, enterpython3
into the Terminal window to launch the Python interpreter.
If you have multiple versions of Python on your computer, you can also use Homebrew and a tool calledpyenv
to manage them.
Getting Python for Linux
If you are using
Linux
, then you probably already have a version of Python installed on your system. The Linux platform has a number of different distributions – Ubuntu, Fedora, Debian, and a few others.
To check if Python is already installed and, if so, find out what the current version is, open the Terminal application on your system and enterpython3
. If Python 3 is installed, then your current version should be displayed along with the chevron prompt,>>>
.
If you need to download or update your version of Python, you can download the most recent release from
python.org
. In Linux, it is also possible to download Python from the Terminal. However, the process for each distribution of Linux can be slightly different. There are a number of great tutorials online that you can follow along with if you choose to go this route to get Python installed on your computer.
Data Types in Python
There are several data types already built into Python, including numeric, string, and Boolean types. The following section reviews what these data types look like, as well as takes a look at a few of Python’s built-in functions to work with them.
Numeric Data Types
When working with numbers, Python has
integer
,
floating-point,
and
complex number
data types (Table
B-1
).
Table B-1
Numeric data types
in Python
Numeric Data Type | Representation |
---|
Integers | 10, 254, 9876540
|
Floating-Point Numbers | 5.7, 0.333, 0.5e6, 3.23e-5
|
Complex Numbers | 4+8j
|
Arithmetic Operators
Of course, Python also provides arithmetic operators and some built-in functions for performing mathematical operations (Table
B-2
).
Table B-2
Arithmetic operators and
expressions
Operator | Example |
---|
Addition/Subtraction | x + 5, 20 - j
|
Multiplication/Division | n ∗ 10, 5 / m (m
≠0)
|
Exponents | n ∗∗ 3
|
Modulo Operation | 100 % d
|
Working with Numeric Data Types
Table
B-3
lists a few of the
built-in mathematical functions
in Python.
Table B-3Python methods for working with numeric values
Functions | Description |
---|
abs(value)
| Returns the absolute value of a number. |
max(iterable)
| Returns the largest value in a list or other iterable object. |
min(iterable)
| Returns the smallest value in a list or other iterable object. |
round(value)
| Rounds a floating-point number and returns an int value. |
sum(iterable)
| Returns the sum of the items in a list or other iterable object. |
String Data Type
Sequences of textual data can be represented using
strings
. Strings can be delimited with single or double quotes (Table
B-4
).
Table B-4
String data type
examples in Python
Numeric Data Type | Representation |
---|
String Examples | 'This is a string literal.'
"String with numbers - 1234."
|
Empty String | '', ""
|
Escape Sequences in Strings | "Include quote " character."
|
Raw Strings | r"Escape
chars ignored."
|
The escape character backslash, ‘
’, can be used to include quotes or whitespace characters, such as ‘
’ for a newline or ‘
’ for a tab, in a string.
Including ‘r
’ before the beginning of a string completely ignores all escape characters. Raw strings are very useful for regular expressions. Triple quotations can also be used to create multiline strings.
Workings with Strings
Strings in Python are
immutable
– these are objects that cannot be modified after they are created. Whenever you apply an operation to a string, a copy is created. Parts of a string, or substring, can also be accessed using indices and slices. The following bit of code looks at creating and accessing parts of strings:
a_string = "I like dogs." # Variable assignment
print(a_string[4]) # Select and print item at index 4
print(a_string[7:10]) # Print items from index 7 to index 9
Individual characters in a list can be accessed by selecting the index value associated with that character. The first item in a string has an index value of 0. Usinga_string[4]
, the letter ‘k
’ is selected. You can also start from the end of the string and work backward by using negative index values, starting from -1.
Use slicing to select a longer substring. In the preceding example,a_string[7:10]
will include everything froma_string[7]
toa_string[9]
, leaving out the final character in the string at index 10.
To test if a substring is or is not contained within a larger string, use the special membership operators,
in
and
not in
.
a_string = "Connor, Sarah"
print('Sarah' in a_string) # Returns and prints True
print('John' not in a_string) # Returns and prints True
It is also possible to manipulate the content of strings. Concatenation is the process of combining strings and can be achieved using the addition symbol,
+
.
first_name = "Peter"
last_name = "Parker"
full_name = first_name + " " + last_name # 'Peter Parker'
Finally, Table
B-5
lists some of the other built-in methods for working with strings. Methods are similar to functions, except they are “called on” an object using specific keywords and a period, ‘
.
’. Methods such as
isupper(
) and
islower()
are useful for testing and comparing strings and validating user input.
Table B-5
More methods of the String
class
String Methods | Description |
---|
upper()
| Converts all letters in the string to uppercase. |
lower()
| Converts all letters in the string to lowercase. |
isupper()
|
ReturnsTrue
if the string has at least one letter and all letters are uppercase.
|
islower()
|
ReturnsTrue
if the string has at least one letter and all letters are lowercase.
|
isalpha()
|
ReturnsTrue
if the string contains only letters and is not blank.
|
isalnum()
|
ReturnsTrue
if the string contains only letters and numbers and is not blank.
|
isdecimal()
|
ReturnsTrue
if the string contains only numeric characters and is not blank.
|
startswith(str, begin, end)
|
ReturnsTrue
if the string or substring value begins with specified prefix.
|
endswith(str, begin, end)
|
ReturnsTrue
if the string or substring value ends with specified prefix.
|
count(str, begin, end)
| Returns the number of times a specified string occurs in a string or substring. |
delimiter.join(iterable)
| Concatenates a list of strings together into a single string value. Use the delimiter to specify how the individual strings are separated. |
split(delimiter, maxsplit)
|
Takes a single string object and returns a list of strings. Use thedelimiter
to specify where in the string a split should occur.
|
strip(chars)
|
Removes specifiedchars
and whitespaces from the beginning and the ending in a string.
|
Boolean Data Type
Objects in Python 3 can be
assigned
one of two Boolean values,
True
or
False
. Non-Boolean objects, ones that are assigned integer or string values, can also be evaluated using Boolean operators and expressions. This comes in handy in situations where you need to check if two strings match or to compare two integer values.
num_1, num_2 = 35, 10 # Ex of multiple assignment statement
print(num_1 == num_2) # Prints False
print(num_1 > num_2) # Prints True
Data Structures in Python
As you begin working with more data, you will need a way to organize, store, and access that information. Python includes a few data structures with their own special sets of rules – lists, tuples, sets, and dictionaries.
Lists
A
list
is a mutable data
structure
that is created using brackets:
# List with mixed data types
a_list = ["John Doe", 23, 1976, "blue"]
# Example of nested list
nested_list = [["zebra", "tiger", "turtle"], [3, 2, 7]]
Mutable
objects are ones whose content can be modified without creating a new object. You can append, remove, or even rearrange items within the list. Similar to strings, items in lists are in an ordered sequence and can also be accessed using indices and slicing.
print(a_list[2]) # Access and print item at index 2
print(a_list[0:3]) # Only print items from indices 0 to 2
print(a_list[:]) # Print the entire list
To access the values inside nested lists
print(nested_list[0]) # Prints ['zebra', 'tiger', ‘turtle']
print(nested_list[1][1]) # Prints 2
To get the length of a list or other iterative objects such as strings or tuples, use the built-in function
len()
:
print(len(a_list)) # Prints 4
Similar to strings, lists and other iterables can also use the
in
and
not in
operators to check if values are present in the list.
print("John Doe" in a_list) # Prints True
Table
B-6
contains some useful methods for working with lists.
Table B-6
Some List class
methods
List Methods | Description |
---|
append(value)
| Appends a single item to the end of a list. |
count(value)
|
Returns the number of times avalue
occurs in a list.
|
index(value)
|
Returns the index of the first occurrence of avalue
in a list.
|
insert(index, value)
|
Inserts onevalue
at a specificindex
location.
|
extend(iterable)
| Adds more than one item to the end of a list. |
pop(index)
|
Removes the item at the specifiedindex
.
|
remove(value)
|
Removes the first occurrence of avalue
in a list.
|
clear()
| Clears the items in a list. |
sort()
| Sorts the items in a list. |
It is also possible to remove
items
or an entire list using the
del
statement.
del a_list[3] # Delete item at index 3
# Delete multiple items using slicing
del a_list[0:2]
del a_list # Delete the entire list
Tuples
A
tuple
is an immutable data
structure
that is created using parentheses:
# Tuple with mixed data types
a_tuple = ("Jane Doe", 25, 1982, "brown")
It is possible to find values in a tuple using indices and slicing just like lists. However, since tuples are immutable, actions such as appending, sorting, or replacing items cannot be performed on them. This can be very useful when you have data that you may want others to view, but not have the ability to alter.
Many of Python’s built-in functions such as
max()
and
len()
can also be used with tuple objects (Table
B-7
).
Table B-7Tuple class methods
Tuple Methods | Description |
---|
index(value)
|
Returns the index of the first occurrence of avalue
in a tuple.
|
count(value)
|
Returns the number of times avalue
occurs in a tuple.
|
Sets
A
set
is a mutable data
structure
that is created using curly brackets:
# Set with mixed data types
a_set = {"John Smith", 45, 2001, "brown"}
Generally, sets are thought of as a collection of data of the same type, but they can also contain different data types. Sets in Python are unordered and unindexed and do not allow for duplicate values. Therefore, methods such as
index()
cannot be used with them. Sets can be very useful for removing repeated values and for performing mathematical operations from set theory on data. A few of those methods can be found in Table
B-8
.
Table B-8A few important Set class methods
Set Methods | Description |
---|
add(value)
| Adds a single item to a set. |
update(iterable)
| Adds multiple items to a set. |
remove(value)
|
Removes the specifiedvalue
from a set.
|
clear()
| Empties all items in the set. |
difference(set)
| Returns the difference of two or more sets as a new set. |
intersection(set)
| Returns the intersection of two or more sets as a new set. |
union(set)
| Returns a set that contains the union of two or more sets. |
Dictionaries
A
dictionary
is a mutable data
structure
composed of key/value pairs that is created using curly brackets:
# Example of dictionary
a_dict = {"name": "Jane Smith", "age": 29, "year": 1970, "eye color": "green"}
In the preceding example, “name” is akey
and “Jane Smith” isvalue
associated with it. The key is similar to the index in lists. You can use the key to access and organize specific items in the dictionary.
Even though dictionaries are unordered, it is very easy to access their contents using the keys. To find out a key’s value, look at the following bit of code:
print(a_dict["age"]) # Prints value associated with "age"
There are also a few methods that can help you to work with the items in dictionaries:
keys()
– Returns a list of all of the dictionary’s keys
values()
– Returns a list of all of the dictionary’s values
items()
– Returns a list containing a tuple for each key/pair value
For example, the following bit of code will return a list of all of the values in
a_dict
:
dict_values = list(a_dict.values()) # Create a list using typecasting
print(dict_values) # ['Jane Smith', 29, 1970, 'green']
It is also possible to check if keys or values exist in a dictionary using the membership operators
in
and
not in
. By default, if you do not specify keys or values, Python will search through the keys. The following example is equivalent to searching for
"year" in a_dict.keys()
:
print("year" in a_dict) # Prints True
To add a new key/value
pair
to the dictionary, you could use an
if
statement to first check if the key already exists or not. If it does not, then add the new item to the dictionary.
if "height" not in a_dict:
a_dict["height"] = 1.82
Another way to check if an item can be found in a dictionary is to use the
setdefault()
method
. If the key does not already exist or does not have a value, then the key/value pair is added. However, if the key already exists and has a value, then the
setdefault()
method does not make any changes to the dictionary. The following code will add the
"hair"
key and its value to
a_dict
:
a_dict.setdefault("hair", "brown")
Table
B-9
lists additional Dictionary class methods.
Table B-9
Some other Dictionary class
methods
Dictionary Methods | Description |
---|
get(key, default value)
|
Returns the value of the specifiedkey
. If the key does not exist, thenget()
uses thedefault value
. Useful for avoiding errors.
|
copy()
| Creates a copy of a dictionary. |
update({key: value})
| Adds a new key/value pair to a dictionary. |
pop(key)
|
Removes an item from the dictionary by specifying thekey
.
|
clear()
| Clears all of the items from a dictionary. |
Data Type Conversion
Typecasting
is the
action
of directly converting one data type to another. In Python, it is possible to convert integers to floating-point numbers, integers to strings, lists to tuples, as well as other types of conversions (Table
B-10
). The following example shows how to convert a list into a dictionary:
info = [["name", "Sam"], ["age", 12]]
print(dict(info)) # {'name': 'Sam', 'age': 12}
Table B-10Typecasting functions
Types | Typecasting Functions | Description |
---|
Arithmetic | int(value, base)
|
Converts different data types to int values. Specify thebase
if converting a string.
|
| float(value)
| Converts integer to floating-point value. |
| ord(character)
| Converts a single character to an integer. |
Strings | str(value)
| Converts other data types into a string. |
Data Structures | list(iterable)
| Converts an iterable object into a list. |
| tuple(iterable)
| Converts an iterable object into a tuple. |
| set(iterable)
|
Converts an iterable object into a set. May result in some data loss if there are
duplicate
values.
|
| dict(iterable)
| Converts an iterable with structure (key, value) into a dictionary. |
Conditionals and Loops in Python
The following section takes a look at programming tools that are used for controlling the flow and execution of commands and repetitive tasks while a program is running. Any of the following statements can be placed inside of another to createnested loops
.
“if-elif-else” Conditional Statements
Conditional statements
are used in programming to decide whether or not to perform certain actions based on whether the specified Boolean constraints evaluate toTrue
orFalse
. These types of statements are handled in Python using
if-elif-else
statements.
The following code shows a simple example of how to use
if
statements to check if items exist in a list:
car_types = ["economy", "sedan", "convertible", "SUV", "economy"]
if "SUV" not in car_types:
car_types.append("SUV")
elif car_types.count("economy") > 1:
car_types.remove("economy")
else:
car_types.append("luxury")
print(car_types) # ['sedan', 'convertible', 'SUV', 'economy']
The firstif
statement evaluates toFalse
since"SUV"
already exists in thecar_types
list. Theelif
statement provides other conditions to check if previous clauses were not true. Finally,else
statements are executed if all previous conditions were false.
There are other operators besides
in
and
not in
that can be used for evaluating Boolean expressions. Table
B-11
lists some of them.
Table B-11Python operators
Types | Operators | Description |
---|
Comparison | x == y
| Equal to |
| x != y
| Not equal to |
| x > y
| Greater than |
| x < y
| Less than |
| x >= y
| Greater than or equal to |
| x <= y
| Less than or equal to |
Logical | x > 5 and y < -5
|
ReturnsTrue
if both statements are true.
|
| x > 5 or y < -5
|
ReturnsTrue
if both statements or only one of them is true.
|
| not(x > 5)
|
Returns the
opposite
. ChangesTrue
toFalse
and vice versa.
|
“for” Loops
Python is very useful for automating repetitive tasks using loops. The
for
loop
is very useful when you have a task that needs to be executed a certain number of times, such as traversing through a sequence until you reach the end.
colors = ["blue", "red", "purple", "green", "white"]
for color in colors:
print("Current color: {}".format(color))
The preceding code will cycle through the list five times, once for each item in the list. There are also ways to repeat a block of code or iterate over a sequence of numbers using the
range()
function. The following code will print out the index values and their corresponding colors from the
colors
list:
for i in range(len(colors)):
print("{}. {}".format(i + 1, colors[i]))
The
enumerate()
function is also a way to include a counter while iterating through a sequence.
for count, color in enumerate(colors, start=1):
print("{}. {}".format(count, color))
List Comprehensions
Now that we have gone overfor
loops andif
statements, let’s take a look at a very important concept in Python,list comprehensions
.
List comprehensions
are a way to create new lists from more compact code.
Given a list of strings and integers, the following example uses list comprehension to create a new list of only the string values:
a_list = ["Sam", 1978, "Elsa", 1984, "Marcus", 1980, "Trevor", 1983]
new_list = [word for word in a_list if type(word) == str]
print(new_list) # ['Sam', 'Elsa', 'Marcus', 'Trevor']
Using nested loops, the following code is equivalent to the preceding example:
new_list = [] # Creates an empty list
for word in a_list:
if type(word) == str:
new_list.append(word)
print(new_list) # ['Sam', 'Elsa', 'Marcus', 'Trevor']
“while” Loops
Unlike the
for
loop, the
while
loop
can be used to execute a block of code an unknown number of times, as long as the Boolean condition being tested continues to evaluate to
True
. When the computer reaches the end of a
while
clause, it returns back to the beginning of the loop and checks again if the condition is still true. If so, the clause is executed once more, and the condition will be checked again at the end.
while True:
print("Please enter your age: ")
age = int(input())
if age < 21:
print("You are underage.")
continue
else:
break
print("Access granted.")
For this example, thewhile
condition will always evaluate toTrue
. However, you could also use other logical or comparison operators to test different conditions. Once in the loop, the user is asked to input their age. This information is then handled using anif-else
conditional statement.
In addition, there are types of statements that can be used to control the flow of the program and handle exceptions in a while loop –
break
and
continue
. These statements can also be used in
for
loops.
break
– Used to immediately exit awhile
loop. After exiting, the program will continue with the statement following the loop.
continue
– Used to
immediately
skip the rest of the loop and return back to start of thewhile
loop. The condition statement is then reevaluated with the next iterative value.
Functions
Afunction
is a collection of
statements
that perform some particular task and can be reused multiple times throughout a program. Functions also make code easier to read by avoiding duplicate code.
You can also define your own functions in Python using the
def()
statement
. When you call a function by invoking its name, you can also pass values, known as arguments, between the parentheses. Since functions in Python are treated as objects, you can also pass them as arguments to other functions. They also always return values whether it is
None
or some calculated value. Functions can even return other functions.
def check_for_nums(items_list):
"""
Checks to see if string (item) contains only
letters. If the string contains a numeric value,
it is removed from the list.
"""
for item in items_list[:]:
if item.isalpha() != True:
items_list.remove(item)
return items_list # Return statement and value
test_list = ["horse", "1234", "d0g", "mouse", "m3"]
new_list = check_for_nums(test_list) # Function call
print(new_list) # Prints ['horse', 'mouse']
The functioncheck_for_nums()
is used to iterate through a list and remove any strings that contain numeric values. The function takes as an argument a list of string values. Whenitems_list
is called in thefor
loop, we need to iterate over a copy of the list (created using[:]
) rather than the actual list itself in order to modify it usingremove()
. Thefor
loop could also be written more concisely using list comprehension.
Be sure to consider local and global scope when creating functions and passing arguments between them. Variables and values created in a called function only exist within that function’slocal scope
. Other
variables
and parameters created outside of all functions exist in theglobal scope
and can be accessed by all functions.
Lambda Functions
Lambda functions
are often
referred
to as anonymous functions, or functions that have not been assigned a name. They are single expressions that can take multiple arguments. The general form for a lambda function is
lambda arguments : expression
The following example demonstrates how to create and call a multiargument lambda function in Python:
full_name = lambda f, l: "Full name: {} {}".format(f, l)
print(full_name("Ben", "Franklin"))
This is equivalent to creating a function using
def()
.
def full_name(first, last):
print("Full name: {} {}".format(first, last))
Lambda functions are very useful when creating GUIs for mapping actions in response to events. When a button is clicked and a signal is triggered, a method, also known as a slot, handles that
event
. A method could be the call to a function, but in some instances, a lambda function can be used for the same reason.
Object-Oriented Programming (OOP)
In this section we will take a brief look at what object-oriented programming is and how to create
objects
using classes.
There are a number of differentprogramming paradigms
, or methods and styles of programming. One common method isprocedural programming
where a computer follows a sequential set of commands to perform some task. This kind of programming can make it difficult for adding new functions and working with more dynamic situations.
Another approach isobject-oriented programming (OOP)
which focuses on creating objects with their own properties and behaviors, and modeling their relationships between other objects. Objects are created using classes – which act as templates for the data, attributes, and methods that can be applied to an instance of a class. Aninstance
, or an object created from a class, has access to all the data and methods inside the class.
OOP also introduces the idea ofinheritance
, which is the concept of creating new classes that derive properties and behaviors from existing classes. An object created using inheritance is known as achild
. A child object has its own set of attributes and also acquires all of the properties and behaviors from itsparent
class.
The following example demonstrates how to create a new class,
Window
, for GUI development which inherits from the PyQt5 class,
QMainWindow
:
# Import necessary modules
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
class Window(QMainWindow):
"""
Create a new class, Window, which inherits from other PyQt modules, in this case from the QMainWindow class in the QtWidgets module. Inheriting from QMainWindow means we have access to all the attributes to create GUIs using PyQt, but we also can add our own variables and methods in our new class.
"""
def __init__(self):
super().__init__() # super is used to access methods from parent class
self.initializeUI()
def initializeUI(self):
"""
Initialize the window and display its contents to the screen.
"""
self.setGeometry(100, 100, 300, 200)
self.setWindowTitle("Create the Window Class")
self.show()
app = QApplication(sys.argv) # Create instance of QApplication class
window = Window() # Create instance of Window class
sys.exit(app.exec_()) # Start the event loop
Thewindow
object is an instance of theWindow
class. To make code easier to understand,
classes
start with an uppercase letter. The child object,window
, inherits from bothWindow
and from theQMainWindow
class and is able to use the methods found inQMainWindow
, such assetGeometry()
andshow()
, to create our GUI window.
In order to reference the current class, the keywordself
allows us to use any of the data or methods withinQMainWindow
as well as any new methods we create in theWindow
class.
Exception Handling in Python
It is quite common for
programs
to run into errors when they are running.Syntax errors
are the ones you will most often run into when writing your code. They are caused by incorrect syntax such as forgetting to include a colon, ‘:
’, after afor
clause.
Exceptions
are the errors that occur when executing code. It is important to consider how your program will handle these exceptions rather than allowing your application to crash. Python includes a number of built-in exceptions, including how to handle not being able to locate or open a file, incorrect data types being passed into a function, dividing by zero, and various other situations.
The best way to handle an exception is to use the
try
and
except
statements. The following code shows how to check if a user correctly enters an integer value for their age:
while True:
try:
weight = int(input("Enter your weight (in lbs): "))
break
except ValueError:
print("Invalid input.")
Code that could possibly cause an error is placed in thetry
clause. If an exception does occur while the program is running, then theexcept
clause will catch it and handle the error accordingly. Depending upon the situation, you could display an error message, use thebreak
orcontinue
statements, or force a specific kind of error to occur.
Reading and Writing to Files in Python
Python also provides built-in modules and functions to open, append, and write to files. Working with and locating files in directories can be a very long topic that includes filename pattern matching, traversing directories, deleting files and directories, and more. This section will simply focus on the basics of opening and
writing
to files.
The simplest way to open a file is to use
with('path to file', mode) as f
There are other ways to open files, but using this pattern allows for cleaner code and ensures that files are attended to by closing the file once the function using the resource is finished executing.
with open ('quotes.txt', 'w') as f:
text = "Life is what happens when you're busy making other plans. -John Lennon"
f.write(text)
Theopen()
method takes as arguments the path to the file and a mode to tell the computer how to handle the file. The second argument,'w'
, means we want to write to a file and ensures that a new file is created if it does not exist already. Thetext
is then written to a new file usingf.write()
. Other options to interact with files include reading the contents of an entire file withf.read()
or only reading one line at a time usingf.readline()
.
Table
B-12
lists the common modes for reading and writing to files.
Table B-12
Some modes for working with
files
Character | Definition |
---|
'r'
| Opens a file for reading. This is the default mode. |
'w'
| Opens a file for writing. Overwrites a file if one already exists. Otherwise, creates a new file. |
'a'
| Opens a new file for appending. File pointer starts at the end of the file if it exists. Otherwise, creates a new file. |
'r+'
| Opens a file for reading and writing. |
'w+'
| Opens a file for writing and reading. Overwrites a file if one already exists. Otherwise, creates a new file. |
'a+'
|
Opens a new file for appending and reading. File pointer starts at the end of the
file
if it exists. Otherwise, creates a new file.
|
Summary
Hopefully this appendix helps you to recall some method you may have forgotten about, or sparks an idea in your mind about how to solve a problem when creating your own GUIs, or maybe even helps you to learn something new about programming in Python.
This appendix covers information from data types and data structures to conditional statements and iteration using loops, to creating your own
functions
and classes, and more. But it only skims the surface of the possibilities of what you could apply in your own applications.
There are so many possibilities for working with PyQt and Python, and covering all of that information could definitely be written in more than one book. If you ever get stuck, the Internet is definitely an amazing resource full of information and guidance to working through your problems.
Best of luck in all of your projects and in your endeavors!