- Basics
- In Python we have the following data types:
- int
- float
- bool
- str
- list
- tuple
- set
- dict
- complex (imaginary numbers)
bin(5)-
Gives us the binary representation of
5, that is0b101->0brepresents in python the this is abinary numberthe actual binary is number is101 -
to convert a
binary numberinto anintegerwe can use theint()with the base of2
int('0b101', 2)-
Use
'''to print multiple linesmultiple_lines = ''' print multiple lines ''' print(multiple_lines)
-
To escape a special character we use
\before the characterweather = "It\'s \"kind of\" sunny" print(weather)
\t- Tab\n- New Line\\- Backslash\r- Carriage Return\b- Backspace\f- Form Feed\ooo- Octal value\xhh- Hex value
-
Using Python 3 format
name = 'Roger' age = 33 print(f'Hi {name}. You are {age} years old')
-
Using Python 2 format
- ATTENTION the
.format()is right after the string. The.format()will evaluate thestring
name = 'Roger' age = 33 print('Hi {0}. You are {1} years old'.format(name, age))
- ATTENTION the
-
Using
custom variables- Using custom variables we have to call them between
{}
print('Hi {new_name}. You are {new_age} years old'.format(new_name="Yumi", new_age=3))
- Using custom variables we have to call them between
-
To work with string we have
[start:stop:stepover]- the
startstarts at index0 stepover, by default the step over is1but we can choose any number of our choice
numbers = '0123456' print(numbers[1:]) # 123456 print(numbers[:3]) # 012 print(numbers[::1]) # 0123456 print(numbers[-1]) # 6 print(numbers[::-1]) # 6543210
- the
- String are immutable, this means that once we assign a value to a string we cannot change the content (different from JavaScript), the only way to change the string content is to re-assign a complete new value to the variable
| Built-in Functions | ||||
|---|---|---|---|---|
| abs() | delattr() | hash() | memoryview() | set() |
| all() | dict() | help() | min() | setattr() |
| any() | dir() | hex() | next() | slice() |
| ascii() | divmod() | id() | object() | sorted() |
| bin() | enumerate() | input() | oct() | staticmethod() |
| bool() | eval() | int() | open() | str() |
| breakpoint() | exec() | isinstance() | ord() | sum() |
| bytearray() | filter() | issubclass() | pow() | super() |
| bytes() | float() | iter() | print() | tuple() |
| callable() | format() | len() | property() | type() |
| chr() | frozenset() | list() | range() | vars() |
| classmethod() | getattr() | locals() | repr() | zip() |
| compile() | globals() | map() | reversed() | import() |
| complex() | hasattr() | max() | round() |
- Lists are like Arrays in other languages, it's an ordered list
-
With list slicing we create a new list
- One way to create a new list with all the values from the previous list is by adding
[:]
amazon_cart = [ 'notebook', 'sunglass', 'toys', 'grapes' ] new_list = amazon_cart[:] print(new_list) # ['notebook', 'sunglass', 'toys', 'grapes'] # another option is to use .copy(); new_list2 = amazon_cart.copy(); print(new_list2) # ['notebook', 'sunglass', 'toys', 'grapes']
- One way to create a new list with all the values from the previous list is by adding
-
the
.append()method changes the list in place, it doesn't return a new new copy of the list modified.basket = [1, 2, 3, 4, 5] new_list = basket.append(100) print(basket) print(new_list) # [1, 2, 3, 4, 5, 100] # None
-
the
.insert()method inserts a new item base on the index.- Just like
.append(),.insert()modifies the list in place (it doesn't return anything)
basket = [1, 2, 3, 4, 5] basket.insert(3, 100) print(basket) # [1, 2, 3, 100, 4, 5]
- Just like
-
the
.extend()method extends the list, in other words, it concatenates two objects (lists).extend()modifies the list in place
basket = [1, 2, 3, 4, 5] basket.extend([100, 101]) print(basket) # [1, 2, 3, 4, 5, 100, 101]
-
the
.pop()method removes the index from the list and return the removed itembasket = [1, 2, 3, 4, 5] removed_item = basket.pop(3) print(removed_item) # 4
-
the
.remove()method removes the value of the list, but doesn't return anythingbasket = [1, 2, 3, 4, 5] basket.remove(3) print(basket) # [1, 2, 4, 5]
-
the
.clear()method removes everything in place from the list.basket = [1, 2, 3, 4, 5] basket.clear() print(basket) # []
-
the
.index()method, return the index of the item that we are search on the listbasket = [1, 2, 3, 4, 5] print(basket.index(2)) # 1
- We can also give a start and stop point to search for the item
.index(value, start, stop)
-
the
'value' in object/list, we can check True/False if the item exists in the listbasket = ['a', 'b', 'c', 'd', 'e'] print('a' in basket) # True print('f' in basket) # False
-
the
.count()method counts how many time the item occursbasket = ['a', 'b', 'c', 'd', 'e' , 'd'] print(basket.count('d')) # 2
-
the
.sort()method sorts the list in placebasket = ['a', 'b', 'c', 'd', 'e' , 'd'] basket.sort() print(basket) # ['a', 'b', 'c', 'd', 'd', 'e']
-
the
sorted()function do the same thing as.sort()but it creates a new sorted arraybasket = ['a', 'b', 'c', 'd', 'e' , 'd'] print(sorted(basket)) print(basket) # ['a', 'b', 'c', 'd', 'd', 'e'] # ['a', 'b', 'c', 'd', 'e', 'd']
-
the
.reverse()method reverts the list in placebasket = ['a', 'b', 'c', 'd', 'e' , 'd'] basket.reverse() print(basket) # ['d', 'e', 'd', 'c', 'b', 'a']
-
create a list using
range()new_list = list(range(1, 100)); print(new_list)
-
the
.join()method iterates through the list and add join with the left part (sentence in this case)sentence = ' ' new_sentence = sentence.join(['hi', 'my', 'name', 'is', 'roger']) print(new_sentence) # hi my name is roger # alternative new_sentence = ' '.join(['hi', 'my', 'name', 'is', 'roger']) print(new_sentence) # hi my name is roger
-
We can assign variables to each item of the list
a, b, c, *other, last_item = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(a) print(b) print(c) print(other) print(last_item) # 1 # 2 # 3 # [4, 5, 6, 7, 8] # 9
-
Dictionary is equal to an object in
JavaScript, it's un-ordered key/value pairsdictionary = { 'a': 1, 'b': 2 } print(dictionary['a']) # 1
-
the
.get()method accepts the first argument is thekeythat we are looking for, if not found we can assign a default value (second argument).user = { 'basket': [1, 2, 3], 'greet': 'hello', } print(user.get('age',55)) # 55 user2 = { 'basket': [1, 2, 3], 'greet': 'hello', 'age' : 20 } print(user.get('age',55)) # 20
-
<value> in dict.key(), loops through the dictionary and checks if the key existsuser = { 'basket': [1, 2, 3], 'greet': 'hello', 'age': 20 } print('hello' in user.keys()) # false print('greet' in user.keys()) # true
-
<value> in dict.value(), loops through the dictionary and checks if the value existsuser = { 'basket': [1, 2, 3], 'greet': 'hello', 'age': 20 } print('hello' in user.values()) # true
-
dict.items(), returns an array of tuples where the fist position ([0]) is the key and the second position ([1]) is the value (the value could be anything, number, string, object...)user = { 'basket': [1, 2, 3], 'greet': 'hello', 'age': 20 } print(user.items()) # dict_items([('basket', [1, 2, 3]), ('greet', 'hello'), ('age', 20)])
-
.clear(), clear the object in place, it removes all the items of the object. In the end we have and empty object -
.copy()creates a brand new copy of the object (not referencing the pointer, it creates a new object) -
.pop()removes the target item and returns the removed item. -
.update()updates an existing item or adds if not existuser = { 'basket': [1, 2, 3], 'greet': 'hello', 'age': 20 } user.update({'age': 55}) print(user) user.update({'ages': 100}) print(user) # {'basket': [1, 2, 3], 'greet': 'hello', 'age': 55} # {'basket': [1, 2, 3], 'greet': 'hello', 'age': 55, 'ages': 100}
-
it's just like a list but we cannot change the content
days_of_the_week = ('monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday') shopping_cart = ['cucumbers', 'potatoes', 'celery', 'oranges', 'avocado', 'grapes', 'banana'] days_of_the_week[0] = 'not monday' print(days_of_the_week) # TypeError: 'tuple' object does not support item assignment shopping_cart[2] = 'cheese' print(shopping_cart) # ['cucumbers', 'potatoes', 'cheese', 'oranges', 'avocado', 'grapes', 'banana']
-
working we tuples, we only have 2 methods available
.count()returns how many times the item appeared.index()returns the index of the item (the first found index)
-
Removes all the duplicates from an "
object"unique_set = {1, 3, 5, 4, 3, 2, 6} print(unique_set) # {1, 2, 3, 4, 5, 6}
-
.difference()returns the difference (who is calling)my_set = {1, 2, 3, 4, 5} your_set = {4, 5, 6, 7, 8, 9, 10} print(my_set.difference(your_set)) # {1, 2, 3}
-
.discard()removes an item from the setmy_set = {1, 2, 3, 4, 5} my_set.discard(5) print(my_set) # {1, 2, 3, 4}
-
.difference_update()returns the difference (who is calling) and modifies the original setmy_set = {1, 2, 3, 4, 5} your_set = {4, 5, 6, 7, 8, 9, 10} my_set.difference_update(your_set) print(my_set) # {1, 2, 3}
-
.intersection()or&returns the intersection between two setsmy_set = {1, 2, 3, 4, 5} your_set = {4, 5, 6, 7, 8, 9, 10} # alternative 1 my_set.intersection(your_set) print(my_set) # {4, 5} # alternative 2 print(my_set & your_set) # {4, 5}
-
.isdisjoint()returnstrue/falsewheretruemeans that the two sets don't have items in commonmy_set2 = {1, 2, 3, 4, 5} your_set2 = {6, 7, 8, 9, 10} print(my_set2.isdisjoint(your_set2)) # True
-
.union()or|concatenate two sets and remove duplicatesmy_set = {1, 2, 3, 4, 5} your_set = {4, 5, 6, 7, 8, 9, 10} print(my_set.union(your_set)) # {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
-
.issubset()checks if the left part (who is calling) is a subset of the other set, returnstrue/falsemy_set3 = {4, 5} your_set3 = {4, 5, 6, 7, 8, 9, 10} print(my_set3.issubset(your_set3)) # True
-
.issuperset()checks if the left part (who is calling) is a superset of the other set, returnstrue/falsemy_set3 = {4, 5} your_set3 = {4, 5, 6, 7, 8, 9, 10} print(your_set3.issuperset(my_set3)) # True
-
Ternary operators are more commonly known as conditional expressions in Python. These operators evaluate something based on a condition being true or not. They became a part of Python in version 2.4
value_if_true if condition else value_if_false
is_nice = True state = "nice" if is_nice else "not nice" print(state) # nice
-
==checks for equality value -
ischecks for memory locationprint(True == True) print('1' == '1') print([] == []) print(10 == 10) print([1,2,3] == [1,2,3]) # True # True # True # True # True print() print(True is True) print('1' is '1') print([] is []) print(10 is 10) print([1,2,3] is [1,2,3]) # True # True # False # True # False
-
We can iterate through a
list/dictionary/tuples/sets/stringand use a shorthand to get thekey/valueuser = { 'name': 'Roger', 'age': 33, 'can_swim': False } for key, value in user.items(): print(key, value) print() for value in user.values(): print(value) print() for key in user.keys(): print(key)
-
We can use
range()that creates a special kind of object that we can iterate -
range(start, stop, step)- by default the step is not specified is
1
for number in range(0,100): print(number)
- by default the step is not specified is
- Using enumerate, it gives us accesses to the index for the
list/dictionary/tuples/sets/string
for index, value in enumerate('Helllloooooo'):
print(index, value)-
We can use
elsecondition withwhile. Theelsepart will be only executed if thewhileloop executed successfullyi = 0 while i < 10: print (i) i += 1; break else: print('This msg will never be printed') # 0 j = 0 while j < 10: print (j) j += 1; else: print('This msg will be printed after 9') # 0 # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # This msg will be printed after 9
-
Function expressions do not exist in Python
- Every function in Python is defined using the def keyword and are never assigned to variables as in JavaScript.
msg = 'Welcome home' def say_greetings(name, emoji): print(f'{msg}, {name} {emoji}') say_greetings('Roger', 'ππ»')
-
With
keywordswe don't need to pass the parameters in order as it appearsmsg = 'Welcome home' def say_greetings(name, emoji): print(f'{msg}, {name} {emoji}') say_greetings(emoji = 'ππ»', name = 'Roger')
-
We can assign default parameters if none is given
msg = 'Welcome home' def say_greetings(name = 'Guest', emoji = 'π'): print(f'{msg}, {name} {emoji}') say_greetings()
-
Docstringsis a way to add extra info / definitions to our functiondef extra_info_function(a): ''' Info: this function prints param a ''' print(a) extra_info_function('!!!!')
-
an alternative, we can use
help()to know more about the function, we just need to point to the function, ot execute the function (())help(extra_info_function)
-
we could also use
DunderorMagic Methods- Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name. Dunder here means βDouble Under (Underscores)β. These are commonly used for operator overloading. Few examples for magic methods are: init, add, len, repr etc.
- Python lets our classes inherit from built-in classes. An inheriting child class of a built-in shares all the same attributes, including methods as the built-in. We can take advantage of core built-in functionality, but customize selected operations through the use of magic methods.
print(extra_info_function.__doc__)
- Rule:
params,*args,default parameters,**kwargs
def super_func(*args, **kwargs):
total = 0
for items in kwargs.values():
total += items
return sum(args) + total
print(super_func(1,2,3,4,5, num1 = 5, num2 = 10))
# 30- More about Anonymous Function
- Python has a different sort of anonymous functions
- Python does have a the concept of anonymous functions but they are called lambda functions.
Think of lambda functions as a JavaScript arrow function that implicitly returns a single expression's result.
```Python
nums = [1, 3, 2, 6, 5]
odds = list( filter(lambda num: num % 2, nums) )
print(odds)
#[1, 3, 5]
```
```Python
double = lambda x: x * 2
print(double(5))
# 10
```