- Python Notes
- Summary
- General Notes
- Primitive Types
- Arithmetic Operations
- Order Of Precedence
- Print Notes
- Libraries
- Text Handling
- Simple and Compound Conditional Structures
- Repetition Structure or Loops or Iterations
- Collections
- Colors in the Python Terminal
- Extra data conversion
- Functions
- Modules
- Packages
- Error Handlings and Exceptions
- Handling Txt file
Successive refinement: partition an application and run tests while developing it, for example to avoid errors early on, and correct them while in the development phase.
Invert typed string with: var[::-1]
Flag - Stopping point
You can get the same value for multiple variables using:
ex = ex1 = ex2 = ex3 = 0
reverse = True - makes some functions inverted ex: L.sort()
function == Method
every function opens and closes parentheses after the name ex: f()
- int - integer
- bool - boolean / true, false
- float - floating point numbers
- str - text string
- Addition: +
- Subtraction: -
- Multiplication: *
- Division: /
- Power: **
- Division (floor): //
- Remainder/Modulo: %
- Comparison: ==
- Assignment: =
- :()
- :**
- :*,/,//,%
- :+,-
Inside a print with f-string or .format you can use :.3f inside the braces to define only 3 digits after the decimal point
end=’ ’ does not break the line
\n - line break
3 double quotes to span multiple lines
f-string - f'test : {variable}'
ceil(N) : rounds up
floor(N) : rounds down
trunc(N) : reduces decimal places without rounding
pow(N) : power
sqrt(N) : square root
factorial(N) : factorial
random() : generates a random number between 0 and 1
randint(start number, End Number) : generates a random integer in a given range
shuffle(L) : Shuffles a list
sleep(seconds): pauses the process for the specified amount of time before continuing execution
date.today().year : current year
itemgetter - used to fetch items inside dictionaries
urllib.request.urlopen( URL of a site ) - attempts to access a site
variable_with_site_url.getcode() - Returns a code for the access attempt, with 200 meaning successful.
phrase[9:21] - Returns the value of phrase starting at position 9 and going up to 20 (python ignores the last one)
len(f) - number of characters in a string or list
(T).count() - counts the amount of a character within a string / list
(T).find() - shows the position of a character within a string / list. if it doesn't exist it returns -1
(T).index(Searched value, Start) - shows the position of the searched value inside a compound variable
in - returns a boolean value
del(Variable)
replace() - Replaces a string/list value with another typed string
upper() - Converts a string to uppercase
lower() - Converts a string to lowercase
capitalize() - Converts a string to lowercase and makes the first letter uppercase
title() - Capitalizes the first letter of each word in a string
strip() - Removes useless spaces at the beginning and end of the string
rstrip() - Removes spaces on the right
lstrip() - Removes spaces on the left
string.center(Number of characters) - Centers the text in the defined Number of characters
split() - Splits a string into a list
'separator'.join(phrase) - joins a string // example '-'.join(phrase) joins the string and separates it by '-'
zfill(number) - adds a certain amount of zeros to a string
runs the program linearly from top to bottom executing all commands
Write everything in one line example: print('1' if var <=3 else '2')
It executes only one conditional block
executes more than one conditional block ex : else
Conditions within conditions
if - if
elif - Always needs an if beforehand
else - Can only be used once in the Nest block with if or elif
for x in range(Start Number, End Number(The Result being EN-1), what is the iteration (Example Add(1) or subtract(-1)) )
for x enumerated( Compound Variable ) returns the value and the index.
while not (Boolean Value):
while true: infinite loop
break - interrupts the repetition loop
continue - continues the loop, and if it runs a part without a continue, it skips the rest of the current loop iteration
You can interpolate collections, for example: Dictionaries inside lists
Character - ()
Tuples are Immutable
sorted(T) - sorts the tuple but doesn't store the value, use a variable to store it
Character - []
sum(L) - sums all values in a list
L.append() - adds a value to the list
L[index] - shows the item at the indicated position
L.insert(Position,Value) - adds a value at a selected position
L.remove() - removes a value from the list
max(L) - Shows the highest value in the list
min(L) - Shows the lowest value in the list
(L).sort - Sorts the list
del L[Index] - Delete an item from a list by the chosen Index
L.pop(Index) - Delete an item from a list by the chosen Index, or if no argument is passed it removes the last value.
L.remove(value) - Remove the searched item by the defined value(Content)
L1 = L2 - the '=' sign creates a link between lists, where changing one affects the other
L1 = L2[:] - copies the list, without creating a link
L1.append(L2[:]) - Copies list L2 Inside list L1
L1 = [['Value1','Value2'],['Value1','Value2']] - Declares a list inside a list
print(L[0][0]) - shows index 0 inside list [0]
L.clear() - Clears a list
L.choice - Curates an item randomly inside the list
Character - {}
Main difference between a list : Has Literal indexes (Letters/Words)
D['Literal Index'] = 'Value' - Adds a value to the variable
del D['Literal Index'] - Deletes the value at the typed index.
D.values() - Returns the Values
D.keys() - Returns the Literal Indexes
D.items() - Returns both the Indexes(Keys), and the Values(values)
D.copy() - Copies the values from a dictionary without creating a link, (for using in loops etc)
D1 = sorted(D2.items(), key=itemgetter(dictionary index being 0 for keys, and 1 for values) ) - Sorts in ascending order
a dictionary based on the values
\033[Style;Text;Back;m
\033[0;33;44m
0 - none
1 - bold
4 - underline
7 - negative
30 - white
31 - red
32 - green
33 - yellow
34 - blue
35 - magenta
36 - cyan
37 - gray
40 - white
41 - red
42 - green
43 - yellow
44 - blue
45 - magenta
46 - cyan
47 - gray
bin() - convert from decimal to binary
oct() - convert from decimal to Octal
hex() - convert from decimal to hexadecimal
They are routines, which may or may not return values and may or may not use parameters
def function():
Routine/algorithm
def function(parameter):
print('-'*10)
print(parameter)
print('-'*10)
def counter(*num) - receives multiple parameters
help(internal function) - Returns help about an internal function
Documentation string, that is, Help for a function you created
One line after defining the function, create 3 double quotes and close them. Anything inside is the 'manual on how to use your function'
def function(a,b,c):
"""
-> here goes a direct description
:param a: Description of parameter a
:param b: Description of parameter b
:param c: Description of parameter c
:return: whether the function returns or not and if so what the return is
"""
Function code starts here
creates parameters that may or may not be inserted without influencing the functionality of the program
assign a value to a variable in case it is not inserted
def function(a,b,c=0(if c receives no value it will receive 0)):
s = a + b + c
print(s)
place where the variable will exist and where it will no longer exist
exists only in one part of the program
exists everywhere in the program
In python, when defining a global and a local variable with the same name, it will create 2 different unlinked variables. To link them, you must use the global command
def function():
global (variable name)
function code starts here
place the return command on the last line of the function along with a variable containing the value you want to return
def function(a,b,c):
s = a + b + c
return s
the separation of the main program from the functions
- Divide a Large program
- Increase readability
- Facilitate maintenance
Create a .py file in the same folder as the main program with the desired name
inside put all the functions you need, after that in the main program use import file_name, or from file_name import function_name
- Code organization
- Easy maintenance
- Hiding detailed code
- Reusability in other projects
A folder with various Modules, allowing you to separate modules by subject
Just create a folder, within the project it already recognizes that it can potentially be a package
Always inside a package you must have a file named: __init__.py where the functions will reside
When projects start to get very large
Typing errors, the typed command does not exist
they are errors that happen due to incorrect assignment, receiving a number different from what was expected, etc
check if something is possible to execute without resulting in an error, if there is a problem, perform another command
put try: break a line and write the command it should try, after writing the command block break a line 'except:' break a line, and write what to do in case of an error, and if necessary else: and put what succeeded. finally:, writes either way with or without an error
try:
Command block
except: / variant / except Exception as error:
if evaluating resulted in an error / variant / print(error.__class__) it shows what the error was
(optional) else:
if it succeeded
(optional) finally:
executes either way if it succeeded or not
you can create numerous excepts and specify for each of them what the error is and how to handle each one:
except TypeError:
Handling for the TypeError.
except ValueError:
Handling for the ValueError
variable = open('Path you want to create/Read',Parameter)
‘r’ - Transforms into a variable ready for reading
‘a’ - Transforms into a variable ready to append text
‘w’ - Transforms into a variable ready to replace everything and put new text
after each letter you can put + so that if the file doesn't exist it creates it, example: a+
encoding=’utf-8’ - Additional Parameter to write/read/save files containing accents
variable_ready_to_[append/replace]_text.write(‘desired text\n’) (the ‘\n’ is optional since it breaks the line, but it is highly recommended because if you add multiple texts it won't break lines automatically)
print(variable_ready_to_read_text.read()) - reads the file value including line breaks