Python Apps with PyQt5
Programming in General
- Programming is the art of creating software for computers.
- Programming can come in many forms, but the majority of professional programming is done with text languages that appear like a combination of English and mathematics.
- The program is a sequence of instructions that the computer follows.
- This is referred to as code.
- Programs are generally composed of 6 major types of instructions:
- Variable declarations and assignments
- These define spaces for data to be stored and update those spaces with new data.
- Arithmetic instructions
- These compute new values using basic arithmetic as well as comaprisons and some other operations.
- Typically these are combined with variable assignments to store the result of the computation.
- Input and output instructions
- These are instructions that provide output to the user or read input from the user.
- These can include text, such as a basic program that takes in text answers and prints text results.
- This can also include graphics and sounds as output and keyboard, mouse and joystick inputs, as is done in games.
- Conditional instructions
- These are instructions that make other instructions execute only if certain conditions are met.
- Repetition instructions
- These are instructions that make other instructions execute repeatedly.
- The number of repetitions can be as low as zero or theoretically infinite.
- Subroutines
- These are instructions that are placed in a separate location so that they can be executed by other instructions.
- This is done to break apart a large program into smaller peices.
- This is also done to allow some instructions to be used in multiple places without having to copy those instructions multiple places.
- Variable declarations and assignments
Python Concepts
- Python is a scripting language
- Another name for this is an interpreted language
- This means that typically the computer is analyzing each instruction that the programmer has written only when it is going to be executed.
- The advantage of this is that you do not have to wait for a separate compilation step before you run your program.
- The disadvantage is that if you make an obvious mistake in the code, you will not get an error until that line of code is reached in your program.
- Python is a dynamically-typed language
- This means that it does not check that a value has the correct type until it is used in some way.
- This is also called Duck Typing
"If it looks like a duck and quacks like a duck, it’s a duck."
- Python is particular about how you indent and use whitespace
- Whitespace is the technical term for any spaces, tabs or newlines in a text file.
- To group together instructions, you must indent all instructions at the same level.
- Python considers indentation with tabs to be different from indentation with spaces, even if they look the same.
Programming Methods
- Python has two main methods for programming, interactive and by loading instructions from a file.
- In interactive mode, Python responds to instructions as you type them.
- To start, type
python
at the command line to start Python in interactive mode.- You may need to type
python3
to get the correct version of Python.
- You may need to type
- To quit, type
quit()
on a new line (or pressCTRL
-D
).
- To start, type
- The alternative to this is to type instructions into a text file and then run those instructions.
- To run a script, you must be in the same directory as your program on the command line.
- Type
python
yourScript.py
at the command line to start Python and run your program.- Again, you may need to use
python3
to get the correct version of Python.
- Again, you may need to use
- In addition, to help those that do not want to install python or who are unable to install it (because they are using a Chromebook or do not have permission to install programs), there are several online websites that allow you to write Python code and execute it on the website. One example of this is repl.it.
Installation Instructions
- You only need to install Python if you want to work on your local machine instead of in an online platform like repl.it.
- Install Python 3:
- You may have python installed already. Try running
python --version
at a command prompt to see if it works and that you have at least version3.5
. - Installation instructions can be found here.
- You may have python installed already. Try running
- Install PyQt5:
- Installation instructions can be found here. They make use of
pip
, which is a program that should come with Python.
- Installation instructions can be found here. They make use of
Python Basics
Variables
- Variables hold data.
- A variable can hold a number, text a list of values or combinations of the above.
- A variable is identified by a name.
apples
count
x
- Since spaces have meaning, variable names with multiple words can't have spaces.
- Instead, tpyically the underscore
_
(shift-
on most keyboards) is used to separate words, e.g.:apple_count
my_favourite_variable
- While typing longer variable names can be tiresome, it is generally considered better to use more descriptive names to help you remember and others understand what the intention of the variable is.
- You can use
g
, but it doesn't mean anything. - A name like
count
is better, but still not very descriptive. - The best names are really obvious:
apple_count
.
- You can use
- Placing a value in a variable is done by putting the variable name followed by and equals sign
=
followed by the value.count = 5
- You can change a variable's value many times.
count = 5 count = 4 count = 6
- Only the final value of each variable is saved, the rest are lost.
- When you place text in a variable, it is called a string value.
- This is done using either single quotes
'
or double quotes"
to start and stop the string. - Whatever you use to start the string must also be used to end the string (both single quotes or both double quotes).
Arithmetic
- You can use
+
,-
,*
and/
for addition, subtraction, multiplication and division. - The result of arithmetic can be saved in a variable just like any other value.
count = 5 price = 1.20 total = count * price
- You can use parentheses
(
and)
(but not square brackets) to give order to arithmetic just like in your math course. - There are two unusual arithmetic operators:
//
is integer division and%
is modulo.- They act like divide and remainder from elementary school.
-
//
will round down to the next integer so that8 // 3
will equal2
since5
goes into3
only2
whole times. -
%
will give the remainder after integer division so that8 % 3
will equal2
since there is2
left after taking out3
from5
.
Input and Output
- Reading input at the console can be done using
input(
"Prompt text: "
)
.- Whatever you put instead of
"Prompt text: "
will be show to the user to hlpe them know what you are asking. - The prompt text is optional.
- Whatever you put instead of
- The result of this can be saved to a variable for processing.
favourite_fruit = input("Enter your favourite fruit: ")
- This always gives you a string value.
- To convert it to a number, you must use
int()
orfloat()
to convert it to a number.-
int()
should be used when you want an integer (a whole number). It will fail if it is given a decimal point. -
float()
should be used when you want a number that might have a decimal point in it.
count = int(input("Enter the count (whole number): ")) price = float(input("Enter the price: "))
-
- Output is done using
print()
. - Whatever you want printed should be put between the parentheses.
- You can print a string, a number or a variable's value.
print(5) value = 7.6 print(value) print("Wheee!")
- Fancier formatting can be done using a formatted string literal
- These are regular strings that have an
f
character before the opening quote. - Variables can be put into the string by surrounding them with curly brackets
{
and}
. - These can be used outside of printing too!
value = 2.99 item = 'pig statue' print(f'The value is {value} and the item is {item}')
- These are regular strings that have an
More Python
Conditions
- To only do something some of the time, you can use the
if
instruction.- After
if
you place a condition. - After the condition is a colon
:
- The code that might be executed is in the next few lines, indented.
- If the condition is true, the code indented under the
if
instruction will be executed.
count = int(input("Enter the count (whole number): ")) if count % 2 == 1: print("That is an odd count!")
- After
- If you want to have two options, you can use
elif
andelse
in a chain of possibilities.count = int(input("Enter the count (whole number): ")) if count % 2 == 1: print("That is an odd count!") else: print("")
Loops
- To something over and over again, you can use the
while
instruction.-
After
while
you place a condition. -
After the condition is a colon
:
-
The code that should be executed over and over again is in the next few lines, indented.
-
While the condition is true, the code indented under the
while
will be executed. -
Note that this may run zero times or 1 or many.
count = int(input("Enter the count (whole number): ")) while count % 2 == 1: print("The count must be an even number!") count = int(input("Enter the count (whole number): "))
-
Note: After the loop we know that
count
must be even.
-
-
To something over and over again, you can use the
for
instruction withrange()
.- The format is
for i in range(
count
)
. - The value
count
indicates how often the loop will run. It could be a variable or a literal value. - The variable
i
(which can use any name you'd like) will have a value of0
the first time the loop runs,1
the next, etc.
count = int(input("Enter the count (whole number): ")) for range(count): print(f"I've run {i} times so far")
-
Note: I had to use double quotes
"
for the string since there was a single quote'
inside it.
- The format is
Functions
-
Functions allow you to separate instructions into reusable parts so you can break apart your program or reduce how often you have to repeat yourself.
- Defining a function uses the
def
keyword. - Then you put the function name. Function names have the same rules as variable names.
- Then you put an open parenthesis
(
and a comma-separated list of parameters and finally a closing parenthesis)
and a colon:
.- The parameters are inputs to the function and must be given when you use the function.
- That line is called the function header.
- The instructions for the function are indented and below the function header.
def my_function(parameter): print(f'This is inside my function; I got {parameter}')
- Defining a function uses the
-
Functions can be used by calling them.
- This is done by using the function name followed by an open parenthesis
(
and a comma-separated list of parameters and finally a closing parenthesis)
- The parameters in this case are when you want the parameters to be inside the function this time.
my_function(6) my_function("pig")
- This is done by using the function name followed by an open parenthesis
-
Functions can return a value by using the
return
instruction as the last line in the function.- This returned value can be used by the calling code
def gimme(): return 42 value = gimme()
- At this point,
value
will have a value of42
because it was returned by the function.
PyQt5
Skeleton code
We'll start with the skeleton code available on this repl.it.
Components
Here is a list of some of the components available in PyQt5:
-
QLabel
: A text label useful for labeling buttons or other things on your application. -
QLineEdit
: A text box for entering a text value. -
QPushButton
: A simple button that the user can click. -
QCheckbox
: A checkbox that can be checked or not. -
QComboBox
: A dropdown list box that holds a set of possible options. -
QRadioButton
: A set of circular buttons where you can only select one at a time. -
QDial
: Rotateable dial for inputing a number. You can control the minimum and maximum values.
There are other controls listed in the documentation.
Layout
To lay out the controls in your application, you will likely use on of these layouts:
-
QVBoxLayout
: Linear vertical layout with each item above or below the next item. -
QGridLayout
: A 2D grid that can hold items.
If possible, I'd recommend starting with QVBoxLayout
and only move to QGridLayout
if you need something more complex.
Other Topics
There were many things we didn't have time to cover. Here are a few that would be worthwhile to learn about at some point using the resources below.
- Lists: Lists hold sequences of information to allow you to collect multiple things in one variable. These are very useful for holding data such as daily temperatures for a while month.
- Dictionaries: Dictionaries are for associating data with some key. For example, you could hold a price for an item and look up that price by the item's name.
Resources
- The Python Tutorial is actually quite detailed and a good resource if you want to learn the details of how everything works in Python.
- Python Programming is a free online book dedicated to teaching Python.
- Here is a pretty good tutorial on PyQt5.
- This tutorial is another fairly good resource for learning some of the details about how PyQt5 works.