├── Images ├── 1.png ├── 2.png ├── 3.png ├── 4.png ├── 5.png ├── 6.png ├── 7.png ├── 8.png ├── 9.png └── Tkinter-grid-columnspan-rowspan.png ├── Standard libraries ├── json │ ├── movies.json │ └── app.py ├── Sqlite3 │ └── app.py ├── CSV │ └── app.py ├── sys │ └── app.py ├── os │ └── app.py ├── README.md └── datetime │ └── app.py ├── Some fun questions ├── Q2.py ├── Q1.py ├── Q3.py └── Q4.py ├── OOP ├── Inheritance │ ├── Multi-level Inheritance │ │ └── app.py │ ├── Multiple Inheritance │ │ └── app.py │ └── A good example │ │ └── app.py └── Classes & objects │ └── README.md ├── Try-except └── README.md ├── Primitive Types ├── app.py └── README.md ├── Data structures ├── app.py └── README.md ├── Functions └── README.md └── README.md /Images/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AHGh1386/Python-cheatsheet/HEAD/Images/1.png -------------------------------------------------------------------------------- /Images/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AHGh1386/Python-cheatsheet/HEAD/Images/2.png -------------------------------------------------------------------------------- /Images/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AHGh1386/Python-cheatsheet/HEAD/Images/3.png -------------------------------------------------------------------------------- /Images/4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AHGh1386/Python-cheatsheet/HEAD/Images/4.png -------------------------------------------------------------------------------- /Images/5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AHGh1386/Python-cheatsheet/HEAD/Images/5.png -------------------------------------------------------------------------------- /Images/6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AHGh1386/Python-cheatsheet/HEAD/Images/6.png -------------------------------------------------------------------------------- /Images/7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AHGh1386/Python-cheatsheet/HEAD/Images/7.png -------------------------------------------------------------------------------- /Images/8.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AHGh1386/Python-cheatsheet/HEAD/Images/8.png -------------------------------------------------------------------------------- /Images/9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AHGh1386/Python-cheatsheet/HEAD/Images/9.png -------------------------------------------------------------------------------- /Standard libraries/json/movies.json: -------------------------------------------------------------------------------- 1 | [{"id": 1, "title": "Terminator", "year": 1989}, {"id": 2, "title": "GodFather", "year": 1976}] 2 | -------------------------------------------------------------------------------- /Images/Tkinter-grid-columnspan-rowspan.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AHGh1386/Python-cheatsheet/HEAD/Images/Tkinter-grid-columnspan-rowspan.png -------------------------------------------------------------------------------- /Standard libraries/json/app.py: -------------------------------------------------------------------------------- 1 | import json 2 | data = Path("movies.json").read_text(encoding="utf-8") 3 | movies = json.loads(data) 4 | 5 | movies = json.loads(Path("movies.json").read_text(encoding="utf-8") 6 | -------------------------------------------------------------------------------- /Standard libraries/Sqlite3/app.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | with sqlite3.connect("db.sqlite3") as conn: 4 | command = "SELECT * from Movies" 5 | cursor = conn.execute(command) 6 | # for item in cursor: 7 | # print(item) 8 | movies = cursor.fetchall() 9 | print(movies) 10 | -------------------------------------------------------------------------------- /Some fun questions/Q2.py: -------------------------------------------------------------------------------- 1 | # fizz buzz 2 | def fizz_buzz(number): 3 | if number % 3 == 0 and number % 5 == 0: 4 | print("Fizz_Buzz") 5 | elif number % 3 == 0: 6 | print("Fizz") 7 | elif number % 5 == 0: 8 | print("Buzz") 9 | else: 10 | print(number) 11 | 12 | fizz_buzz(29) 13 | -------------------------------------------------------------------------------- /OOP/Inheritance/Multi-level Inheritance/app.py: -------------------------------------------------------------------------------- 1 | # ================================Multi-level Inheritance===================== 2 | 3 | 4 | class Animals(): 5 | 6 | def eat(self): 7 | print("eat") 8 | 9 | 10 | class Birds(Animals): 11 | def fly(self): 12 | print("fly") 13 | 14 | 15 | class Chickens(Birds): 16 | pass 17 | 18 | # Chickens --> Birds --> Animals 19 | -------------------------------------------------------------------------------- /Standard libraries/CSV/app.py: -------------------------------------------------------------------------------- 1 | import csv 2 | 3 | with open("data.csv", "w") as file: 4 | writer = csv.writer(file) 5 | writer.writerow(["trns_id", "pro_id", "price"]) 6 | writer.writerow([1000, 1, 10]) 7 | writer.writerow([2000, 2, 15]) 8 | 9 | with open("data.csv", "r") as file: 10 | reader = csv.reader(file) 11 | # print(list(reader)) 12 | for row in reader: 13 | print(row) 14 | -------------------------------------------------------------------------------- /OOP/Inheritance/Multiple Inheritance/app.py: -------------------------------------------------------------------------------- 1 | # Employee -> Person -> LivingCreature -> Thing 2 | 3 | # ======================multiple Inheritance======================== 4 | 5 | 6 | class Employee: 7 | def greet(self): 8 | print("Employee Greet") 9 | 10 | 11 | class Person: 12 | def greet(self): 13 | print("Person Greet") 14 | 15 | 16 | class Manager(Employee, Person): 17 | pass 18 | 19 | 20 | manager = Manager() 21 | manager.greet() 22 | -------------------------------------------------------------------------------- /Some fun questions/Q1.py: -------------------------------------------------------------------------------- 1 | # write a program that calculates average 2 | def average(): 3 | summery, counter = 0, 0 4 | while True: 5 | number = int(input("Enter your Number to Calculate New Average :")) 6 | if number != 0: 7 | summery += number 8 | counter += 1 9 | print(f"The Current Average is: {summery//counter}") 10 | else: 11 | print(f"The Last Average is: {summery//counter}") 12 | break 13 | -------------------------------------------------------------------------------- /Standard libraries/sys/app.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | # Get the command line arguments 4 | arguments = sys.argv 5 | print("Command Line Arguments:", arguments) 6 | 7 | # Get the Python version 8 | version = sys.version 9 | print("Python Version:", version) 10 | 11 | # Get the maximum integer size 12 | max_int = sys.maxsize 13 | print("Maximum Integer Size:", max_int) 14 | 15 | # Get the platform information 16 | platform = sys.platform 17 | print("Platform:", platform) 18 | 19 | # Get the current recursion limit 20 | recursion_limit = sys.getrecursionlimit() 21 | print("Current Recursion Limit:", recursion_limit) 22 | 23 | # Set a new recursion limit 24 | new_limit = 2000 25 | sys.setrecursionlimit(new_limit) 26 | print("New Recursion Limit:", sys.getrecursionlimit()) 27 | -------------------------------------------------------------------------------- /Some fun questions/Q3.py: -------------------------------------------------------------------------------- 1 | def count_vowels(word): 2 | vowels = "aeiou" 3 | count = 0 4 | word = word.lower() 5 | for char in word: 6 | if char in vowels: 7 | count += 1 8 | return count 9 | 10 | 11 | def reverse_string(sentence): 12 | reversed_sentence = "" 13 | word = "" 14 | i = len(sentence) - 1 15 | while i >= 0: 16 | if sentence[i] == " ": 17 | reversed_sentence += word[::-1] + " " 18 | word = "" 19 | else: 20 | word += sentence[i] 21 | i -= 1 22 | reversed_sentence += word[::-1] 23 | return reversed_sentence 24 | 25 | 26 | def main(): 27 | sentence_input = input("Enter a sentence: ") 28 | vowels_count = count_vowels(sentence_input) 29 | print(f"The number of vowels in '{sentence_input }' is: {vowels_count}") 30 | reversed_sentence = reverse_string(sentence_input) 31 | print(f"The reversed sentence is: {reversed_sentence}") 32 | 33 | main() 34 | -------------------------------------------------------------------------------- /Standard libraries/os/app.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | # Get the current working directory 4 | current_dir = os.getcwd() 5 | print("Current Directory:", current_dir) 6 | 7 | # Create a new directory 8 | new_dir = os.path.join(current_dir, "new_directory") 9 | os.mkdir(new_dir) 10 | print("New Directory created:", new_dir) 11 | 12 | # Change the current working directory 13 | os.chdir(new_dir) 14 | print("Current Directory after change:", os.getcwd()) 15 | 16 | # List all files and directories in the current directory 17 | print("Files and Directories in", os.getcwd()) 18 | for item in os.listdir(): 19 | print(item) 20 | 21 | # Rename a file or directory 22 | old_file = os.path.join(os.getcwd(), "old_file.txt") 23 | new_file = os.path.join(os.getcwd(), "new_file.txt") 24 | os.rename(old_file, new_file) 25 | print("File renamed from", old_file, "to", new_file) 26 | 27 | # Delete a file 28 | os.remove(new_file) 29 | print("File deleted:", new_file) 30 | 31 | # Delete a directory 32 | os.chdir(current_dir) 33 | os.rmdir(new_dir) 34 | print("Directory deleted:", new_dir) 35 | -------------------------------------------------------------------------------- /OOP/Inheritance/A good example/app.py: -------------------------------------------------------------------------------- 1 | # =====================A Good Example Of Inheritance=============== 2 | 3 | 4 | class InvalidOperationError(Exception): 5 | pass 6 | 7 | 8 | class Stream(ABC): 9 | def __init__(self): 10 | self.opened = False 11 | 12 | def open(self): 13 | if self.opened: 14 | raise InvalidOperationError("Stream is already open.") 15 | self.opened = True 16 | 17 | def close(self): 18 | if not self.opened: 19 | raise InvalidOperationError("Stream is already closed.") 20 | self.opened = False 21 | 22 | @abstractmethod 23 | def read(self): 24 | pass 25 | 26 | 27 | class FileStream(Stream): 28 | def read(self): 29 | print("Reading data from a file.") 30 | 31 | 32 | class NetworkStream(Stream): 33 | def read(self): 34 | print("Reading data from a Network.") 35 | 36 | 37 | class MemoryStream(Stream): 38 | def read(self): 39 | print("Reading data from a Memory.") 40 | 41 | 42 | stream = MemoryStream() 43 | stream.open( 44 | -------------------------------------------------------------------------------- /Standard libraries/README.md: -------------------------------------------------------------------------------- 1 | # Python Standard Libraries 2 | 3 | 1. `math` - Mathematical functions and constants. 4 | 2. `random` - Random number generation. 5 | 3. `datetime` - Date and time manipulation. 6 | 4. `os` - Operating system interactions (file operations, directories). 7 | 5. `sys` - System-specific parameters and functions. 8 | 6. `json` - JSON encoding and decoding. 9 | 7. `csv` - CSV file reading and writing. 10 | 8. `re` - Regular expressions. 11 | 9. `gzip` - Compression and decompression using the gzip format. 12 | 10. `pickle` - Object serialization and deserialization. 13 | 11. `socket` - Low-level networking interface. 14 | 12. `urllib` - URL handling. 15 | 13. `http` - HTTP client and server. 16 | 14. `xml` - XML processing. 17 | 15. `sqlite3` - SQLite database access. 18 | 16. `logging` - Logging facility for Python. 19 | 17. `argparse` - Command-line argument parsing. 20 | 18. `timeit` - Execution time measurement. 21 | 19. `itertools` - Tools for efficient looping and iteration. 22 | 20. `collections` - Additional data structures (namedtuple, defaultdict, Counter). 23 | 21. `functools` - Higher-order functions and function decorators. 24 | 22. `pathlib` - Object-oriented filesystem paths. 25 | 23. `operator` - Functions corresponding to Python operators. 26 | 24. `statistics` - Mathematical statistics functions. 27 | 25. `multiprocessing` - Process-based parallelism. 28 | 26. `threading` - Thread-based parallelism. 29 | 27. `socketserver` - Framework for network servers. 30 | 28. `email` - Email message handling. 31 | 29. `hashlib` - Cryptographic hash functions. 32 | 30. `subprocess` - Subprocess management. 33 | -------------------------------------------------------------------------------- /Try-except/README.md: -------------------------------------------------------------------------------- 1 | ### Exceptions 2 | * Exceptions 3 | * A Siple IndexError in list and ValueError in input method 4 | * Handling Exceptions 5 | * Try / except clause 6 | 7 | * Using as statement we can print the reason of exception 8 | * Use type to get info about error class 9 | * Handling Different Exceptions 10 | * A simple error of Zero Division x = 10 / age 11 | * We can add more except clause to handel other kind of errors 12 | * Also we can put more error kind in front of except clause inside parentheses 13 | * Cleaning Up 14 | * A finally clause always execute after a try/except clause 15 | 16 | * The With Statement 17 | * With statement automatically release resources 18 | 19 | * Any kind of objects that have Context Management Protocol(CMP) in case of using with statement python automatically call __exit__() method for it 20 | * We can open multiple file using one with statement 21 | * Raising Exceptions 22 | * We can write our function and get exceptions by raise statement 23 | * Try block can get our raise exception error as variable which we define 24 | 25 | * Cost of Raising Exceptions 26 | * Using timeit library to calculate time 27 | * If we are building a simple app we can use raise exception and try block but in complex program with lots of processes or users it's better to handle problem without try or raise clauses 28 | -------------------------------------------------------------------------------- /Primitive Types /app.py: -------------------------------------------------------------------------------- 1 | my_string = "Hello, World!" 2 | 3 | # String methods 4 | print(my_string.upper()) # Output: HELLO, WORLD! 5 | print(my_string.lower()) # Output: hello, world! 6 | print(my_string.capitalize()) # Output: Hello, world! 7 | print(my_string.title()) # Output: Hello, World! 8 | print(my_string.swapcase()) # Output: hELLO, wORLD! 9 | print(my_string.count("l")) # Output: 3 10 | print(my_string.startswith("Hello")) # Output: True 11 | print(my_string.endswith("World!")) # Output: True 12 | print(my_string.find("o")) # Output: 4 13 | print(my_string.rfind("o")) # Output: 8 14 | print(my_string.index("W")) # Output: 7 15 | print(my_string.rindex("o")) # Output: 8 16 | print(my_string.replace("o", "e")) # Output: Helle, Werld! 17 | print(my_string.strip()) # Output: Hello, World! 18 | print(my_string.lstrip("H")) # Output: ello, World! 19 | print(my_string.rstrip("!")) # Output: Hello, World 20 | print(my_string.split(",")) # Output: ['Hello', ' World!'] 21 | print(my_string.split(" ")) # Output: ['Hello,', 'World!'] 22 | print(my_string.isalpha()) # Output: False 23 | print(my_string.isdigit()) # Output: False 24 | print(my_string.isalnum()) # Output: False 25 | print(my_string.islower()) # Output: False 26 | print(my_string.isupper()) # Output: False 27 | print(my_string.isspace()) # Output: False 28 | print(my_string.isnumeric()) # Output: False 29 | print(my_string.isdecimal()) # Output: False 30 | print(my_string.isprintable()) # Output: True 31 | print(my_string.center(20, "*")) # Output: ****Hello, World!**** 32 | print(my_string.zfill(20)) # Output: 0000000Hello, World! 33 | print(my_string.encode()) # Output: b'Hello, World!' 34 | print(my_string.endswith("world!")) # Output: Fals 35 | -------------------------------------------------------------------------------- /Standard libraries/datetime/app.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | # Get the current date and time 4 | current_datetime = datetime.datetime.now() 5 | print("Current Date and Time:", current_datetime) 6 | 7 | # Get the current date 8 | current_date = datetime.date.today() 9 | print("Current Date:", current_date) 10 | 11 | # Create a specific date 12 | specific_date = datetime.date(2022, 12, 31) 13 | print("Specific Date:", specific_date) 14 | 15 | # Create a specific time 16 | specific_time = datetime.time(12, 30, 45) 17 | print("Specific Time:", specific_time) 18 | 19 | # Format a date and time as a string 20 | formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S") 21 | print("Formatted Date and Time:", formatted_datetime) 22 | 23 | # Parse a string to a datetime object 24 | parsed_datetime = datetime.datetime.strptime("2022-12-31 12:30:45", "%Y-%m-%d %H:%M:%S") 25 | print("Parsed Date and Time:", parsed_datetime) 26 | 27 | # Perform date arithmetic 28 | future_date = current_date + datetime.timedelta(days=30) 29 | print("Future Date:", future_date) 30 | 31 | # Calculate the time difference between two dates 32 | date1 = datetime.date(2022, 1, 1) 33 | date2 = datetime.date(2022, 12, 31) 34 | time_difference = date2 - date1 35 | print("Time Difference:", time_difference.days, "days") 36 | 37 | 38 | # 1. `datetime.now()` - Retrieves the current date and time. 39 | # 2. `date.today()` - Retrieves the current date. 40 | # 3. `date()` - Creates a specific date. 41 | # 4. `time()` - Creates a specific time. 42 | # 5. `strftime()` - Formats a date and time as a string. 43 | # 6. `strptime()` - Parses a string to a datetime object. 44 | # 7. `timedelta()` - Performs date arithmetic. 45 | # 8. `days` - Retrieves the number of days in a time difference. 46 | 47 | -------------------------------------------------------------------------------- /Primitive Types /README.md: -------------------------------------------------------------------------------- 1 | ### Primitive Types 2 | 3 | * Variables 4 | * Memory and memorizing Variables in computers 5 | * Built-in primitive types (Numbers, Booleans, Strings) 6 | * Numbers (Integer, Float) / Booleans (True/False) / Strings("text") 7 | * Variable Names 8 | * Being descriptive and meaningful 9 | * Lowercase Letters 10 | * Use underscore 11 | * Don't start with numbers 12 | * Space around the equal sign 13 | * Strings 14 | * Single, Double, and Triple quote. 15 | * Built-in Functions like len(Argument)<- to call 16 | * Strings as an array str[0][-1][0:3][0:][:3][:] 17 | * Escape Sequences 18 | * str = "Course\"s problem" 19 | * \", \', \\, \n 20 | * Formatted Strings 21 | * first="Ali" and last="D" formatted=f"{first} {last}" print(first+" " + last) 22 | * Concatenation + 23 | * Comments in Python # 24 | * String Methods 25 | * Differences between methods and functions 26 | * Tell about functions and how it works with example 27 | * python is case sensitive language 28 | * saving in memory and original data doesn't change with example 29 | * Tell about the way of saving strings as array. 30 | * len() 31 | * .upper() 32 | * .lower() 33 | * .title() 34 | * .strip() /lstrip() or rstrip() 35 | * .find("pro") / -1 for "Pro" 36 | * .replace("", "") 37 | * "pro" in course 38 | * "pro" not in course 39 | * Numbers 40 | * Integer, Float, Complex x = a + bi 41 | * Standard Arithmetic Operations(+-/*//%**) 42 | * augmented operators in python x+=1 43 | * Working with Numbers 44 | * round() 45 | * abs() 46 | * math.ceil() 47 | * Python3 math modules in Google 48 | * Type Conversion 49 | * input("x: ") run in Terminal and input a number 50 | * int(), float(), bool(), str() 51 | * type() use formatted string 52 | * all False values False, "", 0, None 53 | * check boolean values in python interpreter / " " is not False 54 | 55 | 56 |
57 |
58 |
59 |
60 |
Functions 2 | * Defining Functions 3 | * Reuseable chunks of code / built-in functions like print() / round() / range() 4 | * Define a function using 'def' keyword 5 | * Naming in functions follows all variables naming rules 6 | * Two Lines break 7 | * Arguments 8 | * Differences between arguments and parameters 9 | * An example for first_name and last_name 10 | * Types of functions 11 | * Functions that perform a task / functions that calculate and return a value 12 | * example for two type in real world and -> print() and round() 13 | * Greet() function in two type 14 | 15 | * All functions return None by default 16 | * Keyword Arguments 17 | * Saving info in invisible variable in python 18 | * Use keyword variables to make our code more readable 19 | 20 | * Use keyword arguments when use a lot of variable to make it clear 21 | * Default Arguments 22 | * We give default value to an argument and make it optional. 23 | * All optional parameters should come after required parameters. 24 | * You can not add another none optional parameter after last optional parameter. 25 | * xargs 26 | * To send a collection of parameters to a function we use * before of one variable name like *number 27 | * *number convert our parameters to a iterable type named tuple 28 | 29 | * To send a collection of parameters to a function 30 | 31 | * xxargs 32 | * To send a collection of key value pair arguments to a function we use xxargs 33 | 34 | * Scope 35 | * Local variables doesn't work in outside of their scope 36 | * Example of the completely the same functions and different local variables 37 | * Global variables and avoid to use theme 38 | 39 | * We can use global keyword to use a global variable inside a function but we should avoid it. 40 | * Accidentally change in global variable inside a function can cause a side effect in other functions that use that variable. 41 | * Debugging 42 | * To debug a python file open Run And Debug section first 43 | * Create lunch.json file into .vscode directory 44 | * Choose current active python file 45 | * Use F5 to run / F10 to Step over / F11 to step in / F9 to put a break point 46 | * In The left Side inside the variables section you can see variables value at the moments 47 | * If you sure about a function and know its working properly Use Shift+F11 to step out of that 48 | -------------------------------------------------------------------------------- /OOP/Classes & objects/README.md: -------------------------------------------------------------------------------- 1 | In Python, classes and objects are fundamental concepts of object-oriented programming (OOP). Classes are used to define objects, which are instances of a class. Here's a basic explanation of classes and objects in Python: 2 | 3 | 1. Creating a Class: 4 | To create a class in Python, use the `class` keyword followed by the class name. Class names typically start with an uppercase letter. Here's an example: 5 | 6 | ```python 7 | class Car: 8 | pass 9 | ``` 10 | In this example, we have defined a class named `Car`. The `pass` keyword is a placeholder that allows an empty class definition. 11 | 12 | 2. Creating Objects (Instances): 13 | To create an object (or instance) of a class, you call the class as if it were a function. This process is called instantiation. Here's an example: 14 | 15 | ```python 16 | my_car = Car() 17 | In this example, `my_car` is an object (instance) of the `Car` class. 18 | ``` 19 | 20 | 3. Class Attributes: 21 | Classes can have attributes, which are variables that store data related to the class. These attributes are shared by all instances of the class. You can define class attributes inside the class definition. Here's an example: 22 | 23 | ```python 24 | class Car: 25 | color = "red" 26 | wheels = 4 27 | 28 | my_car = Car() 29 | print(my_car.color) # Output: red 30 | print(my_car.wheels) # Output: 4 31 | ``` 32 | 33 | In this example, `color` and `wheels` are class attributes. They are accessed using the dot notation (`object.attribute`). 34 | 35 | 4. Instance Attributes: 36 | Instance attributes are specific to each instance of a class. They are defined within the class's methods (functions). Here's an example: 37 | 38 | ```python 39 | class Car: 40 | def __init__(self, color): 41 | self.color = color 42 | 43 | my_car = Car("blue") 44 | print(my_car.color) # Output: blue 45 | ``` 46 | 47 | In this example, `color` is an instance attribute. It is initialized using the special method `__init__()` (also known as the constructor). The `self` parameter refers to the instance being created. 48 | 49 | 5. Class Methods: 50 | Methods are functions defined within a class. They can access and modify the attributes of the class. Here's an example: 51 | 52 | ```python 53 | class Car: 54 | def __init__(self, color): 55 | self.color = color 56 | 57 | def start_engine(self): 58 | print("Engine started!") 59 | 60 | my_car = Car("blue") 61 | my_car.start_engine() # Output: Engine started! 62 | ``` 63 | 64 | In this example, `start_engine()` is a class method. It is called on an instance of the `Car` class using the dot notation (`object.method()`). 65 | 66 | These are the basic concepts of classes and objects in Python. By using classes and objects, you can create reusable and structured code, allowing for easier management and organization of your program's data and functionality 67 | -------------------------------------------------------------------------------- /Data structures/README.md: -------------------------------------------------------------------------------- 1 | ### Data Structures 2 | * Lists 3 | * A sequence of objects. one or two or More dimensional Lists 4 | * zeros = [0] * 100 / Use + to concatenate or * to multiply 5 | * Use list() method to convert objects to list: num = list(range(20)) 6 | * Use len() method to get length of a list 7 | * Accessing Items 8 | * lst[0] , lst[-1] 9 | * Use assign item to change list Items lst[1] = "B" 10 | * Use [:] to get a range of items in list / [::2] 11 | * Use [::-1] to reverse list(range(20)) 12 | * List Unpacking 13 | * first, second, third = lst / left and right must be equal in number 14 | * first, second, *other = lst / first, *other, last = lst 15 | * Lopping Over List 16 | * Use for to loop over a list 17 | * enumerate() unpack list item to key and value 18 | 19 | * Adding or Removing Items 20 | * Use .append() method to add an item to end of a list 21 | * Use .insert() method to add item at specific position in list / lst.insert(1, "D") 22 | * Use .pop() method to remove an item from end of a list / .pop() .pop(0) 23 | * Use .remove("b") to remove first occurrence of that item / remove without index 24 | * to remove all "b" in the list you should loop over list 25 | * Use del lst[0] to delete an item or del lst[:3] to delete a range of items ==> this is difference between pop and del 26 | * use lst.clear() to delete all items in the list. 27 | * Finding Items 28 | * To find index of an item use lst.index("item") 29 | * .index() method return ValueError when try to find an item that is not exist. 30 | * Use if .. in .. to prevent this error 31 | * Use lst.count("item") to check existence of an item 32 | * Sorting Lists 33 | * Use lst.sort(key, reverse=True|False) method to sort a list 34 | * To sort a list without changing the original list use sorted(lst) function / sorted(lst, reverse=True) 35 | * To sort a list of unordered items like list of tuples we should write a function and pass use sort item and pass all items to this function 36 | * Lambda Functions 37 | * A one line anonymous function we can pass to other functions 38 | * ... = lambda parameters:expression 39 | 40 | * Map Functions 41 | * Use mapping to map a list to make another better list 42 | * In ordinary way we define another list and append all second item to the new list 43 | 44 | * Filter Functions 45 | * To filter a list to a particular list contain some special items we use filter function 46 | * Regular way is looping over and separate elected items and add it to a new list 47 | * List Comprehension 48 | * "[expression for item in items] / [item[1] for item in lst] 49 | * To convert filtered list to comprehension do this: [item for item in lst if item[1] >= 10] 50 | * We can use if .. else statement in comprehension at first part of clause 51 | * Zip Function 52 | * To combine two or more equal list (equal in list member) and make a new list, use zip function 53 | * Zip function return a tuple for each member contain all same index items 54 | * Stacks 55 | * A LIFO data structure 56 | * Website's pages visiting hierarchy is good simple fore Stack 57 | * We can use . append(), .pop() methods for simulating stack and stc[-1] and not stc to check it 58 | * Queues 59 | * A FIFO data structure 60 | * We use deque for optimize Using queue 61 | 62 | * Tuples 63 | * Tuple is a read only list and we use () to define it 64 | * if we remove () Python Assume it as tuple like 1, or 1,2 65 | * We can multiple or concatenate tuples 66 | * We can convert a list or any iterable into a Tuple using tuple() 67 | * We cannot mutate tuples and assign a value of tuple to a new value 68 | * Swapping Variables 69 | * x, y = Y, x 70 | * This clause works as unpacking in tuples x, y = (11, 10) 71 | * Arrays 72 | * If we deal with large sequence of numbers we should use Array 73 | * Array take less memory and work a little bit faster 74 | * For the using array we should import it 75 | * Array(typecode, iterable) 76 | * All members in array should be the same type 77 | * Sets 78 | * Set is a unordered collection of data without duplicates 79 | * By converting a List to set we can remove all duplicates / set() 80 | 81 | * Shining usage of sets is in mathematics 82 | * To make union of Two sets print(set1 | st2) / print(set1 & st2) / print(set1 - st2) / print(set1 ^ st2) 83 | * Sets items not in sequence and we cannot access them by index 84 | * We can existence of a value by using if .. in statement 85 | * Dictionaries 86 | * Dictionary is a key value per collection of data 87 | * In dictionary keys can only be an integer of string and value can be kind of anything 88 | * We can define a dictionary using dict() function 89 | 90 | * Dictionary Comprehension 91 | * We can use Comprehension for sets and dictionaries 92 | * Val = {x : x*2 for x in range(5)} 93 | * Generators 94 | * Generator object like list is a iterable but generate value in each iteration 95 | * Generators don't store all values in memory 96 | 97 | * Generators objects has no len 98 | * Unpacking Operators 99 | * We can print Items of a list in unpacked using [*numbers] 100 | 101 | * We can use unpacking operators to combine list 102 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python 2 | 3 | 4 | 5 | 6 | 7 | ### Getting started 8 | 9 | - About Python 10 | 11 | - The World's Fastest growing programming language 12 | - Most Popular among Software Engi., Data Analysts, Math, Science, Net Engi., and Kids 13 | - Google, Facebook, Spotify, DropBox, and etc. use Python 14 | - Python is simple 15 | - ![](Images/1.png) 16 | - 17 | - Python is a multipurpose Language 18 | - 19 | - ![](Images/2.png) 20 | - 21 | - Most Desirable language 22 | - ![](Images/3.png) 23 | - 24 | - Python2 and Python3 25 | - 26 | 27 | - Installation Instruction 28 | 29 | - Install python (Download and install) 30 | - Note "check `Add python 3 to PATH`" 31 | - check your installation on windows Command prompt 32 | 33 | - Python Interpreter 34 | 35 | - Check some code in it 36 | - Check errors 37 | 38 | - Editors 39 | 40 | - Text Editors `Notepad` , `Atom`, `Sublime` 41 | - IDEs `Pycharm`, 42 | - Use `VSCode` for this class 43 | 44 | - Create Your First Python File 45 | 46 | - Open your folder in VSCode And create .py file 47 | - Talk about extensions 48 | - First Built-in Function `Print()` 49 | - Execute first code in terminal 50 | 51 | - Turn VSCode to a Powerful IDE Using Extensions 52 | 53 | - Install python Extension in VSCode 54 | - ![](Images/4.png) 55 | - Install Linter to find Potential errors 56 | - Select right Python for your Project 57 | 58 | - PyLint 59 | 60 | - Check PyLint Functionality 61 | - Check errors in problems panel 62 | - Talk about command pallet `Shift + ctrl + p` 63 | - Choose Right linter - `pylint` 64 | 65 | - Python Enhancement Proposal 66 | 67 | - PEPs In google 68 | - PEP8 69 | - Talk about Python code formats 70 | - Format Document In command pallet 71 | - autopep8 Installation 72 | - Talk about some developer mistake in formatting code 73 | - Turn auto format on save in `Code>Preferences>sittings` 74 | - Search for FormatOnSave and turn it on 75 | 76 | - Running Python Code 77 | 78 | - Install Code Runner 79 | - Running Code by Key or `ctrl+alt+n` 80 | 81 | - Python Implementation 82 | 83 | - Cpython and python interpreter 84 | - Other Implementations of python Jython, IronPython, PyPy 85 | - These implementations help us to use other languages code in our python code 86 | 87 | - Execution of Python code 88 | 89 | - Cpython and python interpreter 90 | - 91 | - C Translation to machine code 92 | - - ![](Images/5.png) 93 | - Codes are different in Mac and Windows based on compliers 94 | - 95 | - - ![](Images/6.png) 96 | - 97 | - Java Solve the problem 98 | - 99 | - - ![](Images/7.png) 100 | - 101 | - Python use it 102 | - - ![](Images/8.png) 103 | - 104 | - Jython Workflow 105 | - 106 | - - ![](Images/9.png) 107 | 108 |
109 | 110 | ### Primitive Types 111 | 112 | - Variables 113 | 114 | - Core concept of storing data by programming languages 115 | - Three different built-in primitive types in python 116 | - Numbers (100, 4.9,...), Booleans (True/False), Strings ("Your Name") 117 | - All your variables' name should be descriptive and meaningful 118 | - All letters in your variable's name should be in lower case 119 | - Set a space before and after your equal sign 120 | - Use Underline between separate word 121 | 122 | - Strings 123 | 124 | - Surround your text with `"` or `'` 125 | - For multiline text (long text) we use `"""` 126 | - Talk about built-in function for String type 127 | - `len()` 128 | - Calling Functions concept by using `()` 129 | - Indexing concept in Python for strings and `[]` 130 | - End of the string using `[-1]` 131 | - Slicing strings Using `[:]` (check all options) 132 | - Using backslash `\` to scape special characters (e.g. `\"`, `\'`, `\\`, `\n`) 133 | - Concatenate strings using `+` 134 | - Formatted Strings using `f` and `{}` 135 | 136 | - String Methods 137 | 138 | - Talk about methods and OOP (Dot Notation) 139 | - `upper()`, `lower()`, and `title()` methods 140 | - Notice that the original string is not changed after using those methods 141 | - Use `strip()` method for users input strings (`lstrip()` and `rstrip()`) 142 | - Use `find()` method to find a special character or series of characters (return an index or `-1`) 143 | - Use `replace("1", "2")` to change one or sequence of characters 144 | - `in` and `not in` expressions for checking the existence of something 145 | - Different between the `find()` and `in` expression is in return value (`index`, `True/False`) 146 | 147 | - Numbers 148 | 149 | - There is three different number type in python 150 | - `Integer`, `float`, and `complex` (a + bi) 151 | - Talk about comments `#` 152 | 153 | - Standard Arithmetic Operations 154 | 155 | - `+`, `-`, `*`, `/`, `//`, `%` and `**` 156 | - Augmented Operations `+=`, `-=`, `*=`, `/=` 157 | 158 | - Built-in Functions for Numbers 159 | 160 | - `round()` 161 | - `abs()` 162 | - Talk about modules (`math`) and import the library and check `.` notation 163 | - Check `math` modules in Google (`Python 3 math modules`) 164 | 165 | - Type Conversion 166 | - Use input function to get data from user 167 | - Check the error and explain the reason 168 | - Built-in Conversion methods in python 169 | - `int()`, `float`, `bool`, and `str` 170 | - talk about `type()` method 171 | - All falsy values in python: `""`, `0`, `False`, and `None` 172 | - Check in interpreter 173 | 174 |
175 | 176 | ### Control Flow 177 | 178 | - Comparison Operators 179 | 180 | - `>`, `<`, `<=` `>=`, `==`, `!=` 181 | - An integer and a string value save differentially in memory `10 == "10"` is wrong 182 | - every character has unique numeric representation ()unicode, so `"bag" == "BAG"` is wrong 183 | - Use `ord()` function to show differences 184 | 185 | - Conditional statement 186 | 187 | - `if` statement (always terminate it with `:`) 188 | - Explain about code block and indentation on a simple example `temperature` 189 | - Simple example (`if statement : pass`) 190 | - Talk about indentation and code block with example of three print under an if statement 191 | - Explain codes out of if block 192 | - With `elif` statement we can add more condition to our code 193 | - If all our conditions are not True we use `else` statement to execute last condition (lots of `elif` and one `else`) 194 | - nested if statements 195 | 196 | - Ternary Operator 197 | 198 | - Turn 5 line code to one 199 | - `X = elem1 if rule1 else elem2` 200 | - message = "OK" if time >= 10 else "Not OK" 201 | 202 | - Logical Operator 203 | 204 | - `and`, `or`, and `not` 205 | - `and` operator return True if both conditions are True 206 | - `or` operator return True if one of conditions is True 207 | - `not` changes the value of a boolean variable 208 | - Don't use `==` for check a boolean variable 209 | - Separate conditions logical comparison to make accurate comparison 210 | - Avoid short circuit in the process of working with logical operators 211 | - Chain logical operators instead of using theme in word format 212 | - Use `18 <= age < 40` instead of `age >= 18 and age < 40` 213 | 214 | - For Loops 215 | 216 | - When we need to repeat a task for number of times `For loop' can do it (Ex: print something for 10 times) 217 | - Talk about counter(`number`) and `range` function (step) and add `... * "."` 218 | 219 | - For...else 220 | 221 | - `else` execute when a loop completely was executed and aBreak didn't happen 222 | 223 | - Nested Loops 224 | 225 | - Talk about Outer and inner Loops 226 | - Explain how exactly python interpreter execute nested loops 227 | 228 | - Iterables 229 | 230 | - Use type for range() function to explain 231 | - Range is complex type 232 | - Iterable of strings or lists 233 | - You can create a `iterable` object and use it in `For` loop 234 | 235 | - While Loop 236 | 237 | - We use `While` loop to repeat something as log as a condition is true 238 | - Explain While loop in python interpreter as real world example 239 | - Simulate Terminal using a while loop as extra example 240 | - Check case sensitive characteristic of python 241 | - Check a poor way of condition for while loop (A `and` B) 242 | 243 | - Infinite Loop 244 | 245 | - Infinite loop is a loop that runs forever 246 | - You should always have a way to break the infinite loop 247 | - it can cause crash for your system 248 | 249 | - Exercise/span> 250 | - A python code that shows even number between 1 to 10 and count them 251 | 252 |
253 | 254 | ### Functions 255 | 256 | - How to Define a Function 257 | 258 | - In programming we should break our code in small, reusable, and more maintainable chunks of code 259 | - Use `def` keyword (short form of define) to declare your function 260 | - Make sure your function names are meaningful and descriptive 261 | - Name conventions should apply for functions naming 262 | - After definition of a function for using it you should call it (Two line break - pep8) 263 | 264 | - Arguments 265 | 266 | - Talk about differences between `print` and our function 267 | - Define parameters in our function 268 | - A parameter is the input that you define for your function but an argument is actual value for a given parameter 269 | 270 | - Types of Functions 271 | 272 | - There is two type of Functions 273 | - A: A function that perform a task (`say_hello()`, `print()`) 274 | - B: A function that calculate and return a value (`round()`) 275 | - We use `return` statement to return a value from a function 276 | - Write `say_hello()` function with `return` and get it in variable 277 | - Talk about print a function that doesn't return any value 278 | - By default all functions return a `None` value (indicator of absence a value) 279 | 280 | - Keyword Arguments 281 | 282 | - Talk about temporary argument that python create for us when we pass a function to another function 283 | - Make your code more readable when you are calling your function by using keyword arguments 284 | - By adding a default value to a parameter we can make it optional 285 | - (`Important`) All optional parameters should come after the required parameters 286 | 287 | - xargs 288 | 289 | - To pass a list of parameters to function we can use `xargs` 290 | - It returns a `Tuple` 291 | - By adding an asterisk (`*`) at beginning of a parameter it can take a list of values 292 | - Talk about tuples and lists by return xargs argument 293 | 294 | - xxargs 295 | 296 | - To pass a series of keyword arguments to a function we can use `xxargs` parameter 297 | - By adding double asterisk (`**`) at beginning of a parameter it can take a list of key value peers 298 | - It returns a `Dictionary` 299 | - By using `bracket` notation we can get the values of a dictionary 300 | 301 | - Scope 302 | 303 | - It's Impossible to call a variable which defined inside a function, outside of it 304 | - A local variable only works inside the scope also parameters 305 | - Thc completely equal variable in two different function is completely separate 306 | - When a function called, python interpreter allocate a memory to it's variables and release it at end function's execution 307 | - On the other side we have global variables which can be used anywhere in code 308 | - Global use memory for long time and you should not use them often 309 | - A global variable's value never change even inside a function 310 | - By using `global` keyword we can reference a local variable to a global one 311 | - Using global variables is not recommended because it can has a side effect in other functions 312 | 313 | - Debugging 314 | 315 | - Start debugging process inside `Debug panel` (F5) 316 | - Choose current file and `VSCode` create a `json` file for your project (`don't touch it`) 317 | - By using `bullet points` (F9) you can define break point for debug process 318 | - By pushing F10 key you can step forward in process 319 | - By pushing F11 key you can step into a sub-process like a function 320 | - To stop debugger with `shift+F5` 321 | - Debugger stops wherever you placed a bullet point 322 | - To step out of a function or loop you can press `shift+F11` 323 | 324 | - VSCode Tricks 325 | - In each line you can move to the end by pushing `end` key 326 | - In each line you can move to the beginning by pushing `home` key 327 | - By pressing `Ctrl+end` cursor move to the end of the file 328 | - By pressing `Ctrl+home` cursor move to the beginning of the file 329 | - By pressing `alt` plus `arrow keys` (top-down) you can move a line of code top or down 330 | - To duplicate a line press `alt+shift+down` keys 331 | - By pressing `Ctrl+/` you can change a line to comment 332 | - By typing some characters of a variable you can place it by pushing enter 333 | 334 |
335 | 336 | ### Data Structure 337 | 338 | - Lists 339 | 340 | - We use `[]` in Python to define a list or sequence of objects 341 | - Talk about different type of list (list of numbers, list of lists like a matrix) 342 | - `zeros = [0] * 100` / Use `+` to concatenate or `*` to multiply 343 | - In python lists items doesn't need to be a same type 344 | - Use `list()` method to convert objects to list like `list(range(20))` or `list("Hello")` 345 | - `list()` function takes an `iterable` as argument 346 | - Use `len()` method to get length of a list 347 | 348 | - Accessing Items 349 | 350 | - By using Bracket notation we can have access to a list items 351 | - Talk about similar thing with regard strings 352 | - To modifying items use assign element. Change list Items like `my_list[1] = "B"` 353 | - Use [:] to get a range of items in list 354 | - By slicing a list, original list doesn't change 355 | - Use [::-1] to reverse a list ex: `my_list(range(20))[::-1]` 356 | 357 | - Unpacking Lists 358 | 359 | - We can Unpack a list into multiple variables 360 | - `first, second, third = my_list` 361 | - Left and right side must be equal in number (Check for error) 362 | - Unpacking a large list : `first, second, *other = my_list` or `first, *other, last = my_list` 363 | - Using a asterisk `*` before a variable change it to a list and it is a packing in Python 364 | 365 | - Lopping over Lists 366 | 367 | - Use for to loop over a list 368 | - `enumerate()` function unpack list item to key and value 369 | - This function convert each item of list to a `tuple` 370 | - Use for loop to show `kays` and `values` in a list (By indexing and unpacking) 371 | - Talk about for loop and represent items in each iteration 372 | 373 | - Adding or Removing Items 374 | 375 | - Use `append()` method to add an item to end of a list 376 | - Use `insert()` method to add item at specific position in list 377 | - Use `pop()` method to remove an item from end of a list (remove with index) 378 | - Use `.remove(item)` to remove first occurrence of that item - remove without index 379 | - To remove all`"b"` in the list you should loop over list 380 | - Use `del lst[0]` to delete an item or `del lst[:3]` to delete a range of items 381 | - This is difference between `pop()` and `del` 382 | - Use `clear()` method to delete all items in the list 383 | 384 | - Finding Items 385 | 386 | - To find index of an item use `.index(item)` method 387 | - `index()` method return `ValueError` when try to find an item that is not exist 388 | - Use `if .. in ..` statement to prevent this error 389 | - Use `count(item)` method to check existence of an item 390 | 391 | - Sorting Lists 392 | 393 | - Use `sort()` method to sort a list 394 | - Use `reverse` parameter as keyword argument to sort your list in descending format `lst.sort(key, reverse=True|False)` 395 | - To sort a list without changing the original list use `sorted(lst)` function ex: `sorted(my_list, reverse=True)` 396 | - To sort a list of unordered items (complex) like list of tuples we should write a function and use sort item and pass all items to this function 397 | - We can pass a function not `call` to the `sort()` method as `key` parameter 398 | - You need to specify `key` parameter as keyword argument 399 | 400 | - Lambda Functions 401 | 402 | - A lambda function is a `one-line` anonymous function that we can pass to other functions 403 | - Lambda function structure: lambda parameter: expression 404 | 405 | - Map Function 406 | 407 | - To transform (map) a part of all items in a list of complex items we need to apply a for loop an get the desire value from it 408 | - By using `map` function we can do it in a shorter and elegant way 409 | - It returns a map object (an iterable) and by type conversion we can transform it to a list object (`list()`) 410 | - We can loop over it or convert it to a list 411 | 412 | - Filter Function 413 | 414 | - When we need to apply a filter on a list and get a specific values `filter` function is the way 415 | - `Filter` function takes a lambda function as first parameter and select items based on the lambda function criteria 416 | - It returns an iterable object (`filter object`) 417 | - We can loop over it or convert it to a list 418 | 419 | - List Comprehension 420 | 421 | - List comprehension in python: [Expression for item in items] 422 | - It's completely the same with the `mapping process` and `filtering process` 423 | 424 | - Zip Function 425 | 426 | - To merge two or more list in a single list of tuples we can use `zip` function 427 | - It returns a `Zip object` which is a iterable 428 | - Add a string to zip function and see the result 429 | 430 | - Stacks 431 | 432 | - A `LIFO` data structure (`example of Books`) 433 | - Website's pages visiting hierarchy is good simple fore Stack 434 | - We can use `.append()`, `.pop()` methods for simulating stack and `stc[-1]` and `not []' to check it 435 | - `[]` is another falsy value 436 | 437 | - Queues 438 | 439 | - A `FIFO` data structure 440 | - We use `deque` for optimize Using queue 441 | - Use `.popleft()` and `deque` class to manage your queue in optimize way 442 | 443 | - Tuples 444 | 445 | - Tuple is a read only list and we use `()` to define it 446 | - if we remove () Python Assume it as tuple like `1, or 1,2` 447 | - Empty parentheses indicate a tuple 448 | - We can multiple a number into a tuple or concatenate tuples 449 | - We can convert a list or any iterable into a tuple using `tuple()` function 450 | - `Indexing`, `packing`, and `unpacking` rules are usable related to tuples 451 | - We cannot mutate tuples and assign a value of tuple to a new value 452 | - We use a tuple when we need a sequence of objects that should be untouched throughout the execution of program 453 | 454 | - Swapping Variables 455 | 456 | - `x, y = Y, x` (Exercise) 457 | - This clause works as unpacking in tuples `x, y = (11, 10)` 458 | - Explain about tuples without `()` 459 | 460 | - Arrays 461 | 462 | - When we deal with a large sequence of numbers we should use Array 463 | - Array take less memory and work a little bit faster 464 | - In 99% of the cases we use lists but sometimes when we experience a performance problem, arrays can solve it 465 | - For the using array we should import it 466 | - Search for `python 3 Typecode` in Google 467 | - `Array(typecode, iterable)` 468 | - We can all methods of lists about arrays 469 | - All members in array should be the same type (test assigning float to integer array) 470 | 471 | - Sets 472 | 473 | - Set is a unordered collection of data without duplicates 474 | - By converting a List to set by using `set()` function we can remove all duplicates 475 | - We use `{}` to define sets 476 | - Like lists we can add to (`.add()` method) and remove items (`.remove()` method) from a set 477 | - `len()` function return the size of a set 478 | - Shining usage of sets is in `mathematics` 479 | - Use `|` operator to make union of two sets 480 | - Use `&` operator to get the intersection of two sets 481 | - Use `-` operator to get the differences between two sets 482 | - Use `^` operator to get the symmetric differences between two sets 483 | - Sets items not in sequence and we cannot access them by index 484 | - We can existence of a value by using `if .. in` statement 485 | 486 | - Dictionaries 487 | 488 | - Dictionary is a `key value pe` collection of data 489 | - In dictionary keys can only be an `integer` or a `string` and value can be kind of `anything` 490 | - Index in dictionaries is the key items (`my_dict["key1"]`) 491 | - We can define a dictionary by using `dict()` function 492 | - Always check for existence of a key before use or call it by `if ... in` statement or `.get()` method 493 | - To delete an item use `del` statement 494 | - For loop on a dictionary return keys in each iteration 495 | - By using `.items()` we can get dictionary's item in the shape of tuple in each iteration 496 | - Practice on writing list comprehension (Change it to a set) 497 | - We can use Comprehension for sets and dictionaries 498 | - `Val = {x : x*2 for x in range(5)}` 499 | 500 | - Generator Expression 501 | 502 | - Comprehension on tuples return a `Generator Objects` 503 | - Generator object like list is a iterable but generate value in each iteration 504 | - Generators don't store all values in memory 505 | - `len()` function doesn't work on generator object 506 | 507 | - Unpacking Operator 508 | 509 | - We can print items of a list by using `[*numbers]` statement 510 | - We can use unpacking operators to combine lists 511 | - Also unpack operator work abut dictionaries by using `**` 512 | - If we have multiple item in our dictionaries, the last item will be used 513 | 514 |
515 | 516 | ### Exceptions 517 | 518 | - Exceptions 519 | 520 | - An exception is a kind of error that terminate the execution of the program 521 | - Like `index error` in lists or getting `None` value is input from user 522 | - By using a `try exception` block we can handel potential errors 523 | - If you don't handel exceptions properly your program will crash 524 | - All codes after try block will be executed after accruing an exception 525 | - By adding an `else` statement to your try block, if no exception is thrown else block code wil be executed 526 | - It's possible that different kind of exceptions happens and it's important to handel them 527 | - We can define `multiple exception` block for our try clause or put all potential exceptions in one exception block (`inside a parentheses`) 528 | - If one of our try block exceptions be executed other exceptions will be ignored 529 | - We should release the external resources like files or network connections after finishing our job with them 530 | - To prevent duplicate or release external resources, we need to define a `finally` at the end of your try block 531 | - Also we can use `with` statement in the case of working with external resources 532 | - This resources will be released when the program doesn't need the anymore 533 | - If any object in python supports context management protocol, we should open them by `with` statement 534 | - These files has two `__enter__` and `__exit__` magic method 535 | - We can open multiple file with one `with` statement 536 | - We can `raise` an exception by using this statement 537 | - Check Python 3 built-in exceptions In Google 538 | - We can manage all raises exceptions by try block 539 | - Using `Try-exception` is costly and only use it for sample and small programs 540 | - `Pass` statement is necessary when we need to do nothing 541 | - Think about using `try` block if you can handel it with a sample `if` statement 542 | 543 |
544 | 545 | ### Classes 546 | 547 | - Classes 548 | 549 | - A class is a blueprint or template that defines the structure and behavior of an object 550 | - An `instance` of a class represents a specific, unique occurrence of that class, with its own set of `data` and the ability to perform `actions` defined by the class 551 | - Wrap up: A `Class` is a blueprint for creating new objects 552 | - Wrap up: An `Object` is an instance of a class 553 | - Classes form the building `blocks` for organizing and manipulating data in a comprehensive and organized manner, enabling `efficient` and `reusable` software development 554 | - Examples of classes and instances in real world 555 | 556 | - Creating Classes 557 | 558 | - We follow Pascal naming conventions in classes naming 559 | - By using `class` keyword we can define our custom classes 560 | - We can define a object by calling a class and assign it to a variable 561 | - Talk about inheritance related to classes and Python objects 562 | - Talk again about `type()` method 563 | - By using `isinstance()` method we can check that an object is instance of a certain class 564 | - We cannot use a class without making an instance of it 565 | 566 | - Constructors 567 | 568 | - `__init__` method is especial `magic method` that executed when a new object was creating 569 | - `self` is reference to the current new object 570 | - Python create our new object and put it in memory and reference that in self statement 571 | - An object has its own attributes that have data which related to it 572 | - For example human is class that have its `attributes` like eye color, skin color, hight, wight, and etc, and its functions like walking, jumping, eating, and etc 573 | - Python fill self variable automatically for us, when an object is created 574 | - We can use self to call this object attributes or functions 575 | - To use functions of an object it's not necessary to put object name in function arguments. Python does it automatically 576 | 577 | - Class vs Instance Attributes 578 | 579 | - We can define a new attribute for an object after creating it 580 | - `Objects in python are dynamic` 581 | - `Instance attributes` belong to each object separately 582 | - `Class level attributes` are shared across all instances of a class 583 | - We can use a class level attribute without making an instance 584 | 585 | - Class vs Instance Methods 586 | 587 | - When we create an instance of a class, we can use its functions as instance methods 588 | - These methods really need to work a specific object 589 | - `Zero()` method is factory method 590 | - To create a class level method we need to use `cls` statement instead of `self` 591 | - Also we need a `decorator` to extend our method behavior 592 | 593 | - Magic Methods 594 | 595 | - Magic methods called by python interpreter automatically depend on who we use our objects or classes 596 | - Search Python 3 magic methods in google 597 | - Print point object and talk about the type 598 | - Use `str` magic method as example to convert variables to string 599 | 600 | - Comparing Objects 601 | 602 | - Two object of a Class with same attributes are completely different because they have different references in memory 603 | - We should use `__eq__` magic methods to represent a comparable form of our class and check equality 604 | - Implement `__gt__` method and check it for `<` and `>` operators 605 | - If you implement a magic method python automatically figure out what to do if you use the other one 606 | 607 | - Performing Arithmetic Operations 608 | 609 | - Use `__add__` magic method to sum to object 610 | - Save the result to another variable and print an attribute of it 611 | 612 | - Creating Custom Containers 613 | 614 | - We can define our custom Container using python built-in data structures like dictionary 615 | - Define `add` method for our TagCloud class 616 | - Use get method to get item 617 | - Convert tags to lowercase through getting item 618 | - Define basic options for your Custom TagCloud like `len()`, `set`, and `get` items 619 | 620 | - Private Members 621 | 622 | - To make an attribute unaccessible from outside a class prefix it with two underline 623 | - Check this by . notation on an instance of your object 624 | - This member is still accessible but is hard to access and it's a kind of warring 625 | - Check `__dict__` method (It's dictionary that all the attribute of a class) 626 | - Python automatically prefix an attribute with the class name 627 | 628 | - Properties 629 | 630 | - To have control over attributes we can define set-get method to control values (It's not Pythonic) 631 | - Also we Can use a more Pythonic way that called properties 632 | - Define a class attribute using `property()` method 633 | - Only path a reference to get and set method 634 | - You have access to your property and easily can set or get it 635 | - set and get method pollute your object interface 636 | - You can make them unaccessible by adding two underline but its not good 637 | - Also you can `@property` decorator to make your code professional 638 | - Change the set and get method name to ideal name 639 | - Add `@name.setter` proChange your constructor and your attribute to regular one 640 | 641 | - Inheritance 642 | 643 | - Classes with same method can make your code busy and noisy hard to maintain 644 | - Avoid `DRY`. it means: `D`on't `R`epeat `Y`ourself 645 | - We can use `inheritance` or `composition` to solve this problem 646 | - Inheritance is a mechanism that allows us to define common behavior or common functions in one class and then inherit them in other classes 647 | - We use `parentheses` in front of a class name and write the `parent class` inside it to inherit all attributes and methods from `Base class` to `Sub class` 648 | - Sub class inherit all methods and attributes from base class 649 | 650 | - The Object Class 651 | 652 | - Use `isinstance()` Method to reveal relationship between classes and object class 653 | - `Object` class is base class for all classes in python 654 | - Check inheritance between a class and object class by `isinstance()` and inspecting an instance of both of them 655 | - `issubclass()` method return True if a class is subclass of another class 656 | 657 | - Method Overriding 658 | 659 | - When we use a subclass, some methods like constructor are overriding the Base class constructor 660 | - By using `super()` method we can call base class constructor in a sub class 661 | - To change the sequence of call super() method we can change the position of method 662 | - To recap method overriding means replacing or extending a method defined in base class 663 | 664 | - Multi-level Inheritance 665 | 666 | - Inheritance prevent code duplication and allows us to reuse code 667 | - Too much Inheritance between classes can increase complexity and introduce lots of issues (Too much of a good thing is bad thing) 668 | - Remember, We should use multi-level inheritance in `one` or `two` level, not more 669 | 670 | - Multiple Inheritance 671 | 672 | - If You use multiple Inheritance not properly it's gonna be source of issues 673 | - In multiple Inheritance python interpreter, first look for specific method in sub class and after that try to find it in multiple parents class in order from left to right 674 | - Multiple inheritance is not a bad thing, just like multi-level inheritance, if you don't use it properly it can cause problems 675 | - Before using multiple inheritance, check that the parent classes should have the minimum subscription 676 | 677 | - A Good Example of Inheritance 678 | 679 | - A good Example of Inheritance on streaming from file and network in our web application 680 | 681 | - Abstract Base classes 682 | 683 | - In our good example of inheritance, we have two serious problems: 684 | - We should built a sub class of Stream class and then use it 685 | - If we need to define a new sub class for Stream class, we should define read() method exactly like other sub stream classes 686 | - In this case we should Covert Stream class to an `abstract base` class 687 | - It's like a half baked cookie 688 | - We need to import `ABC` class and `abstractmethod` decorator from `abc` module 689 | - Remember we cannot instantiate a abstract class (we con not make instance of it) 690 | - If a class derive from a abstract class it has to implement its abstract methods 691 | 692 | - Polymorphism 693 | 694 | - `Poly` means many, `Morph` means form 695 | - It enables objects of different types to be treated as objects of a common superclass 696 | - By define a abstract method and concrete a method our functions can use many forms of classes automatically 697 | - A function can deal with concrete methods of different classes automatically 698 | 699 | - Duck Typing 700 | 701 | - To use Polymorphism we define a abstract class with common behavior and create subclasses with that behavior 702 | - If something like duck and quacks like duck, it's a duck 703 | - Python is dynamically type language and it doesn't check the type of object 704 | - If a certain method exist in object python accept it as abstract base method 705 | 706 | - Extending Built-it Types 707 | 708 | - We can extend a built-in class like string class in python and give it more functionality by define a new class 709 | - Do it for list 710 | 711 | - Data Classes 712 | - In Python we have classes that have only data and do not show any behavior 713 | - We can use `id()` method to print physical address of an object 714 | - We can use `namedtuple` library to define a class that have only data 715 | - `namedtuples` are immutable 716 | 717 | ### Modules 718 | 719 | - Creating Modules 720 | 721 | - A real program can contain tens of thousand lines of code 722 | - We write python code in separate modules 723 | - Python modules naming is like variables 724 | - Each module contain highly related objects (functions, variables, classes, etc.) 725 | - We can use objects in one file inside of another file by call theme by `from ... import` statement 726 | - By pressing `ctrl+space` after modules name in import statement we can see all methods and classes inside that modules 727 | - Using `*` to import all objects in a module can caused a overwriting and malfunction 728 | - If we used `import` statement only we should call objects by adding module name bef ore of any object `(sales.calc_tax())` 729 | 730 | - Compiled Python Files 731 | 732 | - When we import a module inside another module python after first time running code make a compiled version of module to speed up in code execution later 733 | - Python look at the time of edit of compiled file for updating it 734 | - Name of the compiled file contain the version of `cpython` that used to execute this code 735 | - These files contain python `bytecodes` 736 | 737 | - Module Search Paths 738 | 739 | - When we import a module at start of compiling a py file python look for finding that module in some predefined directories which come with the python installation 740 | 741 | - Packages 742 | 743 | - When we want to organize our python files in separate directories we should make `packages` 744 | - Adding `__init__.py` file to a directory convert it to a python package 745 | - A package is container for one or more modules 746 | 747 | - Sub-Packages 748 | 749 | - After add new directory we should add `init` file 750 | - And make change in import statement 751 | 752 | - Intra-packages References 753 | 754 | - To import a module inside another module of another package we can use `absolute ot relative` statement 755 | - Absolute import is better and `PEP*` recommend it 756 | 757 | - The dir() Function 758 | 759 | - `dir()` is a built-function that show all methods inside a module 760 | 761 | - Executing Modules as Script 762 | 763 | - When a module load for the first time all statement in it will be executed 764 | - The name of the module that starts our program is always `main` 765 | - After add `if name == "main":` to a module when run in directly the the block code of it will be executed. but when imported it into another file this part of code will be ignored 766 | - by this way we make this file useable as script as well as reuseable module that we can import into another module 767 | 768 | ### Python Standard Library 769 | 770 | - What we are going to learn 771 | 772 | - Working with the `path`, `Files`, `SQLite`, `Date/Time`, `Random values` and So on... 773 | 774 | - Working With Path 775 | 776 | - After import `path` library we ca use it in different ways 777 | - We can use `raw strings` to scape lots of double `\\` 778 | - search python 3 `pathlib` in google 779 | - The most important methods of this library is `exist()`, `is_file()`, `is_dir()`, `with_name()` and ... 780 | 781 | - Working With Directories 782 | 783 | - Important methods in `Pathlib` library for work with directories 784 | - We use `iterdir()` method to get list of files and directories in a particular directory 785 | - It returns a generator object because a directory can contain a millions of files within 786 | - We use `glob()` method to find files based on a specific pattern 787 | - We use `rglob()` method to find files based on a specific pattern recursively 788 | 789 | - Working With Files 790 | 791 | - Useful methods to working with files is `exist()`, `unlink()`, `rename()`, `stat()` and ... 792 | - Use `time` module to convert `timestamp` to a human readable format 793 | - By using `read_text(_)` or `read_bytes()` and also `write_text(_)` or `write_bytes()` methods we can change content our file 794 | - We can use `shutil` library to copy files instead of using `read_text(_)` or `write_text()` methods 795 | 796 | - Working With ZIP and CSV Files 797 | 798 | - To work with zip file Use `zipfile` library 799 | - To work with CSV file Use `csv` library 800 | - `csv` is acronym for `Comma Separated Values` 801 | - After importing csv module we use open built-in function to `open()` a csv file 802 | - By using `writer()` method we can built a csv file and write data in it 803 | - By using `reader()` method we can read from a csv file 804 | - By using `list()` method we can make a list of csv rows 805 | 806 | - Working With JSON Files 807 | 808 | - `JSON` is `javaScript Object Notation` 809 | - We use `JSON` to format data in human readable way 810 | - To answer the requests that ask some data from your website you need to provide data in JSON format 811 | - Note that `dump()` and `load()` convert between files and objects, while `dumps()` and `loads()` convert between strings and objects 812 | 813 | - Working With XML Files 814 | 815 | - `XML` means eXtensible Markup Language (not programming language) 816 | - It was designed for storing, organize, and transport data 817 | - It has no predefined tags 818 | - XML separates information for presentation 819 | - XML tags doesn't look like anything in the browser 820 | - `prolog` is the first line of xml and it's optional 821 | - `` and closing tag `` (it's a case sensitive language) 823 | - Nesting is important and avoid mismatch 824 | - There is two different modules that allows us to work with xml file `xml.sax` and `xml.dom` 825 | - In `sax` we never load whole file in to the ram and we only load the pieces that we need and we can't change content (very large xml file) 826 | - In `dom` we load whole file into the ram and we can read write and change file in a hierarchical structure 827 | - We need a `handler` (work with file) and `parser` (translate file) 828 | 829 | - Working With SQLite Database 830 | 831 | - `SQLite` is very light weight Database that we use to store data of an application 832 | - We can use `SQLite Database browser` to manage our sqlite db file in visual (download `db browser for sqlite` from google) 833 | - Insert data into database using a SQL `INSERT` query text 834 | - Read data from database using a SQL `SELECT` query text 835 | - When we try to read from database we'll get cursor 836 | 837 | - Working With Timestamps 838 | 839 | - To work with time and date in python we can use two modules (`time`, `datetime`) 840 | - Time module returns `timestamp` and datetime module returns an object that contains many attributes like `year`, `month`, and ... 841 | - Start of timestamp in unix base systems is a actual date (`1970-1-1`) and timestamp demonstrates all seconds from that time 842 | 843 | - Working With DatetTimes 844 | 845 | - `DateTime` object can converts a date to python object 846 | - `DateTime` can show currents date time by method `now()` 847 | - `DataTime` object can converts `strings` to real datetime by `strptime()` method (by using a pattern like ("%Y/%m/%d")) 848 | - Search Python 3 `Strptime` in Google 849 | - `DataTime` object can converts timestamp object to string by `fromtimestamp()` method 850 | - `DataTime` object can converts datetime object to string by `strftime()` method 851 | - We can compare datetime objects 852 | 853 | - Working With Time Deltas 854 | 855 | - We can add or subtract a duration from our datetime object 856 | - `timedelta` has it's attributes and methods 857 | 858 | - Generating Random Values 859 | 860 | - We can make random values by using `random` module 861 | - We use `string` module to give choices method all ascii letters and numbers to generate a good password 862 | - By using `join()` method we can join all items in a list together 863 | 864 | - WebBrowser Module 865 | 866 | - We can open a web browser by using `webbrowser` Module 867 | 868 | - Send Email 869 | 870 | - We can send email by using email `module` 871 | - First we should add all info that an email need to be sended by `sntp` protocol 872 | 873 | - Line Arguments 874 | 875 | - By using `argv` module we can have access to command prompt extra codes like `user` or `password` attributes which have been written by user 876 | 877 | ### Python Package Index 878 | 879 | - Pypi 880 | 881 | - There are times that we need features that not implemented in the Python standard libraries 882 | - We use `Pypi`(Python Packaging Index) to import lots of useful libraries to our program 883 | - Visit pypi.org and search on it to find your desireable package 884 | - Search in google: `"Best python packages for working with ..."` 885 | 886 | - Pip 887 | 888 | - We use tool named `pip` to manage our packages 889 | - Use `"pip install 'package-name'"` to install a package 890 | - We can use `'pip list'` to check our installed packages 891 | - Check a package like `requests` in pypi.org 892 | - By adding `==` and the a specific version number we can install an earlier or older version of a package(`requests==2.9.*`) (`~`) 893 | - use `pip uninstall 'package-name'` to uninstall a package 894 | - Import an installed packages in python file as example 895 | 896 | - Virtual Environments 897 | 898 | - When we need to work with two different version of a package in two separated projects simultaneously we should create a `virtual environment` for each of them 899 | - By `python -m venv env` we can make a virtual environment for our project 900 | - Our packages would be installed inside the `site-packages` directory 901 | - In windows, to active the virtual environment we should use this command: `env\bin\activate.bat` 902 | - We use `deactivate` command to deactivate `venv` 903 | 904 | - Pipenv 905 | 906 | - `Pipenv` is tool that combine pip with virtual environment to a single tool 907 | - Install pipenv using pip first 908 | - To install packages using pipenv we use `pipenv` command instead of `pip` in `pip install` command 909 | - We can locate our new virtual environment by command: `pipenv --venv` 910 | - We activate our virtual environment by this command : `pipenv shell` and deactivate it by `exit` 911 | - In vscode we need some configuration to use pipenv 912 | - After implementing pipnv you need to change the path of python to your project virtual environment directory 913 | - `pipfile` and `pipfile.lock` help to keep track of our project dependencies 914 | - In another computer by using `pipenv install` we can install all our projects' dependencies (It looks for pipfile) 915 | - To install all packages in their actual version that used in the time of developing of the package 916 | - `pipenv graph` shows you all installed dependencies 917 | - By using `pipenv uninstall` you can remove a dependency 918 | - To find the out dated packages we can use `pipenv update --outdated` 919 | - By using `pipenv update` we can update our dependencies 920 | - `pydoc3 math` show the documentation of math library 921 | - `pydoc -w PACKAGE_NAME` can convert a package to `HTML` file 922 | 923 | ### Tkinter 924 | 925 | - GUI Application 926 | 927 | - Create virtual environment and run it 928 | - Install `tkinter` library (`pipenv install tk`) 929 | - Install `pyinstaller` library 930 | - Create your `part_manager.py` file 931 | - Create your `db.py` file 932 | - Import `tkinter` library (`import tkinter as tk`) 933 | - `mainloop()` method Keep your app run permanently 934 | - Change your app title 935 | - You need to add a widget to your root application 936 | - By calling `StringVar()`, `Label()`, and `Entry()` methods we can create a data entry section 937 | - We can add `grid` geometry to add a button to our application 938 | - `grid` is most compatible geometry manager that is most flexible with all kind of applications 939 | - By using `geometry()` method we can apply size to our app 940 | - Add some widget to your app (`Label`, `textbox` and ...) 941 | - Create a `listbox` using `Listbox()` method for your app to show items 942 | - `rowspan` and `columnspan` give more space to your grid cells vertically and horizontally 943 | - Now we need a `scrollbar`. Create it with `Scrollbar()` method and place it in the third column 944 | - By using `configure()` method we can stick our scrollbar to listbox 945 | - `command` option set scroll behavior 946 | - Now we need to add our buttons to app by using `Button()` method 947 | - For `command` option we need to path a function that do something when user push the button 948 | - Define your command functions at top of the file 949 | - Now we need to define our database in `db.py` file 950 | - It's more better, organized and optimized to use class 951 | - In our class `constructor` we need to define db and connection to it 952 | - Also we should define `table` at first if it doesn't exist 953 | - Now we need to define `CRUD` operations in the form of the `class methods` 954 | - After define `cursor` in each method you need execute your SQL command and finally commit it 955 | - Give your values to cursor in the form of tuple 956 | - In the case of deleting an object it's important that you have a `deconstructing` method in your class 957 | - Now create an object with your class and insert some date into it (Use my_file repo) 958 | - Import your `Database` class inside part_manager module and instantiate it 959 | - Now we can all our methods inside the db module and place them in the functions that we define for buttons 960 | - `populate_list` echo all records inside the database 961 | - First delete all items in listbox and import database information into it 962 | - Define `add_item` method and use it as command for `Add Part` button 963 | - Your app add item even all textbox are empty and you should avoid it by using `messagebox` and check input 964 | - To remove an item we need to find its `id` by another method called `select_item` whcih we define to get selected item in the list 965 | - Our select item should get an `event` that is binded to our Listbox SELECT 966 | - Also we need to fill textboxes with actual info in data base after selection 967 | - To remove an item just by passing first element of selected item to `remove()` method we can do it 968 | - For `Update` you should give the selected item id and all textboxes info to update method 969 | - Now you can create an executable file of your application by using `pyinstaller` module ad this command: 970 | - `"pyinstaller --onefile --windowed app.py"` 971 | 972 | 973 | ### Give star⭐ if it was useful 😉 974 | --------------------------------------------------------------------------------