Intro to Python (Q1-Q2)
Operator cheat sheet
Floating point (decimal) divide operator: /
Whole integer divide operator: //
Multiply operator:
Exponent Multiply Operator: ** and =
Modulus (use in place of / to calculate remainder): %
Intro to strings and inputs
- Created python strings introduction and indexing operator guides
Overview
Strings are used to represent character data.
They can be represented as a sequence of characters, blanks, and punctuation characters, enclosed within single
quotes.
You can add strings together with +, such that "hello"+"world" will output "helloworld"
You can multiply strings together with *, such that "hello" * 3 will output "hellohellohello
Indexing Strings (filtering characters)
If you would like to pick a specific character, just pass the string variable to the indexing operator [], simply attach [startCharVal : endCharVal] to the end of your variable with the character or section of characters you would like starting from either the beginning, or with - to filter from the end.
mystring = "asparagus"
mystring[0] would return “a”
mystring[0:5] would return “aspara”
mystring[-3] would return “g”
mystring[2:] would return everything after s, so “sparagus”
mystring[1] = g would replace the first letter with G, so “guspragus”
lastly mystring[:2] would return everything including and before s, so “as”
Steps
Add another : and wow! You can control how far Python jumps between characters. Normally, python goes one character at a time, but with a second : and an integer you can tell it to go through every other character, or to go through the string backwards with -1.
mystring = 'asparagus'
print(mystring[0:8:-1] or [::-1])
> # Returns sugarapsa
Absolutely loud correct buzzer and explosion sound effect with this one line function to reverse an input (Google DOES NOT want you to know this one simple trick /j):
print(input()[::-1])
Print command tricks
Commas allow you to print multiple different things, automatically separated by a space
Newlines are always added automatically after the print command finishes outputting the contents fed to it
seperator lets you change what character is inserted between items in a print command,
end lets you change what character is used at the end of a print command.
print("thing1", "thing2", sep = ' and ')
> # Returns "thing1 and thing2"
file lets you set an output file for print, which writes / appends the output to the file. First open a file with open, then set file = outfile.
Undercore Underscore Functions
Underscore functions affect the self, usually using concatenation
String Functions
Cool and rad ways to tot-tot-totally whip up new strings
string.count(target): Returns the number of times the target occurs within a string
string.find(target): Returns the index of the first occurrence of the target in a string
string.index(target): Does the same thing as .find but crashes if it can't find the term you're looking for, while .find simply returns -1
string.lower() OR string.upper() return a copy of the string that is all lowercase or uppercase
string.islower() OR string.isupper() return True if the string is lower or upper case
string.replace(old, new) returns a copy of the string with all occurrences of the old segment replaced with the new one
string.swapcase() uppercases lowercase letters and lowercases uppercase letters.
string.title() uppercases the first letter of each word. It can get a bit jank with commas and apostrophies, so you might prefer string.capwords()
s.split(seperator) returns a list of substrings, split using the set separator which defaults to a space.
ord(character) gives you the number corresponding to the character, and allows you to change the characters by shifting them up one or down one, eg, if shifting up B would become C, C would become D.
chr(number) turns a number into it's corresponding ASCII character, eg, 97 becomes A.
Multi-line strings
Use instead of ' ' to create strings that include newlines
Floats
You should add 0.1 and 0.2 (python will do a great job of adding them normally without any random issues!)
Floating point numbers have a set number of digits with a decimal somewhere in the mix, which is how you can create non-integer numbers.
print(0.1 + 0.2)
> 0.30000000000000004
Wow! It certainly uh.. did math... I think
Integers (ints)
whole number. you're welcome.
print(1 + 2)
> 3
Intro to functions and doc strings (documentation strings)
- Added Floats & Ints, added to strings, and added function documentation
Overview
You can take commands you execute frequently and bundle them up! Instead of calling everything seperatly, just call the bundle.
def myFunction() :
print('hello world!')
Doc Strings
But! How do we remember what it does? This is where doc strings come in.
You can add a string right below the function declaration, which will appear whenever you run help function()
,
making it easier for other programmers to learn what your functions do.
def myFunction():
`Prints hello world when called`
print('hello world)
Then, you can check your doc string with help.
> help myFunction()
># Prints hello world when called
Pass
Python: So wait- you WANT a function to do nothing? That's not allowed! What are you thinking? You
utter microwave
Author: uhhhh pass
Python: fine
def doNothing():
`World's most productive function`
pass
Overview
Put things in a list! Many strings! Many ints! And also functions for wrangling your data in lists, and other types too.
Unlike strings, they are mutable, which means they can change over time.
Another note! If you turn a string into an array, each digit in the string will have it's own index.
Insert
adds an item to the beginning of the list, first, optionally tell it the index, then give it the thing to insert.
myList = [0.5, 2.1, 4.5, 3.2, 9.9]
myList.insert(2, 5.6)
myList
> # Returns [0.5, 2.1, 5.6, 4.5, 3.2, 9.9]
Append
adds an item to the end of the list
myList = [0.5, 2.1, 4.5, 3.2, 9.9]
myList.append('cake')
myList
> # Returns [0.5, 2.1, 4.5, 3.2, 9.9, 'cake']
Sort
orders a list from smallest to biggest, but only if you're working with an array of numbers. Strings are a no go.
myList = [0.5, 2.1, 4.5, 3.2, 9.9]
myList.sort()
myList
> # Returns [0.5, 2.1, 3.2, 4.5, 9.9]
Pop
Remove something from an array at a set index and return it. You can use
e taking someone's pizza order receipt off a stack and handing it to them after their order is complete.
myList = [0.5, 2.1, 4.5, 3.2, 9.9]
lastThingInList = myList.pop(-1)
lastThingInList
> # Returns 9.9
Pop removes the last item by default, so we can actually remove the index of -1
myList = [0.5, 2.1, 4.5, 3.2, 9.9]
lastThingInList = myList.pop()
lastThingInList
> # Returns 9.9
Max & Min
Get the largest or smallest thing in an object, such as an array or string.
myList = [0.5, 2.1, 4.5, 3.2, 9.9]
max(myList)
> # Returns 9.9
max(2, 5)
> # Returns 5
min(myList)
> # Returns 0.5
Sum
Add em' up!
myList = [0.5, 2.1, 4.5, 3.2, 9.9]
sum(myList)
> # Returns 20.2
Count
Check how frequently an object appears in a list
myList = [0.5, 2.1, 4.5, 0.5, 9.9]
myList.count(0.5)
> # Returns 2
In
your walls. I mean, your list. Is a thing in your list?
myList = [0.5, 2.1, 4.5, 3.2, 9.9]
2.1 in myList
> # Returns True
Join
Crush the thing into one thing
2024-09-18 - For loops
Iterate through a sequence or range, repeating set code until items are exhausted.
If you don't have a set number of items, you can use the range function with a start, end, and step, to iterate through the values given
Indexed Loops
Goes through an array and opearates on each instance in the array
myList = [0.5, 2.1, 4.5, 3.2, 9.9]
for index in range(len(myList))
myList[index] +=1
> # Returns [1.5, 3.1, 6.6, 5.5, 4.2, 10.9]
Pro tip for finding divisors!
All small divisors will be less than the square root of the number you're finding divisors for, so you can find the
first half of them by testing the number divided by the numbers ranging from 1 up to the square root, then find the
rest by dividing the number by the small divisors you just found..
Identifiers
An identifier is a string that serves as an identifying name for a value, for a built-in or user-defined function. Eg, when you say cat = 4, cat is the identifier. Identifiers must have an underscore or alphabetical character, lower or uppercase, as the first digit, followed by any sequence of alpha-numeric characters or underscores.
Python Keywords
and | del | from | not | while |
---|---|---|---|---|
as | elif | global | or | with |
assert | else | if | pass | yield |
break | except | import | ||
class | exec | in | raise | |
continue | finally | is | return | |
def | for | lambda | try |
Operator | Description |
---|---|
lambda | Lambda Expression |
or | Boolean OR |
and | Boolean AND |
not | Boolean NOT |
in, not in, is, is not | Comparison including membership and identity tests |
| | Bitwise OR |
^ | Bitwise XOR |
& | Bitwise AND |
<<,>> | Shifts |
+,- | Addition and subtraction |
*,/,//,% | Multiplication, division,remainder |
+x,-x,~x | Positive, negative, bitwise NOT |
** | Exponentiaition |
x[index],x[index:index], x(arguments), x.attribute | Subscription, slicing, call, attribute, reference |
(expressions), [expressions], {key:data]}., expressions | Binding or tuple display, list display, dictionary display, string conversion |
Imports & The math library
You can bring in other modules by importing them. If you only run import module
you'll need
to call it with module.function()
, while if you run from module import *
you can call any
function without module before it.
The math library is a common one, including the following functions:
math.sqrt()
math.pi
math.e
math.floor(x, /) - 'Returns the lagest integer number <= x, rounding down'
math.ceil(x, /) - 'Returns the smallest integer number >= x, rounding up'
File processing
You can open a file in python with file = open('example.txt', 'r')
where R indicates that
it is in read mode, W is write, and A is append. W does NOT preserve content already in the file!
infile.read() - 'Returns a string containing the remaining unread contents of the file'
file.readline() - 'Returns the next line of the file, up to and including /n'
file.readlines() - 'Returns a list (array) of items which are remaining and unread'
file.write() - "Writes something to a file, only computes when the file is closed. KEEP IN MIND- Write does NOT work like print, it will not add anything not explilcitly stated."
file.close() - 'Closes a file'
Exception Handling
Add try, then a except. If an error occurs in the try block, it will try to match it to one or more
except blocks. If it can't match it, the function throws a built in exception. Common exceptions include ZeroDivisionError
,
IndexError,
NameError
, TypeError
, ValueError
, etc. Honestly
Dictionaries
Key value stores, all you really need to know is that when looping over them the loop will go through the keys, eg, for i in dictionary, i will be each key in the dictionary.
Tuples are immutable arrays created with parenthesis, once created it's locked in stone.
Sets are like Tuples, except that they are unordered and cannot have duplicate keys. Sets can be modified with .add() and .remove(). You can only create sets by using item = set(item1, item2, etc)
The Random Module
random.randint(1,6)
will return a random integer between 1 and 6, you can set the
low and high values to anything you would like!
random.uniform(1,10)
will return a random float between 1 and 10
random.choice(list)
lets you pick a random item out of a list or string.
random.sample(list, 5)
picks 5 items out of list at random.
Other random notes
Numerical analysis
Is a hybrid between math and computer science which studies how computers fail to process operations, 0.1 + 0.2 is
an example of how python breaks down.
print(chr(sum(range(ord(min(str(not())))))))
Formatting floats
"WHERE WAS THIS LAST QUARTER" you says loudedededely
"uhhhhhhhhhhh don't worry about it here's how you format them" I say respondently
myAWesomeFLOAT = 0.1
# LETS GIVE IT SO MANY TRAILING ZEROS!!!!!
print(f"myAWesomeFLOAT:.500f")
# The number before the . = digits on the front, the number after = digits on the back
Classes
Like a mold which you can cast things in... Defining a class creates a hollow structure which you can then populate with data and manipulate, it's mostly helpful.
First, you'll need an __init__
function in order to instantiate a given instance of a
class, each instance can be represented with Self. If you do call a function from a class and want to pass an
instance in, you should do so by calling the class, then the function, and passing the instance into the function
like so: Class.function(objectname)
which could look like this: Accounts.get(john)
Class Account(object):
'Create and manage a bank account for a given user'
def __init__(self, val =0.0 ):
'Sets initial balance to zero'
# Initialize another class off of this one, if you would like
HigherClass.__init__(self, vlal) # Call to consturctor inheritance
self.acct = Account() # Call to constructor for composition
self.balance = val
def set( self, value ):
'Update acconut balance'
self.balance = value
def get( self ):
'Get current account balance'
return self.balance
Calling for inheritance pulls values from the super class, while calling for composition uses the superclass to structure data being created and structured within the child class
Special Functions
Class Account(object):
'Create and manage a bank account for a given user'
def __init__(self, val =0.0 ):
'Sets initial balance to zero'
self.val = val
def __repr__(self):
'Return a raw representation of an object'
return f"Account({self.val})"
def __str__(self):
'Return a string representation of an object'
return f"Account has a balance of {self.val}"
def __eq__(self, other):
'Check if two accounts are of equal balance, this runs if you use =='
return self.val == other.val # True if they match
def __add_(self, other):
'Add one account to another'
return self.val += other.val
You might have noticed Account.balance(self) is used instead of self.balance, this is because self gets muddy when classes inherit data from other classes, known as a super class. Instead of learning it the quick way (self.balance) and then needing to relearn it later, it's better to learn it once the right way.
__init__
Required, passes initial data into an instance of a class
__str__
This is used if you call print on a python class instance, you can make it
do anything as long as it only takes self as an input and returns a string
__repr__
Used if you call eval on a python class instance, should return only the
raw data with no pretty formatting
__gt__
Used when greater than operations are called on a class instance
__iter__
Iterator, used when loops are called and allows you to adjust iteration behavior
__next__
Called to get the next value by iterators.
__funcName__
can be called anywhere, even without the class prefix.
Persistent data in classes
If you're looking to store values globally, not just in a specific instance of a class, the best way to do that is to define a variable before the init function, which is created when the class is first called and remains persistent across every instance. Importantly, you must call the variable as part of the class as you're affecting it globally, otherwise python will throw an error trying to find it in the local __init__ function or class instance.
Here's an example that increases a value by one every time a new instance is created.
Class Counter(object):
instances = 0
def __init__(self, val = 0.0):
Counter.instances += 1
Use iter([])
!
Doctesting
Write sample inputs and outputs for your python functions and check if they behave as expected. You can
get started with import doctest
.
if __name__=='__main__':
import doctest
print(doctest.testfile('TESTFILE.py'))
# TESTFILE.py
>>> from testExample602 import *
>>> val1 = sumPos([3, 5.5, -1.1, 0, 8, -2.2, 9.1])
>>> val1
25.6
>>> val2 = sumPos([0, -0.25, 1, 3.5, -0.7, 0.5])
>>> val2
5.0
>>> val3 = sumPos([])
>>> val3
0
Small thing about error handling
Use raise, not except.
Asserts
Asserts enforce typing to ensure you receive only the values you want to see. To use one, write a Boolean statement or two, followed by a comma and a string which will be returned as an error.
assert type(val) == int or type(val) , f'{val} is not numeric'
Random
random.randrange(range) for random number woo