Code Python Notes
Code Python Notes
https://www.py4e.com/lectures3/Pythonlearn-15-Database-Handout.
We can use print statements to debug. If we are getting error statements, you can
use print statements in your code to help define the errors. When you run code
you’ll see the display message “adding numbers” followed by another line of
“dividing numbers” then a traceback. Those two lines of display code help you
decipher where the problem is with the written code. Yes, the traceback has “line
4” in it but if you have tons of line of code, you can just glance through your
print statements to help you determine what you meant to do next where there error
occurred.
If debugging - sometimes comments written into your code is helpful. Using # to
start comment line.
VARIABLES
Types of Variables
* Booleans have true and false
* Integers have a whole bunch
* Floats have a whole bunch
* None types have one thing, None. We think of it as the absence of a value. The
lack of a value
If you want to use multiple words - use lower case and use _ to for spaces
Modulus operator
The modulus operator works on integers and yields the remainder when the first
operand is divided by the second. In Python, the modulus operator is a percent sign
(%). The syntax is the same as for other operators:
STRING CODE
Strings - store characters and have many built-in convenience methods that let you
modify their content. Strings are immutable, meaning they cannot be changed in
place.
Two strings, using + sign, allows you to combine two lines together as one line in
the display. Instead of one line with Christopher and another line as Harrison.
This works with variables and a string literal
If I want to add a space when I combine two lines - use + again. Ie - see last line
of code after first_name +
If you want to use multiple words - use lower case and use _ to for spaces ie-
“last_name”
Saved as PyCharm\stringcombine.py
I also added comment code for first two lines so they wouldn’t show up in code.
Notice the red lines under the words in line 5. That tells me those are a problem.
So….I know I have to input lines for user to input their data - Christine and
Machon
Added age too just to try and see if I could figure out string
Then capitalize() input by adding a period “.” after first_name. It will give you
the prompt to add capitalization and you just tab or click. Always consider adding
this to any “input” you ask for so the user input works regardless of their use of
capitalization
If you want to bring all of that together, you can do that by string combining +.
And even bring input values from user.
While concatenating strings works, it doesn't always read well. Python offers the
ability to add placeholders for easier dynamic string creation. Can streamline by
using place holders for yellow and circled spots above.
FORMAT
You can choose to use brackets or numbers. Always start with zero for numbers. It
will go in order
If I want to use the same string somewhere else or want to document that one of
them will be the first, then the second, etc...better to use numbers
If I want to use variable name in same line, use the ‘f’ for format as shown in the
last line below
Different examples of ways to write this string for same output many ways to wring
these string options.
#1
#2
#3
#4
In pycharm - how I wrote it
first_name = 'Christine'
last_name = 'Machon'
first_name = 'Christine'
last_name = 'Machon'
#5
You could delete lines 4-7 but wanted to keep for notes
replace
character positions
without whitespace
upper case
lower case
is this present or in the group
true statement
change value in a list
CHAPTER 2
Mnemonic names will help me know what expressions I want to write. Python doesn’t
read the words - letters are simply names
NUMBERS
Type conversion
From this
To this - you have to concatenate with str by type conversion
If you have a number stored in a string and want to keep it as a number and do math
with it, you have to take the number from a string into an integer
Used one input number and a variable number to create a math problem. Must use int
portion to convert it from a string to an integer.
You don’t have to have all detail on previous display. You can format it to simply
show parts of it, those you want.
Input is always stored as a string - you need to store it as a date object. You
need to know if it’s given to you in day/month/year, month/day/year, etc. I can be
worth it to you use a format because you have to know what format you’ll receive in
your format -that info will be in the library with the format.
If you are only using it as a date, you can leave it as a string. If you want to
format, then you have to store it as a date object.
How do you know how you will receive date? Look it up on the date/time function
ERROR HANDLING
Error - things you don’t have control over e - ie database issue, server being
down, permission changing, etc.
Debugging - when you KNOW there is a problem with your code. Causing your code to
crash/etc. Try except isn’t good for debugging.
* Syntax Errors
* Runtime Errors
* Logic Errors
Try Except is good for when something is going wrong with your code externally you
couldn’t predict which would cause your code to go sideways. Not to find errors or
debug
this is a Try Except not to find bugs. While you shouldn’t use it to debug - you
can sometimes use it to find errors
If I know there is a problem in my code - then don’t use this.
If there is a problem that is external with your code, then try except is perfect
for it.
Logic - when code runs but doesn’t give you the response you are looking for and
doesn’t give you an error or syntax message. Your code doesn’t make sense. Common
mistakes.
This code doesn’t run at all and provides no error message.
The code asks “If x is less than y
Then it asks to display “x is greater than y”. How can you ask it a less than y
then ask for a greater than answer?
You can also look at your error to help what you’ll write in your try except code.
Take a look at Unit testing and test driven development. They are beyond the scope
of this course. They are writing little automated tests to try and catch mistakes
in your code. Good tool to use to help catch these types of mistakes and avoid them
in the future. Python unit tests are great for this too
Conditional Statements
Conditions
Everything under “if” which is indented will only run IF it meets those conditions
- ie greater than or equal to 1
This statement reads - If the price is greater than or equal to 1 then tax it at .
07 then print the tax amount
Otherwise run “else” which reads - If the tax is less than 1 then tax at zero then
print that amount. Which would be zero
Both of these conditional statements above will do exactly the same thing. The one
on the right is cleaner and doesn’t repeat the print statement as does the one on
the left. Just your preference
Error Solution
One CANADA is capitalized and the other is not. So Python thinks the lower case
Canada is not equal to the uppercase one.
So when you use the highlighted part, a user types in a value, it won’t matter
what case it’s in. It allows our code to react to different conditions.
Multiple Conditions
For these “if” and “elif” that fall into one of these categories, do this. For
everyone “else” , do this instead.
Nesting of statements
If statement with a block of indented will only execute if it’s true. So it only
runs “IF” the country is Canada. If it isn’t Canada, then the entire block will
not run and it will drop to the “else” statement.
Complex Conditions
Can use AND instead of nesting or with nesting. In this case, you need to meet
both requirements to be on the honor roll. Both option 1 and option 2 work but #2
option is cleaner on one line. Programmers choice. Both conditions must be met
for AND statements as noted below on how they are processed.
Boolean Flag
Rather than writing the IF statement, we used in the “honor roll” example, 2 or 3
times you can make a Boolean Flag. It will remember what happened in the other IF
statement. An example is above. The #1 is the honor roll statement from previous
example. By adding the yellow highlighted section - you’ve created a Boolean Flag.
You need to do it for each if, elif & else statement.
Then, later when you are coding and need to reference that same IF statement,
rather than retype the same statement, you simply type the Boolean Flag, minus the
true or false as noted in #2
comparison operators.
== Double equal equal is a question mark.
* Remember equals is an assignment statement, it has kind of direction. x = 1,
right? x = 1. That puts 1 in x.
* But, if you say x == 1, you're asking the question, is x equal to 1 and it
doesn't harm x
* Double equals is the question mark version of equality.
Remember that none of these harm the data that they're looking at. They evaluate
and then return us a true or a false. So here's an example of all these things kind
of in action.
Maintaining the same indent, you make this all part of the conditionally executed
block.
So this is three lines of code that it runs, it runs this line then sequentially
runs the next line, sequentially runs the next line.
And we indicate when it is that we want to get out of this block and then continue
by de-indenting.
So when it's true it runs all of them, then now it's running sequentially,
sequentially, sequentially. And now it says, oh if, if x = 6. Well this one's going
to be false, then that skips all of these. None of these run. Skips all of the
indented blocks. And so this indenting is a way to, in effect, make bigger blocks
of conditional code, or multi-line blocks of conditional code.
6:08
Indentation is important in Python. It's more important in Python
3.2 Assignment
Then add a try and except here to pretend you aren’t sure of code.
in Python when you know that there's a dangerous set of lines and you want to take
out insurance You put them in a try-catch block
Add the error code to except section. You can copy and past the error message from
this assignment section:
“Error, please enter numeric input”
What happens when you put “ten” input. It gives you the error code you programmed
but also has a traceback…
just look, what line are you mad about, dear computer?
7:25
Line 9. Okay, let's take a look at line 9. It's always this line or the one before
it, almost always. Almost always it gets it right. And it says name 'fr' is not
defined.
So let's just focus on this, it's complaining about this. And the problem is that
it came down from line 1 to line 5. But then it blew up. Line 5 never ran. That's
the line that blew up, and then it ran this error on line 7
Now if we type in “ten” instead of “10”, it fails exactly the same way as it did
before with just an error code and no traceback message. It run it, produces the
error code, quits and doesn’t run rest of code. It would provide the end user an
error code to change the “ten” to a numeric “10”
So if you're doing really simple input code, checking is one of the things we call
this, just to make sure the data make sense and doesn’t continue. If the data
doesn't make sense, if these two statements don't work, then whatever we've been
given is nonsensical data that we're not capable of handling. So that is how to
write exercise 3.2.
Functions:
* Sequential
* Conditional
* Iterations
* Store and reuse pattern
4.1 - FUNCTIONS
MAX
It seeks out the largest letter in a function
MIN does the opposite and looks for the smallest thing - which is a space
BUILDING FUNCTIONS
This one starts with a question that is answered as False and will never be true as
it is written. This will never run anything either. This is a bad loop too. Break
gets out of the loop.
Definite Loops
Uses ‘for’ and finite. Go over all the lines in the file or items in a list. More
predictable and to validate them.
‘For’ then the ‘i’ is the Iteration variable. You can choose whatever word you
want. It will just run for each of these items in the list. Can use numbers or
words. It asks ‘are you we done yet?’ No? Then move on to the next item in the
collection/list. Then it goes to the next one and after its done it asks the
question again. Are we done yet until it goes through all items.
Essentially this says to python, run this code 5 times with ‘i’ taking on the value
of these numbers. This way you don’t have to write out 5 lines of code to run the
same string. This “FOR” statement does it for you with one simple line.
Set some variables - not really know what largest variable, our goal when the loop
finishes, we know something. How many are in the list, what is the largest of the
group...we’ll know something about those items in the list.
Loops Idiom
Counting the number of things we will be looping through. We might want to keep
track of how many? How many have we seen?
‘Zork’ - variable
‘Thing’ - iteration variable
Zork + 1 is an increment
the difference between the count and the total is instead of adding 1 here, you
add the thing you're running that you're totaling up. So that's how we compute
totals.
we divide sum by count and now we have calculated the average, actually this should
be 154 divided by 6
filtering is the idea that we're looking for something that meets some criteria.
So we're going to go through and look at all the things in the loop. And we're
trying to figure out if something is greater than 20 and we're going to declare
that large number. So this is how you put an if in the loop. So sometimes this loop
will do nothing, sometimes this loop will print out Large number. And so, value is
going to be 9 and that's false, so it doesn't do anything. Value is 41, that's
true, so it prints out this. Value's 12, so it does nothing. Value's 3, it does
nothing. Value's 74 and so it prints this out. Value's 15, so that's false. Done.
Now the for loop knows oh, we're done, go on to the next line. Okay?
5:29
So this is kind of a filtering pattern where we are going to do some if statement
and conditionally run some code based on the value that we are looking at for now.
So that's like searching for large numbers in our long list of numbers.
Sometimes instead of printing something out in the middle of the loop, just like in
functions, we don't often print in functions. We tend to prefer using return
values, sometimes we just want a variable that tells us whether something was found
or not. And so we're going to use a boolean variable. So boolean is another type of
a variable - either True or False.
False is a constant in Python.
we're looking for 3. And we want to know did we find 3 or not. It goes through, it
won’t print what it processes...only ‘Before False’ and ‘After True’ to let you
know it did find a 3. Doesn’t tell you what which ones were true or false or how
many, only that it did find 3.
This example:
Since the value of None is nothing, the first thing it finds becomes the first. In
this example it is 9. Then since it grabbed 9 as the first, then 41 becomes false.
Then it goes to the elif and uses 9 as the smallest, false for anything higher than
9 until it finds the 3 which is less than 9. Then 3 becomes the smallest. It will
loop through all list and eventually print out the smallest in the group. None
becomes irrelevant as soon as it finds the first number, then that number is the
variable. So while we value None at nothing, the ‘If” statement primes it and gets
it started
FLAG VALUE
There is a variable called None type, None. It only has one constant in it, the
absence of a value.
We're going to say, you know what, before this loop starts, the smallest number
we've seen is nothing. We've seen no numbers whatsoever. And that's going to be our
marker to indicate that we've seen no numbers.
But we're going to use smallest equals None. None is a variable, a value, that we
can distinctly detect different than numbers. So we can say is the contents of
smallest None? If smallest is None, is is like it's more powerful than double equal
sign.
Means is it exactly the same as. And so if we are asking is smallest None, that's
only true if we've got a None in there. If we put 17 in, smallest is not None. So
this is how it works. Start with smallest equals None.
If smallest is None, this means that it's the first time. If the smallest is None,
smallest is value.
don't hurt their operands and they return you a true or a false. So is, None, and
is not is also a logical operator
Is and is not are like less than or less than or equal to or not equal to
You shouldn't use is when you should be using double equals == (usually you're
using == for a True, False, or None). So that we don't overuse is, because is, is a
really, really strong equality. So it's a stronger equality than double equals to,
so the double equals is mathematically equal to with potential conversion.
VOCABULARY
The reserved words in the language where humans talk to Python include the
following:
and del global not with
as elif if or yield
assert else import pass
break except in raise
class finally is return
continue for lambda try
def from nonlocal while