Python 3
Last updated
Last updated
__name__ == '__main__'
Adding this to a python file script will ensure that everything inside this condition will be only ran, if the script file was runned directly.
This happens because when you import functions from other files, python runs the entire file. So if you have code executing there, it will execute it on the import.
To avoid this you put this code inside this condition.
https://www.w3schools.com/python/python_strings_methods.asp
Can be accessed like arrays
: str[0]
.
You can use in
to check substrings.
False
None
0
""
()
, []
and {}
[]
<class 'list'>
https://www.w3schools.com/python/python_lists_methods.asp
Are ordered, changeable and allow duplicates.
Ordered means the items have a defined order, and that order will not change.
Changeable means that we can change, add, remove items after the list was created.
Allow duplicates.
It's items are indexed [0]...[n]
.
Can have items of different data types.
Access
Can have negative indexing list[-1]
that will access from end.
Can also index a range list[2:5]
, not including 5
.
Check existence
With in
.
Changing and Inserting values
You can change a range of values list[2:5] = ["", "", ""]
.
Inserting values
Insert values in a fixed position with list.insert(i, value)
.
Inserting at the end with list.append(value)
.
Merging lists
You can merge lists with list.extend(list)
or by adding list = list + list2
.
Removing values
Removing by value with list.remove(value)
.
Removing by index with list.pop(i)
.
Removing last item with list.pop()
.
Clear the list with list.clear()
.
Unpacking values (Destructuring)
Using *
will throw the rest of the list to the variable.
List Comprehensions
Sorting lists
You can sort with list.sort(key = myFunc)
.
You can reverse a list list.reverse()
.
()
<class 'tuple'>
Are ordered, unchangeable and allow duplicates.
Unchangeable means that we cannot change, add or remove items after the tuple was created.
It's items are indexed [0]...[n]
.
Can have items of different data types.
Creating a tuple with one item requires a comma
(value,)
Access
Can have negative indexing tuple[-1]
that will access from end.
Can also index a range tuple[2:5]
, not including 5
.
Changing/Inserting and Deleting values
Since they are immutable, you must transform them in a list
, or create a new tuple.
Unpacking values (Destructuring)
Using *
will throw the rest of the list to the variable.
Merging and Multiplying Tuples
You can merge tuples with tup1 + tup2
.
You can multiply the values of a tuple with tup1 * 5
, and this will copy the values 5
times inside the tuple.
{}
<class 'set'>
https://www.w3schools.com/python/python_sets_methods.asp
Are unordered, unchangeable, unindexed and cannot have duplicates.
Unordered means that items do not have a defined order.
Unchangeable means you cannot change its values after it was created, BUT you can INSERT new items and DELETE.
Unindexed means that items cannot be referenced by index or key.
Access
Although items cannot be accessed by index, you can loop a set with for x in set
.
Check existence
With in
.
Adding new values
Add new values with set.add(value)
.
Merging sets
Merge another set or iterable with set.update(otherSet)
.
Removing values
Remove a value with set.remove(value)
. (Will raise error if value DONT exists)
Remove a value with set.discard(value)
. (Will NOT raise error if value DONT exists)
Remove a random value with set.pop()
.
Combining sets
Subtrating sets (Exclusive elements)
Shared sets (Intersection)
Unique sets elements
{}
<class 'dict'>
Are ordered >3.6
collections, storing data in key: value
pairs.
Ordered means that items have a defined order.
Changeable means that we can change, add and remove items after its creation.
Don't allow Duplicates with the same key.
Access
You can access by key dict[key]
.
You can access by dict.get(key)
.
Check existence
You can check if a key
exists with in
.
Keys and values
You can get the keys in a list with dict.keys()
.
You can get the values in a list with dict.values()
.
You can get a list of tuples with dict.items()
returning [(key, value), ...]
.
Merge dicts
You can merge dicst with dict.update(otherDict)
.
Removing items
By key with dict.pop(key)
or del dict[key]
.
Remove the last item (Only >3.6
) with dict.popitem()
.
Clearing dict
You can delete a dict with del dict
, but this will also delete the variable.
You can clear a dict with dict.clear()
.
Looping with key, value
Regular for
will give you access onlly to the key.
To loop having the key
and value
do it with .items()
.
Copying dicts
You cannot copy a dictionary values by just assingning it to a new variable. Doing it like this will only copy the reference.
You must use newDict = dict.copy()
.
Or use the dict()
constructor.
Python does not natively supports Arrays
To use them you must import them from NumPy
library.
They basically work just like a List
.
range
functionrange(start, end, step)
Returns an iterator from [start, end)
, and you can add a step
number like:
The current range index will add in steps of 2
.
Don't convert range()
to list(range())
range
map
filter
It is going to occupy A LOT more memory.
Else
in For
loopsAn else
statement after a for
, is a block of code that will be executed after the loop ends.
If the for loop was breaked with break
, than the else
WILL NOT be executed.
pass
statementUse pass
to fill empty blocks like if
, for
, class
or etc.
>3.6
You can state the type in declaration.
Usefull for hiting and intelisense.
For code more readable only.
Create a class with class ClassName:
.
Then create an object from this class with obj = ClassName()
.
__init__()
functionAll classes have a function __init__()
which is basically the class constructor.
__str__()
functionControls what should be returned when the class object is represented as a string.
If not set, the string representation of the object is returned.
Use it to format the way you wish when printed.
self
parameterIs a reference to the current instance of the class.
Every function inside the class that have to access the class properties, MUST have a self
as FIRST parameter.
You do not have to name it self
, you can call it whatever you want, it just HAVE to be the first parameter.
Allows us to define a class that inherits all the methods and properties from another class.
To do this you simply inform the Parent class name when creating the class:
To overwrite it you just declare a constructor for the child class.
You can also use super()
:
All these class have a move()
method, since they inherit from Vehicle
, and some class overwrite and some don't.
Also check the use of pass
in the Car
class, since it does nothing but inherit.
Are small anonymous functions, that can have multiple arguments but only one returned expression.
You can assign them to variables.
lambda arguments : expression
Are objects which implements the iterator protocol:
__iter__()
__next__()
string
, List
, Tuple
, Dictionary
and Set
are all iterable objects.
You can call iter()
function on them and iterate them with next()
.
for
loops automatically create iterators on objects and execute next()
at each loop.
You can create iterators by implementing the __iter__()
and __next__()
methods.
To avoid an iterator running forever, raise StopIteration
.
Variable creation is limited by the scope of where it is created.
A variable created in the main body of the Python code is a global variable and belongs to the global scope.
Global variables
Creating or referencing global variables inside blocks can be done with global
keyword.
nonlocal
variable reference
Using nonlocal
to a variable will make the reference to the variable be of the outer scope.
Useful with nested functions.
Consider a module to be the same as a code library.
A file containing a set of method, classes or variables to be included.
mymodule.py
Transform this
to this
This operator firts evaluetes the expression or function and than assign it to the variable.
Take a look at Partials
You can raise exceptions with raise
keyword.
raise Exception("Some exception")
.
raise TypeError("Only integers")
.
And many other types.
else
block executes code when there is no error.
finally
block executes code regardless if there were errors or not.
You can have multiple except
statements for different exceptions.
This is a better aprouch than using Any
type.
If a parameter is of a type list
or any mutable type, and has a default value - like an empty list -, calling the function multiples times might produce bugs, because the calls may share the same list object.
should be
You can create custom decorators also, and import them in your scripts.
Like decorators, for performance, and etc.
Cache result of functions.
You can also see the cached info
It will call this decorated function when script terminates, for whatever reason.
Interesting for DB connection close.
You can also unregister these functions
Shuffles a list in place.
Returns a random number between 0 and 1
.
Returns a random int
number within a specified range [beginning, end]
.
Works the same as randint
, but with a specified range [beginning, end)
.
It also let's you provide a step
, randrange(beginning, end, step)
.
Selects a random element from a list.
Selects a specified k
number of random elements from a list. (By default 1
element)
You can also provide a weight
parameter, which will be a tuple | list
of float
that will be applied to the elements. (Must be in the same order as the element's list)
Returns a list
.
Does the same as choices
, but it only retuns unique
elements. (Each will only appear once)
This means k
must be greater or equal to the length of the provided list.
If the element is repeated inside the provided list, IT CAN repeat.
It will "save"
the state of the other random functions, so that, they will reproduce the same result if necessary.
pywhatkit
camelot