Skip to content

Latest commit

 

History

History
508 lines (404 loc) · 16 KB

File metadata and controls

508 lines (404 loc) · 16 KB

Python Notes

Summary

General Notes

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()

Primitive Types

  • int - integer
  • bool - boolean / true, false
  • float - floating point numbers
  • str - text string

Arithmetic Operations

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Power: **
  • Division (floor): //
  • Remainder/Modulo: %
  • Comparison: ==
  • Assignment: =

Order Of Precedence

  1. :()
  2. :**
  3. :*,/,//,%
  4. :+,-

Print Notes

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}'

Libraries

Math

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

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

Time

sleep(seconds): pauses the process for the specified amount of time before continuing execution

Datetime

date.today().year : current year

Operator

itemgetter - used to fetch items inside dictionaries

Urllib

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.

Text Handling

Location

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)

Transformations

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

Division

split() - Splits a string into a list

Joining

'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

Simple and Compound Conditional Structures

Types

Sequential

runs the program linearly from top to bottom executing all commands

Pythonize

Write everything in one line example: print('1' if var <=3 else '2')

Simple

It executes only one conditional block

Compound

executes more than one conditional block ex : else

Nested

Conditions within conditions

If

if - if elif - Always needs an if beforehand
else - Can only be used once in the Nest block with if or elif

Repetition Structure or Loops or Iterations

Loop With Control Variable

For

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.

Loop With Logical Test

While

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

Collections

Notes

You can interpolate collections, for example: Dictionaries inside lists

Tuples

Character - ()

Tuples are Immutable sorted(T) - sorts the tuple but doesn't store the value, use a variable to store it

Lists

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

Dictionaries

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

Colors in the Python Terminal

Ansi

\033[Style;Text;Back;m \033[0;33;44m

Style

0 - none
1 - bold
4 - underline
7 - negative

Text

30 - white
31 - red
32 - green
33 - yellow
34 - blue
35 - magenta
36 - cyan
37 - gray

Back

40 - white
41 - red
42 - green
43 - yellow
44 - blue
45 - magenta
46 - cyan
47 - gray

Extra data conversion

bin() - convert from decimal to binary
oct() - convert from decimal to Octal
hex() - convert from decimal to hexadecimal

Functions

What Is It

They are routines, which may or may not return values and may or may not use parameters

Basic Function Declaration Without Parameters

def function():
 Routine/algorithm

Basic Function Declaration With Parameters

def function(parameter):
    print('-'*10)
    print(parameter)
print('-'*10)

Pack Parameters - Receive Multiple Parameters

def counter(*num) - receives multiple parameters

Interactive Help

help(internal function) - Returns help about an internal function

Docstrings

What Is It

Documentation string, that is, Help for a function you created

How To Create

One line after defining the function, create 3 double quotes and close them. Anything inside is the 'manual on how to use your function'

Example

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

Optional Parameters

What Is It

creates parameters that may or may not be inserted without influencing the functionality of the program

How To Create

assign a value to a variable in case it is not inserted

Example

def function(a,b,c=0(if c receives no value it will receive 0)):
    s = a + b + c
print(s)

Variable Scope

Scope Definition

place where the variable will exist and where it will no longer exist

Local Scope

exists only in one part of the program

Global Scope

exists everywhere in the program

Hint

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

Example
def function():
    global (variable name)
    function code starts here

Return Results

How To Create

place the return command on the last line of the function along with a variable containing the value you want to return

Example

def function(a,b,c):
    s = a + b + c
    return s

Modules

What Is It

the separation of the main program from the functions

Focus

  • Divide a Large program
  • Increase readability
  • Facilitate maintenance

How To Create

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

Advantages

  • Code organization
  • Easy maintenance
  • Hiding detailed code
  • Reusability in other projects

Packages

What Is It

A folder with various Modules, allowing you to separate modules by subject

How To Create

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 To Use

When projects start to get very large

Error Handlings and Exceptions

Error Types

Syntax

Typing errors, the typed command does not exist

Exception

they are errors that happen due to incorrect assignment, receiving a number different from what was expected, etc

Error Handling

What Is It

check if something is possible to execute without resulting in an error, if there is a problem, perform another command

How To Create

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

Example

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

Except

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

Handling Txt file

Prepare To Read Save Replace

variable = open('Path you want to create/Read',Parameter)

Parameters To Create Read

‘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

Save Text

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)

Read Text File

print(variable_ready_to_read_text.read()) - reads the file value including line breaks