Each line of your code is an instruction for Python to execute.
Python will execute the lines in order, from line 1 to the end of your file.
This is called sequence. It works for simple programs, but there are other ways to control the flow of your program.
Selection allows you to make decisions based on a test. Repetition allows you to run a section of code over and over.
Let's look at these ideas separately.
Conditional statements allow your code to branch in different directions.
The decision is based on a logical test which results in True or False.
if test:
do this
x = 5y = 4if x > y: print('X is greater than Y')What happened? The conditional test 'is x > y' was true, so the print() occurred.
x = 4y = 4if x > y: print('X is greater than Y')
What happened? It appears that 4 cannot be less than 4! The print() will not happen.
x = 5y = 4if x > y: print('X is greater than Y')if y == 4: print('Y is equal to 4')
Keep in mind that those 2 if statements are not aware of each other. Later on in this lesson, I'll show you how to make those two statements aware of each other.
x = 5y = 4if (x > 4) and (y > 4): print('Both are greater than 4') if (x > 4) or (y > 4): print('One or both are greater than 4')In the first example, and is being used to evaluate both tests. Please look at the logic gate note if you are unfamiliar with and.
In the second example, or is being used to evaluate both tests. Please look at the logic gate note if you are unfamiliar with or.
Is there not, a third ?
if test:
do this
else:
do this instead
Notice how in the if / else, the else does not need a condition. It will just run when the if condition fails.
x = 5y = 4if (x > 4) and (y > 4): print('Both are greater than 4')else: print('Both are NOT greater than 4')
The practice of pairing an else with an if is HIGHLY advisable. It does make debugging easier. If you find yourself writing an if statement, and you don't see the point of adding an else to it, add an else anyhow. In that else, insert a print statement like "This should not happen #1". I added the number because if it ever does happen, and you have many of them in your code, you'll appreciate knowing where it occurred.
Earlier we saw that a series of if statements did not know about each other. elif (else-if) allows a series of if statements to know about each other.
if condition_1:
do ONLY this, if the first condition is true
elif condition_2:
do ONLY this, if the second condition is true
elif condition_3:
do ONLY this, if the third condition is true
else:
if everything failed, then ONLY do this
In this example, which statement will print?
x = 3if x == 1: print('x is 1')elif x == 2: print('x is 2')elif x == 3: print('x is 3')else: print('x is not valid')Remember area.py from the first set of problems?
# Author: Jack M.# Date: 2/9/2018# File Name: M_rect_area.py# Description: making a program to calculate the area of a rectangleprint('This program will give you the area of a rectangle: ')height = input('height') #this is where you input the height of the rectanglewidth = input('width') #this is where you input the width of the rectangleheight = int(height) #changing height into a int because it will be a numberwidth = int(width) #changing the width to a int because it will be a numberarea = height * width #area is equal to height times widtharea = str(area) #area is changing to a string because it was a intprint('The answer is: ' + area + ' meters') #the area is in meters so you would #add meters to the end How can we use an if statement structure to change the path of our code?
# Author: Jack M.# Date: 2/9/2018# File Name: M_rect_area.py# Description: making a program to calculate the area of a rectangleprint('This program will give you the area of a rectangle.') #Display menu options print(' MENU')print('==========')print('S to start')print('H for help')print('==========')print(' ')choice = input('Option?: ') #get user's choiceif choice == 'H': print('This program will give you the area of a rectangle.') print('Please provide the height and width when asked.')elif choice == 'S': height = input('height: ') #this is where you input the height of the rectangle width = input('width: ') #this is where you input the width of the rectangle height = int(height) #changing height into a int because it will be a number width = int(width) #changing the width to a int because it will be a number area = height * width #area is equal to height times width area = str(area) #area is changing to a string because it was a int print('The answer is: ' + area + ' meters') #the area is in meters so you would #add meters to the endelse: print('Not a valid choice. Only S and H are valid choices')This template works well, for now. It will be improved by the end of the next unit.
Use this template for this unit only.
We've looked at math operators like +, -, *, /, and %.
Next, we're going to look at conditional operators.
x < y # less thanx <= y # less than or equal tox > y # greater thanx >= y # greater than or equal tox == y # is / equalx != y # not equalYou can compare two strings with ==.
and
Both sides of the expression (and) must be true.
If you had a key, and the car had fuel, you could start it. If either is missing, then the car will not start.
fuel = Truekey = Trueif(fuel == True) and (key == True): print('Car started')else: print('Car OFF')If we run the same code again, but change either fuel or key to False, what would happen?
or
Either side of the expression (or), or both sides of the expression (or) must be true.
If you wanted to write this note down, you could use a pen, or a pencil. As long as you have one:
pen = Truepencil = Falseif(pen == True) or (pencil == True): print('Writing')else: print('Not Writing')What happens if we have both? change pencil to True to find out.
not
The negation of an expression.
Take a look at this example first:
pencil = Falseif not (pencil == True): print('Not Writing')else: print('Writing')We begin without a pencil. My test is asking if the opposite of having a pencil was occurring ... and that's correct ... so I'm not writing.
Can you think of a hallway or a staircase in your home, one with a single light, but two switches that run it? Ever have that switch in the 'wrong position'?
Fundamentally, documentation is the most effective way to maintain of your source code, explain your binary file, and keep users updated.
The 3 Levels of Documentation are:
Source code comments
Other programmers / code maintainers / people who will work on the project when you are gone / project leader / Teacher
In the source.
Comment as you code, use clear variable names (this makes your commenting easier). Algorithms and complex decision structures should be well explained. Files require a document header
Help for users while program is running. The Help function in a menu (or button) should have help located with the binary file ... today, most help functions point to a website, wiki, or forum ... why? Information can be updated centrally.
Users / Teacher
Appears in the running application.
Consider a menu option. Example:
S - Start
H - Help
Q - Quit
Help for users outside of the program.
Think 'Reference Manual'.
Users / Teacher
In a text (.txt) file named assn1_readme.txt or assn1_help.txt
Use any text editor, not a word processor to build the file. Use a horizontal divider (78 chars max) to avoid word-wrap.
Here are some headings for your external documentation:
Author - Your name
Class / Section - Your course code and section number
Date - The hand in date
Version - How do you keep track of what version of your software you are working on?
Unit / Question # - What Unit does the assignment belong to? Which question was it?
Programming Language - Be specific: Python 3.x or Python 3.4.4. Both are better than indicating just Python
Problem Description - Your description of my question. This is just like the header comments.
Program Assumptions - What is required for your program to run? A computer running which OS, and which version of your language? Are there any other assumptions that you are making on behalf of your user?
Features of Program - What new features did you add to my question?
Restrictions - What your solution cannot do. THIS IS NOT A KNOWN ERROR. Please see next category.
Known Errors - List your known errors. These are mistakes. errors that cause it to crash, logical, syntax or run-time errors.
Implementation Details - Pretend a friend wants to try to use a program you wrote.
(Thanks to Sarah J. for the clarification)
Additional Files - What files should be included with your program?