Python Stuff
A collection of notes i’ve taken for using python
this is a WIP because it's hard to compile notes like this
Continue to: Lists
Syntax
how to make python code actually work with python
Indents are literally just spaces in code.
You have to use at least 1 indent in code. doesn’t matter
how many.
The only exception is that all strings of code must
share the same indentation because it’d be kinda weird
if it didn’t.
Meaning if they are under the Same function or other
statements, they must share an indention.
Variables are things defined by other things.
For example x can be a variable representing the string:
“math.wav”
Python Stuff 1
Python lacks a way to define variables via command.
You can only use alpha-numeric characters in variable
naming. Underscores are the only exception
You cannot use dashes in variable names
Comments are done using a # then text you wanna comment.
= is meant to be an assignment operator. The kind you would
use to assign variables. It is not an equal sign here.
An actual equal sign would be “==”.
STDOUT = standard output. its where the program running sends
out streams of the output data to. Typically in text form.
Variables
As mentioned before, there is currently no way to declare a
variable via command. it's simply there the instant it is
defined
you can assign a variable multiple values, assuming they are
different types i.e string, integer etc.
You can put variables inside strings using curly braces with
their name inside.
Casting can be used to make it clear data type the variable
is representing
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Additionally, you can use “type(variable)” to have python
retrieve what data type it is.
Variables are case sensitive meaning one variable (B) won’t
override another variable named (b)
Python Stuff 2
Variable names have a set few rules which go as follows:
A variable cannot begin with a number.
A variable must start off with a letter or an underscore
Variable names can only contain alphanumeric values
The variable cannot contain any of python’s keywords
make sure to use snake case to divide up all the words in
variables. just because.
Python lets you define multiple variables in 1 line.
it also lets you define 3 variables to represent the same
thing.
You can create a collection of variables. an example is shown
below:
words = ["Generic","Something","fake"]
#said variable can be converted into other ones as show belo
w:
x,y,z = words
#x, y, and z will each take one of the terms defined as words
at the top.
You can use print to output variables into something like a
terminal.
You can use plus in the parentheses of print to print
multiple variables
x = "this"
y = "is"
z = "a test."
#defines the variables
print(x+y+z)
Python Stuff 3
#the plus tells python to print all those individual va
riables on the same line.
You can also use it to add up numbers if the variables
are integers.
if you want to mix-match strings(words) and integers,
you can use a comma instead of a plus sign.
You can define variables outside of a function and call it
inside of one. if it is outside of any functions it is called
a Global Variable
You can make a variable global in a function by using
Global (insert variable here) then defining it.
This will override the original definition of the
variable once the function is ran.
Data types
Python has a few data types built in out the gate. they are
the following:
1 Text type in the form of string.
3 numeric types in the form of integers, float (non-
integers) and Complex (the weird one).
Sequence types in the form of list, tuple, and range.
1 mapping type in the form of dict (a dictionary in the
fold of a table)
2 set types in the form of set and frozenset
1 boolean type in the form of well, bool
3 Binary types in the form of bytes, bytearray, and
memoryview.
1 none-type called… well… nonetype.
Python Stuff 4
Once again, you can use the type() function to figure out
what data type a variable is
Numeric data types have different usages. they are the
following:
int=integers,
float=decimals
complex=scientific numbers that use values like e and j.
Python is capable of converting different numeric types into
others
you must create a new variable that equates to (insert
numeric form you want to change it to)(variable). example
below:
x = 10
y = 2.1
z = 1j
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
Casting
There are scenarios in which you have to specify what data
type a variable is. this is where casting comes in
Python Stuff 5
Casting allows you to state what type of data is being
used in a variable. it is done like so:
x = int(1)
#using a function that has the name of the data type te
lls python that whatever is in the parantheses is of th
at data type and will function accordingly.
You can use any data type so long as it correlates what's
in the parentheses
Strings
Strings is basically just text. it is surrounded by single
or double quotation marks
You can use a sequence of 3 quotation marks before and
after the text to have it appear on multiple lines. This
works for both single and double quotation marks.
they can be assigned variables for ease of use
you can tell python that each line of text has to be on an
individual line by using 3 quotation marks of the same
time (” or ‘)
by placing an integer when printing text, you can specify
what character to print
a = "Hello, World!"
print(a[1])
#the [1] tells it to print the 2nd letter in the string in
a
by using in, you can tell python to check for certain
phrase in a string.
Python Stuff 6
words = "things are very well"
if "well" in txt:
#checks to see if the word 'well' is in the text
print("Yes, 'well' is present.")
You can use len() to have python tell you the length of a
string
#tells python what a even is and defines the variable
a = 'amongus'
#will tell python to return the length of the string attac
hed to the variable a
print(len(a))
One can use slicing to make python take specific portions
of a string with [starting point:ending point]
If the starting value is left blank, it will start with
the first character
In the same vein, if you leave the ending point
blank, it will just use the last character
#defines b as Hello, Wordl!
b = "Hello, World!"
#tells python to print/return all the text between the 2nd
and 5th characters
print(b[2:5])
You can use negative values to start the slice from the
end
the upper() function can be used to turn all the
characters that can be turned uppercase in the string to
be uppercase
Python Stuff 7
a = "amongus"
#the upper() function is attached to the next via a . so p
ython knows to apply the change to the info defined in "a"
print(a.upper())
lower() like its uppercase counterpart, turns the string’s
values all lowercase.
the strip() function can be used to remove random white-
space in the first and last places of the string
its format is the following:
txt=" some words "
print(txt.strip())
replace() can be used to replace a specific character in a
string in another
a = "guud wurds"
#the first character in replace() is the character that wi
ll be changed and the second is the letter character it wi
ll be changed to
print(a.replace("u","o"))
#Python will print "good words" instead of the "guud word
s" that a is supposed to be.
You can use format() to insert numbers into strings
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
#the curly brackets act as a placeholder
You can add an unlimited amount of these values to format.
The numbers replace the placeholder depending on the order
Python Stuff 8
its in
This means the first variable stated in format() will
go the first placeholder, the second goes to the second
placeholder and vice versa
Strings can hold code. When they do so they are called f
strings. To make them f strings you have to put an f
before a quotation mark
you can use \” as an escape character. This allows for one
to use double quotes and have quotation marks inside of a
string without python having a stroke.
wow="Very\"good\"words"
print(wow)
#This will allow python to print "Very "good" words" as ot
herwise it would think you were starting and ending string
s over and over again
Python has a couple other escape characters and they are
the following:
Escape Character Result
\' Single Quote
\\ Backslash (adds a \)
\n New Line
\r Carriage Return
\t Tab (adds 5 spaces basically)
\b Backspace (Removes last character)
\f Form Feed
\ooo Octal value
\xhh Hex value (Hexadecimal numbering)
Python has a bunch of methods that change how strings are
affected that haven’t been mentioned. Some of the built-in
Python Stuff 9
ones are:
Method name Usage
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
Returns the number of times a specified value
count()
occurs in a string
encode() Returns an encoded version of the string
Returns true if the string ends with the specified
endswith()
value
expandtabs() Sets the tab size of the string
Searches the string for a specified value and
find()
returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
Searches the string for a specified value and
index()
returns the position of where it was found
Returns True if all characters in the string are
isalnum()
alphanumeric
Returns True if all characters in the string are
isalpha()
in the alphabet
Returns True if all characters in the string are
isdecimal()
decimals
Returns True if all characters in the string are
isdigit()
digits
isidentifier() Returns True if the string is an identifier
Returns True if all characters in the string are
islower()
lower case
Returns True if all characters in the string are
isnumeric()
numeric
Returns True if all characters in the string are
isprintable()
printable
Python Stuff 10
Returns True if all characters in the string are
isspace()
whitespaces
Returns True if the string follows the rules of a
istitle()
title
Returns True if all characters in the string are
isupper()
upper case
Joins the elements of an iterable to the end of
join()
the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
Returns a translation table to be used in
maketrans()
translations
Returns a tuple where the string is parted into
partition()
three parts
Returns a string where a specified value is
replace()
replaced with a specified value
Searches the string for a specified value and
rfind()
returns the last position of where it was found
Searches the string for a specified value and
rindex()
returns the last position of where it was found
rjust() Returns a right justified version of the string
Returns a tuple where the string is parted into
rpartition()
three parts
Splits the string at the specified separator, and
rsplit()
returns a list
rstrip() Returns a right trim version of the string
Splits the string at the specified separator, and
split()
returns a list
Splits the string at line breaks and returns a
splitlines()
list
Returns true if the string starts with the
startswith()
specified value
Python Stuff 11
strip() Returns a trimmed version of the string
Swaps cases, lower case becomes upper case and
swapcase()
vice versa
Converts the first character of each word to upper
title()
case
translate() Returns a translated string
upper() Converts a string into upper case
Fills the string with a specified number of 0
zfill()
values at the beginning
Booleans
Booleans represent something either being true or false. They
are binary variables
One can use print() to to showcase whether or not a boolean
is registered as true or false
print(10 > 9)
#this will either print true or false. Since 10 is greater th
an 9, it will return and print 'True'
One can also use if or else statements with booleans
a = 21
b = 33
if b > a:
print("b is greater than a")
#python will only print this if the boolean has been set to
'True'
else:
print("b is not greater than a")
Python Stuff 12
#python will only print this if the boolean has been set to
'False'
bool() can be used to have python evaluate anything put
inside of it as either true or false
the data type goes inside the parentheses
Almost all values will be evaluated as true when using
bool. The only exceptions are any empty string, range,
tuple, set, dictionary, or number that is 0 will result in
“False”.
The value “none” and “False” also results in “False”
using bool() on a class that has a “__len__” function
that returns 0 will also result in “False”
A function can be evaluated as true if it can return true
def myFunction() :
return True
print(myFunction())
#this will print 'True' as myFunction() has "return True"
under it in hierarchy
Python has a couple built-in functions that check for
something specific in a piece of data and evaluates it via
a boolean. isinstance() is one that can check if something
is of a certain data type
x = 200
#defines x for later
print(isinstance(x, int))
#begins by calling isinstance() and begins by introducing
the data it will evaluate and after the comma tells python
Python Stuff 13
what its checking for. In this case, it is checking to see
if the 200 in x is an integer.
Operators
Operators are things a python can preform on variables an values
Arithmetic operators preform various math related operations
to values in python.
This can range from adding two integers to multiplying two
floats
+ Addition x + y
- Subtraction x - y
* Multiplication x * x
/ Division x / y
% Absolute Value x % y
** Exponentiation x ** y
// Floor division x // y
Note: For Exponentiation, the second value acts as the
exponent (to what power it is.) meaning if x is 2 and y is 3,
it will represent 2³ and will result in 8.
you can use “is” and “is not” as substitutes for == and =/
respectively.
You can use “in” and “not in” to check if a specific value is
or isn’t in a value. It can return either the boolean “True”
or “False”
Same applies for in or is not to see if something is
present
for x in y:
Python Stuff 14
#code, or something
When used with strings, + and & operates can be used to
combine multiple strings and are called concatenation
operators
Functions
Functions are blocks of code that only run when they are
called/told to
you define a function with the following:
def function_name_here():
#code goes here
Lists
Lists are literally just lists of data types, typically strings
or numeric types although they can be any data type
uhh list and member are interchangeable here
Lists are made using brackets.
you can define and call entire lists in variables
said items in the list have a fixed position and order
that won’t change. given you add a new item to the list,
it simply adds it to the end for the sake of consistency.
lists are compatible with the len() function just like other
data types.
They are also compatible with type() too
you can still use brackets when calling the list to pick
certain items on the list. this is called indexing
Note: it always starts as 0 so the first item is 0 and the
second is 1.
Python Stuff 15
You can use negative indexing to make it start from the
end. this would mean [-1] would take the second to last
item in the list
You can also use ranges in indexing it looks like this:
listthing = ["uhhh","words","methinks","wahoo"]
print(listthing[2:4])
#this tells python to pick all the items in the list start
you can leave the first half blank to include everything
from the beginning and the inverse applies for leaving the
second half blank
remove() can be used to remove an item from a list.
you put the list first then a period to use it
popcan be used to remove one from a specific index
You can use a multiplyer operator on a list to repeat
items in a list.
This is called the repetition operator
Tuples
Tuples are almost identical to lists except they cannot be
changed.
Set
sets are also like lists but are not in order and are not
changeable and aren’t indexed
Python Stuff 16
Dictionary
Disclaimer: in python 3.6 or older dictionaries weren’t in
order. as of 3.7, the are in order
beyond this, they contain similar properties to lists except
they cannot have duplicate members/items.
Python’s built-in functions
Python has a plethora of built-in functions for various
situations examples are:
len() which tells you the length of a string
type() that tells you the data type of the given data
Python Modules
Python has a bunch of modules that carry out basic functions
built in such as:
Random (makes a randomizer system)
time (keeps track of time)
os (allows python to access portions of your operating
system like files)
a bunch of other ones too. This is a full list of them
Conditional Statements
Conditional statements involve requesting the computer check if
a certain requirement is or isn’t met
if handles asking if the requirement is met.
One can ask if 70>0 and if it is true the code block
within it will run
x = 1
y = 2
Python Stuff 17
#You begin with the actual "if" then insert the condition.
All if else statements end in ":" before you can add the c
ode block
if y > x:
print("x is in fact lesser than y")
Looping and stuff
Loops are the process of repeating code a set period of times.
There are For and While loops.
For loops are used to repeat a block of code a specific
number of times
for i in range(100):
print("real")
#this will print "real" 100 times. Range is used to se
t the number of times it does so and i is the variable to
make it work.
A while loop is used for repeating the block of code until a
condition is met. Ideal for undefined stuff
real = False
while real == False:
print("real is still false")
#this will keep printing "real is still false" until t
he variable real is no longer false which can be at any ti
me. Hence why its used for undefined variables
File Handling
Python Stuff 18
Random python facts
Not equal to is done using !=.
you can use print ("\033[A \033[A") to delete
the last line in output
Python Stuff 19