0% found this document useful (0 votes)
3 views

Python Notes

The document provides an overview of programming concepts, specifically focusing on Python as a high-level programming language and interpreter. It covers essential topics such as program structure, data types, operators, logical expressions, variables, code execution, and importing modules. Additionally, it explains string handling and the use of escape characters in Python.

Uploaded by

airstrider1984
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Notes

The document provides an overview of programming concepts, specifically focusing on Python as a high-level programming language and interpreter. It covers essential topics such as program structure, data types, operators, logical expressions, variables, code execution, and importing modules. Additionally, it explains string handling and the use of escape characters in Python.

Uploaded by

airstrider1984
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Unit 1

●​ What is a program?
○​ A set of instructions that will accept user input and transform it to useful output.
○​ Programs are frequently coded using a “programming environment”, which includes:
■​ A code editor - this is an area of the screen where the programmer can type and edit
their code
■​ An interpreter - this is an over-simplified (and very incomplete and somewhat inaccurate)
description of an interpreter:
●​ the interpreter interprets your source code into byte code (an intermediate-level
code), one line at a time (looking for syntax errors)
■​ A console - this displays what your code does (the output), and also allows you to input
and execute single lines of code or to call (run) a program
○​ There are 2 types of rules that programs must follow:
■​ Syntax - grammar, spelling, punctuation, etc (is everything spelled and formatted the way
expected by the program?)
■​ Semantics - logic (does the code make sense?) and intent (does the code do what you
want it to do?)
○​ Some other common terminology for programs/programming:
■​ Execute - this is when code is run
■​ Stop/kill - this is when a program is stopped
■​ Input - this is some sort of data that a user provides (or inputs) into the program. This
could be text/character-based, it could be an image, drawing, mouse click, audio, video,
or whatever the program expects
■​ Output - this is what the program returns/displays/outputs after evaluating the input
■​ Literal values - these are values that are hard-coded. You might use a literal value for a
scientific constant or something else that you want to be constant, but literal values can
limit the practicality of your program if misused.
■​ Abstraction - representing real-world values as data by ignoring details
●​ Ex: a number without a unit/context
■​ Expression - any combination of literal values, mathematical operators, comparison
operators, and boolean operators.
●​ Any value alone is an expression
●​ All operations are expressions
●​ Expressions can be made up of other expressions (ex: using boolean operators)
●​ What is Python?
○​ Python is 2 things:
■​ A high-level programming language (high-level simply means that it uses language
closer to how humans communicate than how a computer communicates)
■​ An interpreter tool
●​ Processes/interprets and executes multiple lines of code and logs errors per line
●​ The default interpreter in Python is actually built off of the programming language
C and is called CPython.
○​ Single lines of python can be executed in the console/terminal called REPL (read evaluate print
loop)
■​ REPL does NOT require the print statement to be used for output.
●​ Ex: If you type “2 + 1” in REPL, it will display the answer (“3”)
■​ REPL can be used to troubleshoot, etc.
●​ Types of values/data in Python:
○​ Integer - whole number
○​ Float - numbers with a decimal
○​ Strings - a series of characters (which include letters, numbers, and other characters); strings
are inside a set of quotation marks
○​ Boolean - True or False (first letter capitalized!)
○​ None (capital “N”) - represents the absence of a value
●​ Math Operators in Python:
○​ + is addition
○​ - is subtraction
○​ * is multiplication
○​ / is division
○​ // is integer or floor division – division answer is rounded down to the nearest whole number,
which means negative answers become more negative)
○​ ** is exponentiation
○​ % is modulo (the remainder from dividing the 2 numbers)
○​ Operands - the value to the left and right of the math operator (does this include comparison
values?)
○​ If either/both operand(s) is a float, then the answer will be a float, even in integer division
●​ Logical/conditional expressions - are used to make decisions
○​ 2 types of operators are used to write conditional expressions:
■​ Comparison operators - ask a question about the relationship between two values;
evaluates as True/False
●​ == is equal
●​ != is not equal
●​ > is greater than
●​ < is less than
●​ >= is greater than or equal to
●​ <= is less than or equal to
■​ Boolean operators - ask a question about other comparisons
●​ Three types of Boolean operators:
○​ and - evaluates two comparisons and determines if BOTH comparisons
are true
○​ or - checks if at least one of the two comparisons is true
○​ not - tests if a single expression is false
■​ Nesting logic - What happens when you have multiple expressions making up one larger
expression? The expressions are evaluated based on priority.
●​ Math operators are evaluated first, according to PEMDAS (highest priority) –
note: Modulo (%) and floor/integer division (//) are types of division.
●​ Comparison operators are solved second (middle priority)
●​ Boolean operators are solved last (lowest priority)​

●​ The above makes sense because you can’t compare values (comparison
operators) until you’ve performed the math to calculate those values, and you
can’t ask about 2 booleans (True/False values) until each comparison has
already been evaluated.
○​ Logical expressions are NOT distributed. For example, the following won’t work:​

print(5 < 1 or 2)​

Instead, if you want to compare 1 and 2 to 5 and determine if at least one of them is less than 5,
you would use this:​

print(5 < 1 or 5 < 2)
○​ Looking at the previous example above (5 < 1 or 2), you might be surprised that instead of
returning a value of True or False, it returns a value of “2”. Here’s why:
■​ If the “or” boolean operator has only 1 (or even no) comparison operators, it falls back to
“truthy” and “falsy” values:
●​ Truthy values are non-zero numbers, non-empty strings, etc.
○​ The value of something that is truthy does NOT get changed to “True”.
●​ falsy values are None, 0, empty strings, and empty collections.
○​ Like truthy values, falsy values maintain their original value.
■​ In (5 < 1 or 2), Python splits in first into its component expressions:
●​ 5 < 1
○​ This evaluates as “False”
●​ 2
○​ This evaluates as truthy, so it’s value stays “2”
●​ Because one side of the “or” operator is “true”/”truthy”, it returns the value of the
true side, which is “2”.
■​ In (( 5 > 13 or 0) or 5 > 3):
●​ This problem gets broken down as follows:
○​ 5 > 13 or 0
■​ This gets further broken down:
●​ 5 > 13 (evaluates as “False”)
●​ 0 (evaluates as falsy; stays “0”)
■​ Evaluates as “0” because neither component expression is “True”
or truthy, and it keeps the value of the right-hand side of the
expression.
○​ 5 > 3
■​ This evaluates as “True”
●​ This overall expression evaluates as “True” because at least one side has a
“True” or truthy value.
■​ In “and” boolean expressions that contain truthy values (or a combination of “True” and
truthy values), the last value is what gets returned (assuming neither side is “False” or
falsy).

○​ When Python encounters an expression, the expression must be evaluated. This means that an
expression will always result in a value that Python can then use in some way.
○​ When evaluating an expression, Python does “substitution” when multiple steps are involved
(meaning it solves a step with higher priority before moving to the next step). However, the
results from these substitution steps are not displayed/output.
○​ Throw away or display?
■​ “Every expression” in Python is evaluated, from the top of the code to the bottom..
However, if the resulting value is not saved to a variable or output (printed to the screen,
for example), the value is simply discarded (thrown away) and forgotten.
●​ Why was “every expression” in quotes? An invalid expression (such as a number
divided by zero) will stop the program with an error message. This would prevent
expressions further down in the code from being evaluated (and other code
below from being executed).
●​ Note: REPL is an exception, in that it will evaluate an expression and display the
result even without the “print” statement.
●​ Variables in Python
○​ Variables are containers that hold a value (it could be any type of data…integer, string, etc). You
can also think of a variable as a label that gets attached to a value.
○​ Variables can be read and/or written to (defined or changed/updated/redefined)
○​ Unlike in JavaScript (which uses var/let to declare a variable), the process of declaring a
variable in Python simply requires you to type the variable name and initialize it (assign it a
value using a single “=” between the variable name and its value)
■​ Ex: your_name = “Bob Jones”
○​ To read a variable’s value, simply type the variable’s name:
■​ Ex: print(your_name)
○​ Suggestions for naming variables:
■​ Choose a name that is clear (understandable), concise (not too short/long), correct
(accurately represents value), consistent (use the same naming style throughout the
program), and conventional (matches style of most other programmers)
○​ Remember that code is executed from top to bottom. If you try to read the value of a variable
before the variable has been declared/initialized, you will get an error…since you can’t read
what doesn’t yet exist.
○​ Tracing - “tracing” a variable is a method used to track the value of a variable over time
■​ Ex: printing the value of a variable inside of a loop for each iteration (cycle) of the loop so
you can see what’s happening to the value each step of the way
○​ Terminology associated with variables:
■​ Write: set/store/save/declare
■​ Initialize: define/create
■​ Update: change/increment
■​ Read: use/load/calling on
●​ Execution of code:
○​ Code is executed one line at a time, from top to bottom.
○​ Statement - a single line of code
○​ Program - a collection of statements (multiple lines of code)
■​ This collection of statements is the “body” of the program
○​ Expressions include:
■​ Literal values
■​ Math operations
■​ Logic operations
■​ Variables
■​ Nested expressions
○​ Statements can have expressions inside of them, but expressions cannot have statements
inside of them.
○​ Comments - comments are ignored during code execution and are usually used to explain a
block of code
■​ In Python, you create a single-line comment by typing an octothorpe/hashtag/numbers
sign/pound sign at the beginning of the line
●​ You can also write a comment at the end of a line of code by following the code
with a hashtag and comment…everything after the hashtag on that line will be
ignored. Ex: in “a = 7#+3#+2”, “#+3#+2” will be ignored as a comment
○​ exception: if the hashtag is in a literal string value, it is not treated as a
comment.
■​ In m = “#3” #4, only “#4” will be ignored/treated as a comment
because #3 is part of a literal value
■​ Use better names (for variables/functions/etc) to help avoid needing comments.
■​ When should you add comments? When the code is confusing/complex for you or
someone else who might be using your code.
■​ Commenting out code (temporarily) can be useful in troubleshooting or in understanding
what a certain block of code is doing.
●​ Importing Modules
○​ Terminology
■​ Module - a file that contains Python code that defines functions, variables, classes, and
other objects in order to complete a certain task. A module (simply a Python program)
can be imported into another module. Any variables from the imported module will now
be available in the module that imported it.
■​ Library - a collection of programs/modules that perform related functions (such as a
library of geometry functions, or a library of chemistry functions)
■​ Package - a container/way of organizing and distributing libraries and modules
●​ Can contain subpackages, modules, and resources (such as images, data files,
or documentation to explain how to use the package or contents of the package)
○​ To import data from another module, you use the “import” statement. There are 3 different ways
to import a module, but this is the simplest:
■​ Type “import helper” if the name of the Python module/file to be imported is “helper.py” or
“import main” if the name of the Python file to be imported is “main.py”, etc
●​ If helper.py contains a variable called “test_score”, you could print its value by
typing “print(helper.test_score)”, whereas “helper” is the Python file name,
followed by a dot, followed by the variable name.
○​ Typing the Python’s file name and a dot each time you want to call on an
imported variable is very annoying, so you can use this statement, which
makes the variable usable as if it were defined in the current file:​

“from helper import test_score”​
“helper” is the module/file name and “test_score” is the variable name​

From now on, I can call on “test_score”. Ex: print(test_score)
■​ Python’s Standard Library - useful built-in modules that are part of Python. A couple of
examples of modules contained in the Standard Library are:
●​ math module - has mathematical constants, such as e, defined as
appropriately-named variables
●​ string module - has string variables which hold various strings of characters.
○​ Ex: the “digits” variable holds all digits “0123456789”
○​ Installing new libraries:
■​ You can install new modules from the command line
●​ In Python, a special tool named “pip” is used to install a module, but you must
know the exact module name of the original, trusted module (verify verify verify)!
○​ Hackers/bad actors will create packages with names similar to other
popular libraries to try to trick developers into installing their version of a
package instead. Many programs have been compromised in this way!
●​ Strings - any combination of characters (letters, numbers, or symbols) that are inside a set of quotation
marks
○​ Single quotation marks (‘) or double quotation marks (“) can surround a string…but you must
open and close it with the same type of quotation mark
■​ What if I need quotation marks (single or double) inside a string?
●​ If you only need one type (single or double) inside of the string, simply use the
opposite type around the string.
○​ Ex: string_variable = ‘Mr. Graham said “study hard for the test”.’​
OR string_variable = “Mr. Graham said ‘this works too’.”
●​ What if you need to use both single and double quotation marks inside a string?
○​ Immediately before the quotation marks inside of the string, type a
backslash to create a special “escape character”
■​ Ex: string_variable = “Mr. Graham said \”Look ma’, I’m using
double quotes inside of my string that has double quotes around
it!\”.”​
Output if printed:​
Mr. Graham said “Look ma’, I’m using double quotes inside of my
string that has double quotes around it!”.​

○​ Are there other special escape characters? Yes, many! Here are a
couple:
■​ \n can be used inside of a string to insert a line break (which
makes a new line)
■​ \t can be used inside a string to indent or insert a tab
○​ Remember that when you “add” two strings together, you are actually concatenating
(combining) the two strings together in the order presented. Ex: print(“100” + “200”) will display
100200 because they are strings (and not integers or floats) in this example.
○​ If you need to enter a large amount of text into your program, you can use a triple quoted string,
which starts and ends with either 3 single quotes OR 3 double quotes (must start and end with
the same type)
○​ String operations:
■​ Addition (concatenation) - use a “+” between two strings in order to
concatenate/combine them
■​ Comparing strings
●​ Use “==” to determine if 2 strings are exactly the same (including capitalization)
●​ Use “!=” to determine if 2 strings are NOT identical
●​ Use “<” to determine if the string to the left comes before the string to the right
alphabetically (this compares the first characters of each string…but if they are
the same, it will move on to the 2nd characters, etc)
○​ Ex: print(“zoo” < “ant”) will display “False”
○​ Use REPL to test if capital letters are treated the same as lower-case
letters! If not, which comes first alphabetically?
●​ Use “>” to determine if the string to the left comes after the string to the right
alphabetically
●​ Use “>=” to determine if the string to the left comes after or is the same as the
string to the right alphabetically
○​ Ex:
■​ print(“zoo” >= “zoology”) will display “False”
■​ print(“zoo” >= “zoo”) will display “True”
■​ Membership in strings
●​ You can use the “in” operator to check whether or not the first string appears in
the second string
○​ Ex: print(“ham” in “Mr. Graham”) will display “True”
○​ Remember that even spaces count as characters!
○​ All strings contain the “empty string”, which is “”
■​ Slicing a string - extracting one or more characters from the string
●​ Indexing - getting only a single character from a string
○​ If you were numbering indexes, you would write a number below each
character in a string.
○​ indexing syntax: variable_name[index]
■​ Ex:​
first_name = “Rohan”​
print(first_name[1]) ← this will display “o”, as indexing starts at
zero
○​ If you try to use an index position that doesn’t exist in the string (ex:
“dog”[10]), it will return an IndexError
●​ Subscripting/slicing - getting multiple characters out of a string
○​ If you were numbering subscripts, you would write a number between the
characters in a string (the zero would be to the left of the first character)
○​ Slicing must occur from left to right! If you attempt to slice from right to
left, a blank line will be returned.
○​ If you use a beginning subscript that is within the string, and an ending
subscript that is past the end of the string, it will slice from the starting
point to the end of the string (ex: “dog”[1:10] -> og)
○​ You can also use negative numbers for subscripts, starting with -1 located
between the last two characters, then becoming more negative as you
move to the left.
■​ Subscripting works the same way as the substring function in
JavaScript if the subscript values are positive, but subscript
positions are a half-step left of indexes…AND subscripts can be
negative as mentioned above
○​ subscript syntax: variable_name[starting_subscript:ending_subscript]
■​ Ex:​
full_name = “David Smith”​
print(full_name[3:7]) ← this will display “id S”
■​ You don’t have to put a number both before and after the colon. If
you leave one blank, it will assume you meant to start at the
beginning (if the left side lacks a subscript #) or to stop at the end
(if the right side lacks a subscript #)
●​ Ex:​
full_name = “David Smith”​
print(full_name[:3]) ← this will display “Dav”​
print(full_name[-3:]) ← this will display “ith”
○​ Errors - Python has different types of errors.. A few examples are:
●​ NameError (results when you reference a variable that doesn’t exist…typo?)
●​ ImportError
●​ ValueError
●​ TypeError (results when you try to do math, comparison, or boolean operations
with 2 different types of data or a type of data that isn’t compatible with the
operator you’re using)
●​ UnboundLocalError
●​ SyntaxError (results when you broke one of Python’s rules regarding spelling,
grammar, and/or punctuation)
■​ When an error occurs, it will identify the error type in the bottom left of the error
message. The error message will also include a line number where the error occurred.
●​ But wait! Remember that the error is sometimes not on the line identified, but is
instead on the line immediately above it.

You might also like