# Lucas Python Sheet --- [TOC] ## Input and Output Display something on the console: ```python print("Hello World") # >>> Hello World ``` Separate multiples print instructions with a coma: ```python print("Lucas is", 18, "years old.") # >>> Lucas is 18 years old. ``` Input something from the console: ```python name = input("Type your name: ") print(name) # >>> Type your name: Lucas # >>> Lucas ``` Be careful! The type of the input is always String! Convert it if you need: ```python age = int(input("Type your age: ")) print(age + 1) # >>> Type your age: 18 # >>> 19 ``` ## Types | Categories | Data Type | |:--------------:|:-----------------------------------------------------------:| | Text Type | <kbd>str</kbd> | | Numeric Types | <kbd>int</kbd> <kbd>float</kbd> <kbd>complex</kbd> | | Sequence Types | <kbd>list</kbd> <kbd>tuple</kbd> <kbd>range</kbd> | | Mapping Type | <kbd>dict</kbd> | | Set Types | <kbd>set</kbd> <kbd>frozenset</kbd> | | Boolean Type | <kbd>bool</kbd> | | Binary Types | <kbd>bytes</kbd> <kbd>bytearray</kbd> <kbd>memoryview</kbd> | Getting the Data Type: ```python x = 5 y = "Hello" print(type(x)) print(type(y)) # >>> <class 'int'> # >>> <class 'str'> ``` Examples of Data Type: ```python x = "Hello World" # str x = 20 # int x = 20.5 # float x = 35e3 # float x = 1j # complex x = ["apple", "banana", "cherry"] # list x = ("apple", "banana", "cherry") # tuple x = range(6) # range x = {"name" : "John", "age" : 36} # dict x = {"apple", "banana", "cherry"} # set x = frozenset({"apple", "banana", "cherry"}) # frozenset x = True # bool x = b"Hello" # bytes x = bytearray(5) # bytearray x = memoryview(bytes(5)) # memoryview ``` ### Types Conversion Examples of type conversion: ```python x = str(3.4) # str x = int("20") # int x = float("20.5") # float ``` Be carful! For some cases the data is modified: ```python x = int(20.7) print(x) # >>> 20 ``` ## Strings String literals in python are surrounded by either single quotation marks, or double quotation marks: ```python print("Hello") print('Hello') # >>> Hello # >>> Hello ``` Use of multiple lines strings by using three double quotation marks, or three single quotation marks: ```python text = """Lorem ipsum dolor sit amet, consectetur adipiscing elit.""" print(text) # >>> Lorem ipsum dolor sit amet, # >>> consectetur adipiscing elit. ``` Strings in Python are arrays of bytes representing unicode characters: ```python text = "Hello World!" print(text[0]) print(text[2:5]) print(len(text)) # >>> H # >>> llo # >>> 12 ``` ### Strings methods The <kbd>strip()</kbd> method removes any whitespace from the beginning or the end: ```python text = " Hello, World! " print(text.strip()) # >>> "Hello, World!" ``` The <kbd>upper()</kbd> / <kbd>lower()</kbd> method returns the string in upper / lower case: ```python text = "Hello, World!" print(text.upper()) print(text.lower()) # >>> HELLO, WORLD! # >>> hello, world! ``` The <kbd>replace()</kbd> method replaces a string with another string: ```python text = "Hello, World!" print(text.replace("H", "J")) # >>> Jello, World! ``` The <kbd>split()</kbd> method splits the string into substrings. Enter the separator as argument: ```python text = "Hello, World!" print(text.split(" ")) print(text.split(",")) # >>> ['Hello,', 'World!'] # >>> ['Hello', ' World!'] ``` The <kbd>count()</kbd> method returns the number of times a specified value appears in the string. ```python text = "I love apples, apple are my favorite fruit" print(text.count("apple")) # >>> 2 ``` ### String Concatenation To concatenate, or combine, two strings you can use the + operator: ```python a = "Hello" b = "World" c = a + " " + b print(c) # >>> Hello World ``` Convert the type of a variable before adding it to a string: ```python quantity = 3 print("I want " + str(quantity) + " apples.") # >>> I want 3 apples. ``` The <kbd>format()</kbd> method takes unlimited number of arguments, and are placed into the respective placeholders: ```python quantity = 3 nb = 567 price = 49.95 order = "I want {0} pieces of item {1} for {2} dollars." print(order.format(quantity, nb, price)) # >>> I want 3 pieces of item 567 for 49.95 dollars. ``` ## Variables <!-- invert two variable, define with coma --> Variables are containers for storing data values. Some rules for Python variables: * A variable name must start with a letter or the underscore character * A variable name cannot start with a number * A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) * Variable names are case-sensitive (age, Age and AGE are three different variables) Assign a value to a variable: ```python x = 5 y = "Hello World" ``` In Python variables do not need to be declared with any particular type and can even change type after they have been set: ```python x = 4 # x is of type int x = "Sally" # x is now of type str print(x) # >>> Sally ``` Use comas in order to assign values to multiple variables: ```python x, y, z = "Orange", "Banana", "Cherry" print(x) print(y) print(z) # >>> Orange # >>> Banana # >>> Cherry ``` This can be useful when you have to invert two variables: ```python x = "Orange" y = "Banana" print(x, y) x,y = y,x print(x, y) # >>> Orange Banana # >>> Banana Orange ``` If you use the <kbd>global</kbd> keyword, the variable belongs to the global scope: ```python def myfunc(): global x x = "fantastic" myfunc() print("Python is " + x) # >>> Python is fantastic ``` ## Operators <!-- Comparaison --> <!-- Lists --> Operators are used to perform operations on variables and values. ### Arithmetic Operators | Operator | Name | Example | |:--------:|:--------------:|:----------:| | + | Addition | x + y | | - | Subtraction | x - y | | * | Multiplication | x * y | | / | Division | x / y | | % | Modulus | x % y | | ** | Exponentiation | x ** y | | // | Floor division | x // y | ### Assignment Operators | Operator | Example | Same As | |:--------:|:-------:|:----------:| | = | x = 5 | x = 5 | | += | x += 3 | x = x + 3 | | -= | x -= 3 | x = x - 3 | | *= | x *= 3 | x = x * 3 | | /= | x /= 3 | x = x / 3 | | %= | x %= 3 | x = x % 3 | | //= | x //= 3 | x = x // 3 | | **= | x **= 3 | x = x ** 3 | | &= | x &= 3 | x = x & 3 | | ^= | x ^= 3 | x = x ^ 3 | | >>= | x >>= 3 | x = x >> 3 | | <<= | x <<= 3 | x = x << 3 | ### Comparison Operators | Operator | Name | Example | |:--------:|:------------------------:|:-------:| | == | Equal | x == y | | != | Not equal | x != y | | > | Greater than | x > y | | < | Less than | x < y | | >= | Greater than or equal to | x >= y | | <= | Less than or equal to | x <= y | ### Logical Operators | Operator | Description | Example | |:--------:|:-------------------------------------------------------:|:---------------------:| | and | Returns True if both statements are true | x < 5 and x < 10 | | or | Returns True if one of the statements is true | x < 5 or x < 4 | | not | Reverse the result, returns False if the result is true | not(x < 5 and x < 10) | ### Identity and Membership Operators | is | Returns True if both variables are the same object | x is y | |:------:|:--------------------------------------------------------------------------------:|:----------:| | is not | Returns True if both variables are not the same object | x is not y | | in | Returns True if a sequence with the specified value is present in the object | x in y | | not in | Returns True if a sequence with the specified value is not present in the object | x not in y | ### Bitwise Operators | Operator | Name | Description | |:--------:|:--------------------:|:-------------------------------------------------------------------------------------------------------:| | & | AND | Sets each bit to 1 if both bits are 1 | | \| | OR | Sets each bit to 1 if one of two bits is 1 | | ^ | XOR | Sets each bit to 1 if only one of two bits is 1 | | ~ | NOT | Inverts all the bits | | << | Zero fill left shift | Shift left by pushing zeros in from the right and let the leftmost bits fall off | | >> | Signed right shift | Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off | ## If / Elif / Else Statements The "if statement" is written by using the <kbd>if</kbd> keyword: ```python a = 33 b = 200 if b > a: print("b is greater than a") # >>> b is greater than a ``` The <kbd>elif</kbd> keyword is used when the previous conditions were not true, and trys to verify this new condition: ```python a = 33 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") # >>> a and b are equal ``` The <kbd>else</kbd> keyword catches anything which isn't caught by the preceding conditions: ```python a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b") # >>> a is greater than b ``` ## Indentation ## Loops ## Lists ### List functions ### Tuples ### Range ## Dictionaries ### Dictionary functions ## Functions <!-- Return --> ### Arguments <!-- Functions as arguments (voir photo) --> ### Recursion <!-- Factorial --> ### Lambdas #### Map / Filter ## Exceptions ### Exceptions handling <!-- Finlay --> ### Raising exceptions ## Classes ### Magic methods ### Delete ## Files <!-- Opening, read, write --> ## Modules ## Comments / Docstrings ## Sources [W3 Schools](https://www.w3schools.com/python) [Solo Learn](https://www.sololearn.com/)