Comments Programming concepts Conditional statements Lois Delcambre a little discussion a little more Python encryption and decryption programs Plan making your programs more readable ID: 637353
Download Presentation The PPT/PDF document "Introduction to Python Module #4" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Introduction to Python Module #4Comments, Programming concepts, Conditional statements
Lois
Delcambre
a
little discussion
a little more Python
encryption and decryption programsSlide2
Planmaking your programs more readable:
comments
coding style
booleans – if elif else while in Pythonadditional Python instruction:Python console (aka Python interpreter)subscripts and decryption/encryptionSlide3
Who is going to read code?When?How often?Slide4
Food for thought …
code
is read much more often than it is
written1 The visual appearance of source code is important. We want to
require
less human cognitive effort
to
understand a
program
.
2
A program is a human-readable essay on problem solving
that also happens to execute on a computer.
3
1 Python Style guide from Guido van
Rossum
, the developer of Python
2
http://en.wikipedia.org/wiki/Programming_style
3 Punch and
Enbody
,
The Practice of Computing using Python
, p. 10, 2013, Pearson.Slide5
You can add commentsto your program
use the “#”
symbol for simple comments
You put comments in to your program so that the next programmer can read your code more easily.Python interpreter ignores all comments.Slide6
Comments are ignored by Python
an example program with comments (
guess_my_number3
)Comments at the top indicate who wrote
the program and when. Provides a brief
summary.
Comment here explains one line of code.Slide7
the way you type your program mattersexcerpt from Google Python Style Rules
Line length
Maximum
line length is 80 characters. Parentheses Use parentheses sparingly. Indentation Indent
your code blocks with
4 spaces
.
Blank
Lines
Two
blank lines between top-level definitions, one blank line between method definitions.
Imports formatting
Imports should be on separate lines.
Statements
Generally only one statement per line. Slide8
Programming concept #1: SimplicityIf something is less complicated, it’s less likely to have problems and easier to troubleshoot and fix.
easier to read!
easier to maintain!
easier to test!therefore it is more likely to work as intendedand it is much more likely to be secure.Slide9
note: functions/methods are like limousines with tinted windows
the outside program CAN’T see any of the variables in the function/method
and ...
if you put functions/methods in a separate file (and then import them when you want them), even the programmer can’t see the code (or variables)Slide10
let’s try it out:
variable inside a function
The calling program
can’t see this variable
called y.
10
add_one_function
Slide11
example showing that y (inside function)is not seen from outside program (try this)
y is defined only
inside the function
code block
The outer program
tries to print y
but Python tells us
that y is not
defined.
add_one_function
Slide12
Programming concept #2: Abstraction
Each function/method introduces an abstraction
This is what Chris Bosh explained to us.
The function name/parameters gives you all that you need to know. all that you are allowed to know
.
The implementation details are hidden inside.
You should introduce nice abstractions (functions) in your programs.Slide13
Programming concept #3: ModularityModules can be inserted or removed from a project; each module code blocks can be changed to make it run faster, to make it more readable, and so on.
Just make sure that the module still performs the same task
.
a function/method introduces modularitya group of functions/methods in a Python module is a module (e.g., the turtle module, the random module)Slide14
Programming concept #4: Information HidingInformation hiding is any attempt to prevent people from being able to see information.
The code for functions and methods are not visible to the program that invokes them.
The code inside a module (that is imported in Python) is not visible even to the programmer.Slide15
You can add docstrings (in triple quotes)immediately after your function header
This is a triple
quoted string.
You can use one
anywhere (as a
lengthy comment).
When you put it
immediately after
the function header,
it serves as
documentation
for the function.
triple quoted strings
can span multiple
lines.Slide16
Planmaking your programs more readable:
comments
coding style
booleans – if elif else while in Pythonadditional Python instruction:Python console (aka Python interpreter)subscripts and decryption/encryptionSlide17
New data type:
Boolean
(you already know integer and string data types)
Exactly two constants;
written
exactly this way:
True
False
Six comparators – always return True or False:
< less than
> greater than
<= (Note: you must put the < first
) less than or equal to
>= (Note: you must put the > first
) greater than or equal to
== (Note: you MUST use two equal signs
) equal to
!= (can also be written as <>
) not equal to
17Slide18
A program with a while loop
This condition compares two
variables from this program.
If they are not equal (if the condition returns True),
then the block is executed.
guess_my_number1Slide19
Also – count and print the number of guesses
Initialize a new variable to 0 using
an assignment statement.
Replace
num_of_guesses
with
the current value of
num_of_guesses
plus 1.
This program will add 1 to
num_of_guesses
every time the code block in the while loop
is executed.
Here, we print the
num_of_guesses
guess_my_number2Slide20
use a while True loop with break
use an if/else in loop to make sure user input is
valid (1)
U
sing the in predicate here.
will return True if the value of
user_guess
is equal to one of the
values in this list.
guess_my_number3Slide21
use a
while True
loop with
breakuse an if/else in loop to make sure user input is valid (2)
The constant True always evaluates
to True. This
l
oop will run forever.
An if statement has a
condition. If the condition
evaluates to True, the code
block is executed.
The break statement exits the loop.
The statement executed after break is this one.
else block is executed if
user_guess
was not in [1, 2, 3, 4, 5]
guess_my_number3Slide22
use a while True loop with break
use an if/else in loop to make sure user input is
valid (3)
one equal sign (=) in an
assignment
statement
two equal signs (==) in a
condition that is
checking for equality.
guess_my_number3Slide23
the 4 blocks
guess_my_number3Slide24
Practice with while loops and if statementstrinket.io
Learn/Start Learning/If-Else Statements
(3 lessons)
Learn/Tutorials (down near the bottom of the page)click on the Learn button in the upper right cornerscroll down to the tutorialschoose the one on Conditionals (for if statements)choose the one on Loops (for while loops)
you can also practice with the conditional expressions (used in if and while) with the tutorial on Logic ExpressionsSlide25
Plan for Day 4making your programs more readable:
comments
coding style
cybersecurity first principlesbooleans – if elif else while in Pythonadditional Python instruction:Python console (aka Python interpreter)
subscripts and decryption/encryptionSlide26
You can choose to run the Python console (also called the interpreter)
On this screen,
Click on this button and then choose >_ Console.
Go to My Trinkets; choose New Trinket (Python)Slide27
The Python Console (interpreter)will be on the right side of the screenSlide28
If you use turtle graphics, the Console ison the lower right side of the screen
python console here:
turtle canvas here:Slide29
The console runs one Python statementat a time (immediately when you type it)
As soon as I typed
t1.forward
and hit return,
the turtle
immediately
went forward.
Enter another
command, and it
will be executed
immediately.Slide30
The console runs one Python statementat a time (immediately when you type it)
Don’t write entire
programs this way.
Use the left window
in trinket to write
programs
and then save and
run them.
You know you’re in
the interpreter when
you see >>> on the line.Slide31
Encrypting in PythonSimplified versions of code that
Dr. Wu-
chang
Feng used to generate the crypto puzzles.Slide32
Demo of transposition encoding(09_SUBSTITUTION_simple on trinket)Slide33
Python program for a substitution cypher What needs to happen?
# s is the original message
s = "the key for number nine is
xxxxx"
alphabet = "
abcdefghijklmnopqrstuvwxyz
"
scramble = "
zyxwvutsrqponmlkjihgfedcba
"Slide34
Take the first letter in s
s = "the key for number nine is
xxxxx
"alphabet = "abcdefghijklmnopqrstuvwxyz "
scramble = "
zyxwvutsrqponmlkjihgfedcba
"Slide35
find it in the alphabet
s = "the key for number nine is
xxxxx
"alphabet = "abcdefghijklmnopqrstuvwxyz "scramble = "
zyxwvutsrqponmlkjihgfedcba
"Slide36
replace it with the correspondingletter in scramble
s = "the key for number nine is
xxxxx
"alphabet = "abcdefghijklmnopqrstuvwxyz "
scramble = "
zyxwvutsrqponmlkjihgfedcba
"Slide37
put the letter from scrambleinto the new msg we are building
s = "the key for number nine is
xxxxx
"alphabet = "abcdefghijklmnopqrstuvwxyz
"
scramble = "
zyxwvutsrqponmlkjihgfedcba
"
encrypted_s
= "g"Slide38
Take the second letter in s
s = "the key for number nine is
xxxxx
"alphabet = "abcdefghijklmnopqrstuvwxyz "
scramble = "
zyxwvutsrqponmlkjihgfedcba
"
encrypted_s
= "
g"Slide39
find it in the alphabet
s = "the key for number nine is
xxxxx
"alphabet = "abcdefghijklmnopqrstuvwxyz "scramble = "
zyxwvutsrqponmlkjihgfedcba
"
encrypted_s
=
"g"Slide40
replace it with the correspondingletter in scramble
s = "the key for number nine is
xxxxx
"alphabet = "abcdefghijklmnopqrstuvwxyz "
scramble = "
zyxwvutsrqponmlkjihgfedcba
"
encrypted_s
= "
g"Slide41
put the letter from scrambleinto the new msg we are building
s = "the key for number nine is
xxxxx
"alphabet = "abcdefghijklmnopqrstuvwxyz
"
scramble = "
zyxwvutsrqponmlkjihgfedcba
"
encrypted_s
= "
gs
"Slide42
continue through all lettersSlide43
final result
s = "the key for number nine is
xxxxx
"alphabet = "abcdefghijklmnopqrstuvwxyz "scramble = "
zyxwvutsrqponmlkjihgfedcba
"
encrypted_s
= "
gsv
pvb
uli
mfnyvi
mrmv
rh
ccccc
"Slide44
Several runs of the programTalk to your neighbor; does it look correct?
alphabet = "
abcdefghijklmnopqrstuvwxyz
"
scramble = "
zyxwvutsrqponmlkjihgfedcba
"Slide45
Let's write the programSlide46
Setting things up
09_subsitution_simpleSlide47
Find out how long alphabet is
09_subsitution_simpleSlide48
Start out with an empty encrypted message
09_subsitution_simpleSlide49
Process each letter in s using a for loop
09_subsitution_simpleSlide50
Check each letter in alphabet
09_subsitution_simpleSlide51
check to see if current character matches position i in alphabet (alphabet[i])
09_subsitution_simpleSlide52
if yes … concatenate scramble[i] to the encrypted message we are building
09_subsitution_simpleSlide53
after all characters in s are seen, print
09_subsitution_simpleSlide54
Class Activity
Talk to your partner: what happens when the original message has punctuation?
Run the program (with a message that has punctuation) to see if you were right.
How would you change this program if you wanted to encrypt both lower and upper case letters?Slide55
Python constructs used in the substitution programNote: these examples are run using the Python console – where each statement is run immediately when typed in. You can recognize that because the beginning of the line has the >>> symbols.Slide56
for loop running through a string(using the Python console here)Slide57
use any variable name you want(using the Python console here)Slide58
use your variable name within loop(using the Python console here)Slide59
for loop running through a string
09_subsitution_simpleSlide60
Using subscripts to run through a string(using the Python console here)Slide61
Subscripts running through a string
09_subsitution_simpleSlide62
You can use len function in range function
(
using the Python console here)
In the first example,
we used an assignment
statement to hold the
length of the message.
Then, we used the range
function in the for loop.
i
will take on the values
0, 1, 2, 3,
… up to one less
than the value of length.
In the second example, we
used
len
(message)
directly in the range function.
There’s no need for an
assignment statement.Slide63
Practice Activity
Modify the
09_substitution_simple.py
program so that the spaces between words in the original message do NOT show up in the encrypted message.Modify the 09_substitution_simple.py program so that a period, a comma, and a question mark are placed into the encrypted message unchanged.
09_subsitution_simpleSlide64
a few tipsWhen in doubt, print it out
(add print statements anywhere – while debugging/developing)
Test as you go
(write a little code; try it/fix it; THEN write more code)Wondering how something works? Try it in the Console(not sure how for i in range(5): works? play with it)For parameters, type function name plus open parentheses (in Shell or program)Slide65
more tipsIn Shell, you can use ctrl-p to see previous Shell command. (see previous in history)
You can use ctrl-n to see next Shell command (from the one you're looking at). (see next in history).
These two tips save typing – in Shell.
You don't have to use the print function in the Shell to see the answer. Shell will show you the answer anyway. (You must use print in a program.)Slide66
arithmetic in Pythonx + y addition
x – y subtraction
x * y multiplication
x / y division (floating point result)x // y division (integer result)x**y exponentiationx % y modulo (or remainder)This one is new for us.
i
nteger division
gives the integer
portion of the answer.
this one is new for us.
modulo gives us the
integer remainder
after dividing x
by y.Slide67
Arithmetic expressions in Console(console always shows you the returned value)
>>> 5 + 6
11
>>> 5 + 11.316.3
>>> 20/4
5.0
>>> 20/3
6.666666666666667
>>> 20//3
6
>>> 5 * 2
10
>>> 5 * 2.5
12.5
>>> 2 ** 3
8
>>> 12%5
2
>>> # 2 is the remainder after dividing 12 by 5Slide68
python program forString to ASCII representationSlide69
Convert text (ASCII) characters to decimal number equivalent
'Hello' is 72 101 108 108 111Slide70
Useful functions in Python(examples shown in the Console)
ord
function – takes an ASCII character as a parameter and returns the decimal number equivalent Slide71
Useful functions (cont.)str
turns a decimal number into an ASCII string of number symbols
>>>
ord('a')97
>>>
ord
('e')
101
>>>
str
(97)
'97'
>>>
str
(101)
'101'Slide72
Python programs: the original messaget: the encrypted message
01_dec_ascii_simpleSlide73
sample run
of
01_dec_ascii_simple
01_dec_ascii_simpleSlide74
You are invited to write decryption programsthe correspond to these encryption programsfor the programming showcase
01_dec_ascii_simple
02_HEX_ASCII_simple
06_COL_XPOSE_simple07_SCYTALE_simple08_CAESAR_simple
09_subsitution_simple
These are all linked to the
code.cyberpdx.org
site
and linked here. Remix any of these; then you’ll have a copy of the code in your trinkets to change as you like.Slide75
Extra material:More detail about parameters for functions/methodsSlide76
terminology
76
this is called the
formal parameter
(for this function)
this is the
parameter
(for this function
invocation)
add_one_function
Slide77
The function on the bottom works but it isn’t usingits formal parameter!
Don’t do this!
using_variables_from_main2
using_variables_from_main1Slide78
both of these programs use variable t1 from the outer program (it would be better to define another parameter)
using_variables_from_main2
using_variables_from_main1Slide79
Better: use one more formal parameter for the turtle that you want to draw the square.
using_variables_from_main3Slide80
Practice activityAccess these programs:
using_variables_from_main1
using_variables_from_main2
using_variables_from_main3Remix them (to have a local copy of them – in your trinkets), run them; try to break themSlide81
No Show and Tell for Day 4Ask for help – whenever you need it
Get ready for the Programming Showcase on Friday afternoon.
Each team needs to select two
subteams to present their program.one subteam with previously inexperienced programmersone other subteam The program must be either:
turtle art
decryption (of any of the message types from crypto)