├── README.md ├── All Python Practices ├── 1-password-length-counter-program.py └── 2-distance-converter-program.py ├── Chapter 2 Contorol Flow ├── Lessons │ ├── nestedloop(matrix).md │ ├── BreakAndContinueStatements.md │ ├── OperatorsInPython.md │ ├── WhileLoops.md │ ├── ConditionalStatements(if&else).md │ └── ForLoops.md └── Code │ └── main.py ├── Chapter 1 Introduction to Python ├── Lessons │ ├── BasicInputAndOutput.md │ ├── WhyPython.md │ ├── VariablesAndDatatypes.md │ ├── TypeConversion.md │ ├── WorkingWithStrings.md │ └── built-InFunctions&Methods.md └── Code │ └── main.py ├── Chapter 3 Data Structures ├── Code │ └── main.py └── Lessons │ ├── DataStructures.md │ ├── Tuples&Sets.md │ ├── WorkingWithDictionaries.md │ └── WorkingWithLists.md └── Chapter 4 Functions ├── main.py └── chapter4.md /README.md: -------------------------------------------------------------------------------- 1 | # READ ME -------------------------------------------------------------------------------- /All Python Practices/1-password-length-counter-program.py: -------------------------------------------------------------------------------- 1 | name = input('Enter your name: ') 2 | password = input('Enter your password: ') 3 | 4 | hidden_password = '*' * len(password) 5 | 6 | len_pass = len(password) 7 | 8 | print(f'ASC, {name} your password {hidden_password} is {len_pass} letters long') -------------------------------------------------------------------------------- /Chapter 2 Contorol Flow/Lessons/nestedloop(matrix).md: -------------------------------------------------------------------------------- 1 | ## Nested `for` loops 2 | 3 | We can use nested `for` loops to iterate over multiple sequences. For example, let's print all possible combinations of two colors: 4 | 5 | ```python 6 | colors1 = ["red", "green", "blue"] 7 | colors2 = ["yellow", "orange", "purple"] 8 | for color1 in colors1: 9 | for color2 in colors2: 10 | print(color1, color2) 11 | ``` 12 | 13 | Output: 14 | ``` 15 | red yellow 16 | red orange 17 | red purple 18 | green yellow 19 | green orange 20 | green purple 21 | blue yellow 22 | blue orange 23 | blue purple 24 | ``` -------------------------------------------------------------------------------- /All Python Practices/2-distance-converter-program.py: -------------------------------------------------------------------------------- 1 | print('Welcome to distance converter program') 2 | while True: 3 | choice = input('(MI) for miles, (KM) for kilometers & (q) for quit: ').lower() 4 | if choice == 'q': 5 | break 6 | elif choice == 'mi': 7 | km = int(input('Enter the kilometers: ')) 8 | mi = km / 1.609 9 | print(f'{km} killometers is {mi} miles') 10 | elif choice == 'km': 11 | mi = int(input('Enter the miles: ')) 12 | km = mi * 1.609 13 | print(f'{mi} miles is {km} killometers') 14 | else: 15 | print('Invalid! please try again.') -------------------------------------------------------------------------------- /Chapter 1 Introduction to Python/Lessons/BasicInputAndOutput.md: -------------------------------------------------------------------------------- 1 | In Python, you can use the `input()` function to get input from the user and the `print()` function to display output to the user. Here are some examples: 2 | 3 | 1. Getting input from the user: 4 | 5 | ```python 6 | name = input("What is your name? ") 7 | print("Hello, " + name) 8 | ``` 9 | 10 | In this example, we're using the `input()` function to get the user's name, and then using the `print()` function to display a greeting. 11 | 12 | 2. Displaying output to the user: 13 | 14 | ```python 15 | print("The answer is", 34) 16 | ``` 17 | 18 | In this example, we're using the `print()` function to display the text "The answer is" followed by the value 34. 19 | 20 | here is how to get user information using `input()` and and output using `print()` -------------------------------------------------------------------------------- /Chapter 3 Data Structures/Code/main.py: -------------------------------------------------------------------------------- 1 | # numbers = [1,2,3,4,5] 2 | 3 | # my_list = [1,2,3, 'Sharafdin', 9, 8, 7, 0] 4 | 5 | # print(my_list[3]) 6 | 7 | # print(my_list[1::2]) 8 | 9 | # my_list[-1] = 'Mr Sharafdin' 10 | 11 | # my_list.append(100) 12 | 13 | # my_list.remove(2) 14 | 15 | # print(my_list) 16 | 17 | # matrix = [ 18 | # [1,2,3], 19 | # [4,5,6], 20 | # [7,8,9] 21 | # ] 22 | 23 | # print(matrix[1][2]) 24 | 25 | # person = { 26 | # "name": "Mr Sharafdin", 27 | # "age": 34, 28 | # "country": "Somalia" 29 | # } 30 | 31 | # text = "Your age is" 32 | 33 | # print(text, person["age"]) 34 | # print('Your name is', person["name"]) 35 | 36 | # print(person["sex"]) 37 | 38 | # print(person.get("name")) 39 | # print(person.get("sex")) 40 | 41 | # person["country"] = "USA" 42 | 43 | # person["sex"] = "male" 44 | 45 | # del person["age"] 46 | 47 | # print(person) 48 | 49 | # my_tuple = (1,2,3,4,5) 50 | 51 | # print(my_tuple[0]) 52 | # print(my_tuple[-1]) 53 | 54 | # my_set = {1,2,3,4,2} 55 | 56 | # my_set.add(10) 57 | 58 | # my_set.remove(3) 59 | 60 | # set1 = {1,2,3} 61 | # set2 = {2,4,3} 62 | 63 | # print(set1.difference(set2)) -------------------------------------------------------------------------------- /Chapter 3 Data Structures/Lessons/DataStructures.md: -------------------------------------------------------------------------------- 1 | # Data Structure 2 | In Python, data structures are objects that are used to store and organize data in memory. Here are some common data structures in Python: 3 | 4 | - Lists: Lists are ordered collections of elements that can be modified. Lists are created using square brackets `[]` and can contain elements of any data type. 5 | 6 | - Tuples: Tuples are ordered collections of elements that cannot be modified. Tuples are created using parentheses `()` and can contain elements of any data type. 7 | 8 | - Sets: Sets are unordered collections of unique elements. Sets are created using curly braces `{}` or the `set()` function. 9 | 10 | - Dictionaries: Dictionaries are unordered collections of key-value pairs. Dictionaries are created using curly braces `{}` or the `dict()` function. 11 | 12 | In addition to these built-in data structures, Python also provides several modules that offer specialized data structures for specific use cases. For example: 13 | 14 | - `collections`: This module provides additional data structures such as `deque`, `Counter`, and `OrderedDict`. 15 | 16 | - `heapq`: This module provides functions for working with heap data structures, which are useful for implementing priority queues. 17 | 18 | - `array`: This module provides an array data structure, which is similar to a list but is optimized for storing elements of a single data type. -------------------------------------------------------------------------------- /Chapter 1 Introduction to Python/Lessons/WhyPython.md: -------------------------------------------------------------------------------- 1 | # What is Python 2 | Python is a high-level, interpreted programming language that was first released in 1991. It has since become one of the most popular programming languages in the world, with a large and active community of developers who use it for a wide range of applications. Python is known for its simplicity, readability, and ease of use, making it a popular choice for both beginners and experienced programmers. 3 | 4 | # Some of the most common uses of Python include: 5 | 6 | ## Web development: 7 | Python is used to create web applications and websites using frameworks such as Django, Flask, and Pyramid. 8 | 9 | ## Data analysis and visualization: 10 | Python has a wide range of libraries for data analysis and visualization, including Pandas, NumPy, and Matplotlib. 11 | 12 | ## Machine learning and artificial intelligence: 13 | Python is widely used for machine learning and AI applications, with popular libraries such as TensorFlow, Keras, and PyTorch. 14 | 15 | ## Scientific computing: 16 | Python has a range of libraries that are used for scientific computing, including SciPy, SymPy, and BioPython. 17 | 18 | ## Automation and scripting: 19 | Python is often used for automating repetitive tasks and for scripting tasks that would be difficult to do manually. 20 | 21 | ## Game development: 22 | Python is used for game development, with libraries such as Pygame and PyOpenGL. 23 | 24 | ### The cool part of Python 25 | 26 | Python's popularity is due in part to the fact that it is open source, meaning that the source code is freely available and can be modified and distributed by anyone. This has led to a large and active community of developers who have created a wide range of libraries, frameworks, and tools that make it easier to use Python for a variety of applications. -------------------------------------------------------------------------------- /Chapter 1 Introduction to Python/Lessons/VariablesAndDatatypes.md: -------------------------------------------------------------------------------- 1 | In Python, a variable is a named location in memory that is used to store a value. Once a variable is defined, it can be used throughout the program to refer to the value stored in that location. Here's an example of defining a variable in Python: 2 | 3 | ```python 4 | x = 5 5 | ``` 6 | 7 | In this example, we're creating a variable called `x` and assigning it the value `5`. 8 | 9 | Python supports several data types, including: 10 | 11 | 1. Numeric data types: These include integers, floats, and complex numbers. 12 | 13 | ```python 14 | x = 5 # integer 15 | y = 3.14 # float 16 | z = 2 + 3j # complex number 17 | ``` 18 | 19 | 2. Strings: These are sequences of characters enclosed in single or double quotes. 20 | 21 | ```python 22 | s = "Hello, world!" 23 | ``` 24 | 25 | 3. Booleans: These are logical values that can be either True or False. 26 | 27 | ```python 28 | a = True 29 | b = False 30 | ``` 31 | 32 | 4. Lists: These are ordered collections of values, which can be of different data types. 33 | 34 | ```python 35 | l = [1, 2, "three", True] 36 | ``` 37 | 38 | 5. Tuples: These are similar to lists, but they are immutable, meaning they cannot be changed once they are created. 39 | 40 | ```python 41 | t = (1, 2, "three", True) 42 | ``` 43 | 44 | 6. Sets: These are unordered collections of unique values. 45 | 46 | ```python 47 | s = {1, 2, 3, 4, 5} 48 | ``` 49 | 50 | 7. Dictionaries: These are collections of key-value pairs, where each key is associated with a value. 51 | 52 | ```python 53 | d = {"name": "John", "age": 30, "city": "New York"} 54 | ``` 55 | 56 | Python is a dynamically typed language, which means that the data type of a variable is determined at runtime based on the value assigned to it. This also means that a variable can be reassigned to a value of a different data type. -------------------------------------------------------------------------------- /Chapter 1 Introduction to Python/Lessons/TypeConversion.md: -------------------------------------------------------------------------------- 1 | Type conversion, also known as typecasting, is the process of converting a value from one data type to another. Python provides several built-in functions for type conversion, which can be particularly useful when working with user input, or when performing operations that involve different data types. 2 | 3 | Here are some examples of type conversion in Python: 4 | 5 | 1. Converting between numeric types: 6 | 7 | ```python 8 | x = 5 9 | y = float(x) # converting integer to float 10 | z = int(y) # converting float to integer 11 | print(x, y, z) # output: 5, 5.0, 5 12 | ``` 13 | 14 | In this example, we're using the `float()` and `int()` functions to convert an integer to a float and back to an integer. 15 | 16 | 2. Converting between string and numeric types: 17 | 18 | ```python 19 | s = "123" 20 | x = int(s) # converting string to integer 21 | y = float(s) # converting string to float 22 | z = str(x) # converting integer to string 23 | print(s, x, y, z) # output: "123", 123, 123.0, "123" 24 | ``` 25 | 26 | In this example, we're using the `int()` and `float()` functions to convert a string containing a number to an integer or float, and the `str()` function to convert an integer back to a string. 27 | 28 | 3. Converting between sequence types: 29 | 30 | ```python 31 | s = "hello" 32 | lst = list(s) # converting string to list 33 | tpl = tuple(lst) # converting list to tuple 34 | print(s, lst, tpl) # output: "hello", ['h', 'e', 'l', 'l', 'o'], ('h', 'e', 'l', 'l', 'o') 35 | ``` 36 | 37 | In this example, we're using the `list()` and `tuple()` functions to convert a string to a list and then to a tuple. 38 | 39 | These are just a few examples of the many ways you can perform type conversion in Python. Depending on your application, you may need to use additional type conversion functions or methods to perform specific operations or conversions. -------------------------------------------------------------------------------- /Chapter 1 Introduction to Python/Code/main.py: -------------------------------------------------------------------------------- 1 | # # # name = value 2 | 3 | # # # int 4 | 5 | # # age = 34 6 | 7 | # # # float 8 | 9 | # # score = 99.7 10 | 11 | # # # string 12 | 13 | # # name = 'Sharafdin' 14 | # # age = '123' 15 | 16 | # player1 = True 17 | # player2 = False 18 | 19 | 20 | # name = input('What is your name: ') 21 | # print('Your name: ' + name) 22 | 23 | # print('Jawaabtu waa: ', 34) 24 | 25 | # print('Sharafdin') 26 | 27 | # num1 = int(input('Number 1:')) 28 | 29 | # int() 30 | # str() 31 | # bool() 32 | # num1 = int(input('Number 1:')) 33 | 34 | # num2 = int(input('Number 2:')) 35 | 36 | # print('Jawaabtu waa: ', num1 + num2) 37 | 38 | # print(type(num1), type(num2)) 39 | 40 | # name = input('Name: ') 41 | 42 | # name = int(input('Name: ')) 43 | 44 | # print(type(name)) 45 | # str(age = 34) 46 | 47 | # age = 34 48 | 49 | # type = type(str(age)) 50 | 51 | # print(type) 52 | 53 | # first_name = 'Mr' 54 | # last_name = ' Sharafdin' 55 | 56 | # print(first_name + last_name) 57 | 58 | # name = input('Your name: ') 59 | # age = input('Your Age: ') 60 | 61 | # print('Your name is ' + name + ' and your age is ' + age) 62 | 63 | # name = 'Sharafdin' 64 | 65 | # num = '12345678' 66 | 67 | # [] 68 | 69 | # 0123 70 | 71 | # print(num[1::2]) 72 | 73 | # name = input('Name: ') 74 | # age = int(input('Age: ')) 75 | 76 | # print('Your name is ' + name + ' and your age is ' + age) 77 | 78 | # print(f"Your name is {name} and your age is {type(age)}") 79 | 80 | # name = 'mr sharafdin' 81 | 82 | # print(name.title()) 83 | 84 | # s = 'Hello World Yow!' 85 | 86 | # print(s.split(' ')) 87 | 88 | # name = 'Isa Yusuf Sharafdin' 89 | 90 | # namelist = name.split(' ') 91 | 92 | # print('Your last name:', namelist[-1]) 93 | 94 | # name = input('Enter your name: ') 95 | # password = input('Enter your password: ') 96 | 97 | # print('ASC, ' + name + 'Your password ' + password + ' is ' + len(password) + ' letters long.') 98 | 99 | # hidden_password = '*' * len(password) 100 | 101 | # len_pass = len(password) 102 | 103 | # print(f'ASC, {name} your password {hidden_password} is {len_pass} letters long') -------------------------------------------------------------------------------- /Chapter 1 Introduction to Python/Lessons/WorkingWithStrings.md: -------------------------------------------------------------------------------- 1 | In Python, strings are a sequence of characters that can be enclosed in single or double quotes. Here are some examples of working with strings in Python: 2 | 3 | 1. Concatenating strings: 4 | 5 | ```python 6 | s1 = "Hello," 7 | s2 = " world!" 8 | s3 = s1 + s2 9 | print(s3) 10 | ``` 11 | 12 | In this example, we're using the `+` operator to concatenate two strings into a single string. 13 | 14 | 2. Accessing characters in a string: 15 | 16 | ```python 17 | s = "Hello, world!" 18 | print(s[0]) # prints the first character of the string 19 | print(s[-1]) # prints the last character of the string 20 | ``` 21 | 22 | In this example, we're using indexing to access individual characters in the string. Indexing in Python starts at 0, so `s[0]` refers to the first character of the string, and `s[-1]` refers to the last character of the string. 23 | 24 | 3. Slicing a string: 25 | 26 | ```python 27 | s = "Hello, world!" 28 | print(s[0:5]) # prints the first 5 characters of the string 29 | print(s[7:]) # prints the substring starting from the 7th character of the string 30 | ``` 31 | 32 | In this example, we're using slicing to extract a portion of the string. The syntax for slicing is `[start:end]`, where `start` is the index of the first character to include in the slice, and `end` is the index of the first character to exclude from the slice. 33 | 34 | 4. f string: 35 | 36 | ```python 37 | name = "John" 38 | age = 30 39 | print(f"My name is {} and I'm {} years old.") 40 | ``` 41 | 42 | In this example, we're using the `f` string to insert the values of the `name` and `age` variables into the string. The curly braces `{}` are used as placeholders for the variables. 43 | 44 | 5. Using string methods: 45 | 46 | ```python 47 | s = "hello, world!" 48 | print(s.upper()) # prints the string in uppercase 49 | print(s.capitalize()) # capitalizes the first character of the string 50 | print(s.replace("world", "Python")) # replaces "world" with "Python" in the string 51 | ``` 52 | 53 | In this example, we're using some built-in string methods to modify the string. The `upper()` method converts the string to uppercase, the `capitalize()` method capitalizes the first character of the string, and the `replace()` method replaces a substring in the string with another substring. -------------------------------------------------------------------------------- /Chapter 2 Contorol Flow/Lessons/BreakAndContinueStatements.md: -------------------------------------------------------------------------------- 1 | # Break and continue statements 2 | 3 | In Python, the `break` and `continue` statements are used to control the flow of a loop. 4 | 5 | The `break` statement is used to exit a loop prematurely, regardless of whether the loop condition has been met or not. When the `break` statement is encountered inside a loop, the loop immediately terminates and control is transferred to the next statement after the loop. 6 | 7 | For example, let's use a `while` loop to print the numbers from 1 to 5, but break out of the loop when we reach the number 3: 8 | 9 | ```python 10 | i = 1 11 | while i <= 5: 12 | print(i) 13 | if i == 3: 14 | break 15 | i += 1 16 | ``` 17 | 18 | Output: 19 | ``` 20 | 1 21 | 2 22 | 3 23 | ``` 24 | 25 | In this example, we use a `while` loop to print the numbers from 1 to 5. Inside the loop, we use an `if` statement to check if the current value of `i` is equal to 3. If it is, we use the `break` statement to exit the loop prematurely. As a result, only the numbers 1, 2, and 3 are printed. 26 | 27 | The `continue` statement is used to skip the current iteration of a loop and move on to the next iteration. When the `continue` statement is encountered inside a loop, the remaining statements inside the loop for the current iteration are skipped, and control is transferred to the next iteration of the loop. 28 | 29 | For example, let's use a `for` loop to print the even numbers from 1 to 10, but skip the number 6: 30 | 31 | ```python 32 | for i in range(1, 11): 33 | if i == 6: 34 | continue 35 | if i % 2 == 0: 36 | print(i) 37 | ``` 38 | 39 | Output: 40 | ``` 41 | 2 42 | 4 43 | 8 44 | 10 45 | ``` 46 | 47 | In this example, we use a `for` loop to iterate over the numbers from 1 to 10. Inside the loop, we use an `if` statement to check if the current value of `i` is equal to 6. If it is, we use the `continue` statement to skip the current iteration of the loop and move on to the next iteration. As a result, the number 6 is skipped and only the even numbers (2, 4, 8, and 10) are printed. 48 | 49 | Both the `break` and `continue` statements are useful for controlling the flow of a loop and making your code more efficient. However, it's important to use them carefully and avoid creating infinite loops or other unintended behavior. -------------------------------------------------------------------------------- /Chapter 2 Contorol Flow/Code/main.py: -------------------------------------------------------------------------------- 1 | # x = 10 2 | 3 | # if x < 5: 4 | # print('x is less than 5') 5 | # elif x == 5: 6 | # print('x is 5') 7 | # else: 8 | # print('x is greater than 5') 9 | 10 | # number = int(input('Enter the number: ')) 11 | 12 | # if number < 0: 13 | # print(number, 'is negative') 14 | # elif number == 0: 15 | # print('This number is zero') 16 | # else: 17 | # print(number, 'is positive') 18 | 19 | # x = 10 20 | # y = 6 21 | 22 | # print(x / y) 23 | # print(12 % 5) 24 | 25 | # print(3 ** 4) 26 | 27 | # 3^2 28 | 29 | # print(12 / 5) 30 | # print(12 // 5) 31 | 32 | # print(x // y) 33 | 34 | # x = 10 35 | 36 | # x = x + 1 37 | 38 | # x += 3 39 | 40 | # print(x) 41 | 42 | # y = 6 43 | 44 | # y -= 2 45 | 46 | # print(y) 47 | 48 | # x = 10 49 | 50 | # x += 2 51 | 52 | # x = x + 2 53 | 54 | # print(x) 55 | 56 | # x = 10 57 | # y = 6 58 | 59 | # print(x > y) 60 | # print(x < y) 61 | 62 | # print(x >= y) 63 | # print(x <= y) 64 | 65 | # print(x == y) 66 | 67 | # if x == y: 68 | # print('x is equal y') 69 | 70 | # print(x != y) 71 | 72 | # x = 10 73 | # y = 6 74 | # z = 3 75 | 76 | # print(x > y and z < y) 77 | 78 | # print(x < y or z > y) 79 | 80 | # 10 < 6 or 3 > 6 81 | # 10 > 6 or 3 < 6 82 | 83 | # print(not(x > y)) 84 | 85 | # for i in range(1, 11): 86 | # print(i) 87 | 88 | # name = 'Sharafdin' 89 | 90 | # for character in name: 91 | # print(character) 92 | 93 | # for number in range(10): 94 | # print('Sharafdin') 95 | 96 | # colors1 = ["red", "green", "blue"] 97 | # colors2 = ["yellow", "orange", "purple"] 98 | 99 | # for color1 in colors1: 100 | # print('The loop is started') 101 | # print(color1) 102 | # for color2 in colors2: 103 | # print(color1, color2) 104 | 105 | 106 | # i = 0 107 | 108 | # while i < 10: 109 | # print('Sharafdin') 110 | # # i = i + 1 111 | # i += 1 112 | 113 | # print('Welcome to distance converter program') 114 | # while True: 115 | # choice = input('(MI) for miles, (KM) for kilometers & (q) for quit: ').lower() 116 | # if choice == 'q': 117 | # break 118 | # elif choice == 'mi': 119 | # km = int(input('Enter the kilometers: ')) 120 | # mi = km / 1.609 121 | # print(f'{km} killometers is {mi} miles') 122 | # elif choice == 'km': 123 | # mi = int(input('Enter the miles: ')) 124 | # km = mi * 1.609 125 | # print(f'{mi} miles is {km} killometers') 126 | # else: 127 | # print('Invalid! please try again.') -------------------------------------------------------------------------------- /Chapter 3 Data Structures/Lessons/Tuples&Sets.md: -------------------------------------------------------------------------------- 1 | ## Tuples 2 | 3 | A tuple is an ordered collection of elements, enclosed in parentheses `()`. Tuples are similar to lists, but they are immutable, meaning that once a tuple is created, its values cannot be changed. 4 | 5 | Tuples are often used to group related data together, such as the x and y coordinates of a point. Tuples can also be used as keys in dictionaries, since they are immutable and hashable. 6 | 7 | Here's an example of how to create a tuple in Python: 8 | 9 | ```python 10 | my_tuple = (1, 2, 3) 11 | ``` 12 | 13 | In this example, `my_tuple` contains the elements `1`, `2`, and `3`. 14 | 15 | You can access individual elements in a tuple using indexing, just like with lists. For example: 16 | 17 | ```python 18 | my_tuple = (1, 2, 3) 19 | print(my_tuple[0]) # prints 1 20 | ``` 21 | 22 | You can also use negative indexing to access elements from the end of the tuple: 23 | 24 | ```python 25 | my_tuple = (1, 2, 3) 26 | print(my_tuple[-1]) # prints 3 27 | ``` 28 | 29 | ## Sets 30 | 31 | A set is an unordered collection of unique elements, enclosed in curly braces `{}`. Sets are similar to lists and tuples, but they can only contain unique elements, meaning that duplicates are automatically removed. 32 | 33 | Sets are often used to perform mathematical operations such as union, intersection, and difference. 34 | 35 | Here's an example of how to create a set in Python: 36 | 37 | ```python 38 | my_set = {1, 2, 3} 39 | ``` 40 | 41 | In this example, `my_set` contains the elements `1`, `2`, and `3`. 42 | 43 | You can add elements to a set using the `add()` method: 44 | 45 | ```python 46 | my_set = {1, 2, 3} 47 | my_set.add(4) 48 | print(my_set) # prints {1, 2, 3, 4} 49 | ``` 50 | 51 | You can remove elements from a set using the `remove()` method: 52 | 53 | ```python 54 | my_set = {1, 2, 3} 55 | my_set.remove(2) 56 | print(my_set) # prints {1, 3} 57 | ``` 58 | 59 | You can perform mathematical operations on sets using methods such as `union()`, `intersection()`, and `difference()`. For example: 60 | 61 | ```python 62 | set1 = {1, 2, 3} 63 | set2 = {2, 3, 4} 64 | print(set1.difference(set2)) # prints {1} 65 | ``` 66 | 67 | ## Conclusion 68 | 69 | Tuples and sets are two different data types in Python that serve different purposes. Tuples are used to group related data together, while sets are used to store a collection of unique elements and perform mathematical operations on them. By understanding how to create, access, and manipulate tuples and sets, you can become a more effective Python programmer. -------------------------------------------------------------------------------- /Chapter 2 Contorol Flow/Lessons/OperatorsInPython.md: -------------------------------------------------------------------------------- 1 | # Python Operators 2 | 3 | Operators in Python are symbols or keywords used to perform operations on one or more values. Python has several types of operators, including: 4 | 5 | ## Arithmetic Operators 6 | 7 | Arithmetic operators are used to perform basic mathematical operations on numeric values. Here are some examples: 8 | 9 | ```python 10 | x = 10 11 | y = 6 12 | 13 | print(x + y) # Addition 14 | print(x - y) # Subtraction 15 | print(x * y) # Multiplication 16 | print(x / y) # Division 17 | print(x % y) # Modulus (returns the remainder after division) 18 | print(x ** y) # Exponentiation (raises x to the power of y) 19 | print(x // y) # Floor Division (returns the integer result of division) 20 | ``` 21 | 22 | ## Assignment Operators 23 | 24 | Assignment operators are used to assign a value to a variable. They also perform an operation on the variable at the same time. Here are some examples: 25 | 26 | ```python 27 | x = 10 28 | x += 5 # Same as x = x + 5 29 | print(x) 30 | 31 | y = 6 32 | y -= 3 # Same as y = y - 3 33 | print(y) 34 | 35 | z = 3 36 | z *= 2 # Same as z = z * 2 37 | print(z) 38 | ``` 39 | 40 | ## Comparison Operators 41 | 42 | Comparison operators are used to compare two values and return a Boolean value (True or False) based on the result. Here are some examples: 43 | 44 | ```python 45 | x = 10 46 | y = 6 47 | 48 | print(x > y) # Greater than 49 | print(x < y) # Less than 50 | print(x >= y) # Greater than or equal to 51 | print(x <= y) # Less than or equal to 52 | print(x == y) # Equal to 53 | print(x != y) # Not equal to 54 | ``` 55 | 56 | ## Logical Operators 57 | 58 | Logical operators are used to combine two or more Boolean expressions and return a Boolean value. Here are some examples: 59 | 60 | ```python 61 | x = 10 62 | y = 6 63 | z = 3 64 | 65 | print(x > y and y > z) # And (returns True if both expressions are True) 66 | print(x > y or y < z) # Or (returns True if either expression is True) 67 | print(not(x > y)) # Not (returns the opposite of the expression) 68 | ``` 69 | 70 | ## Membership Operators 71 | 72 | Membership operators are used to test if a sequence (such as a string, list, or tuple) contains a specific value. Here are some examples: 73 | 74 | ```python 75 | x = "Hello, World!" 76 | 77 | print("Hello" in x) # In (returns True if the specified value is present in the sequence) 78 | print("Goodbye" not in x) # Not In (returns True if the specified value is not present in the sequence) 79 | ``` 80 | 81 | These are the basic types of operators in Python, but there are also other operators that are used for more advanced programming tasks. -------------------------------------------------------------------------------- /Chapter 3 Data Structures/Lessons/WorkingWithDictionaries.md: -------------------------------------------------------------------------------- 1 | # Dictionaries in Python 2 | 3 | Dictionaries are a built-in data structure in Python that allow you to store and retrieve data using key-value pairs. In this lesson, we will cover the basics of working with dictionaries in Python. 4 | 5 | ## Creating a Dictionary 6 | 7 | To create a dictionary in Python, use curly braces `{}` and separate the keys and values with a colon `:`. For example: 8 | 9 | ```python 10 | my_dict = {"name": "Sharafdin", "age": 34, "planet": "Jupiter"} 11 | ``` 12 | 13 | In this example, `my_dict` contains three key-value pairs: `"name": "Sharafdin"`, `"age": 34`, and `"planet": "Jupiter"`. 14 | 15 | ## Accessing Values 16 | 17 | You can access the value associated with a key in a dictionary using square brackets `[]` and the key name. For example: 18 | 19 | ```python 20 | my_dict = {"name": "Sharafdin", "age": 34, "planet": "Jupiter"} 21 | print(my_dict["age"]) # prints 34 22 | ``` 23 | 24 | If the key does not exist in the dictionary, you will get a `KeyError`: 25 | 26 | ```python 27 | my_dict = {"name": "Sharafdin", "age": 34, "planet": "Jupiter"} 28 | print(my_dict["gender"]) # raises KeyError: 'gender' 29 | ``` 30 | 31 | To avoid this error, you can use the `get()` method, which returns `None` if the key is not found: 32 | 33 | ```python 34 | my_dict = {"name": "Sharafdin", "age": 34, "planet": "Jupiter"} 35 | print(my_dict.get("gender")) # prints None 36 | ``` 37 | 38 | ## Modifying Values 39 | 40 | You can modify the value associated with a key in a dictionary by assigning a new value to the key: 41 | 42 | ```python 43 | my_dict = {"name": "Sharafdin", "age": 34, "planet": "Jupiter"} 44 | my_dict["age"] = 31 45 | print(my_dict) # prints {"name": "Sharafdin", "age": 31, "planet": "Jupiter"} 46 | ``` 47 | 48 | ## Adding and Removing Key-Value Pairs 49 | 50 | You can add a new key-value pair to a dictionary by assigning a value to a new key: 51 | 52 | ```python 53 | my_dict = {"name": "Sharafdin", "age": 34, "planet": "Jupiter"} 54 | my_dict["gender"] = "Male" 55 | print(my_dict) # prints {"name": "Sharafdin", "age": 34, "planet": "Jupiter", "gender": "Male"} 56 | ``` 57 | 58 | You can remove a key-value pair from a dictionary using the `del` keyword: 59 | 60 | ```python 61 | my_dict = {"name": "Sharafdin", "age": 34, "planet": "Jupiter"} 62 | del my_dict["planet"] 63 | print(my_dict) # prints {"name": "Sharafdin", "age": 34} 64 | ``` 65 | 66 | ## Conclusion 67 | 68 | Dictionaries are a powerful and flexible data structure in Python that allow you to store and retrieve data using key-value pairs. By understanding how to create, access, modify, and iterate over dictionaries, you can become a more effective Python programmer. -------------------------------------------------------------------------------- /Chapter 2 Contorol Flow/Lessons/WhileLoops.md: -------------------------------------------------------------------------------- 1 | # While loops 2 | 3 | In Python, the `while` loop is used to repeat a block of code while a certain condition is true. The loop will continue to execute as long as the condition remains true. 4 | 5 | The basic syntax of a `while` loop in Python is: 6 | 7 | ```python 8 | while condition: 9 | # code to be executed while condition is true 10 | ``` 11 | 12 | Here, `condition` is some expression that evaluates to a Boolean value (`True` or `False`). The code inside the loop will continue to be executed as long as `condition` is `True`. If `condition` is `False` when the loop is first encountered, then the code inside the loop will be skipped entirely. 13 | 14 | For example, let's say we want to print the numbers from 1 to 5 using a `while` loop: 15 | 16 | ```python 17 | i = 1 18 | while i <= 5: 19 | print(i) 20 | i += 1 21 | ``` 22 | 23 | Output: 24 | ``` 25 | 1 26 | 2 27 | 3 28 | 4 29 | 5 30 | ``` 31 | 32 | In this example, we initialize the variable `i` to 1 before the loop starts. The `while` loop continues to execute as long as `i` is less than or equal to 5. Inside the loop, we print the value of `i` and then increment it by 1 using the `i += 1` statement. 33 | 34 | We can also use a `while` loop to iterate over a list or other sequence. For example, let's print each item in a list of numbers: 35 | 36 | ```python 37 | numbers = [1, 2, 3, 4, 5] 38 | i = 0 39 | while i < len(numbers): 40 | print(numbers[i]) 41 | i += 1 42 | ``` 43 | 44 | Output: 45 | ``` 46 | 1 47 | 2 48 | 3 49 | 4 50 | 5 51 | ``` 52 | 53 | In this example, we initialize the variable `i` to 0 before the loop starts. The `while` loop continues to execute as long as `i` is less than the length of the `numbers` list. Inside the loop, we print the value of the `i`-th item in the list using the index operator (`numbers[i]`), and then increment `i` by 1. 54 | 55 | We can also use a `while` loop to perform some task until a certain condition is met. For example, let's ask the user to enter a number between 1 and 10: 56 | 57 | ```python 58 | number = 0 59 | while not (1 <= number <= 10): 60 | number = int(input("Enter a number between 1 and 10: ")) 61 | print("You entered:", number) 62 | ``` 63 | 64 | In this example, we initialize the variable `number` to 0 before the loop starts. The `while` loop continues to execute as long as `number` is not between 1 and 10 (inclusive). Inside the loop, we ask the user to enter a number using the `input()` function and convert it to an integer using the `int()` function. If the number is between 1 and 10, the loop will exit and we will print a message indicating the number that was entered. 65 | 66 | Note that in all of these examples, it's important to ensure that the loop will eventually terminate. If the condition in the `while` loop is never `False`, then the loop will continue to execute indefinitely, which can cause the program to hang or crash. -------------------------------------------------------------------------------- /Chapter 3 Data Structures/Lessons/WorkingWithLists.md: -------------------------------------------------------------------------------- 1 | # Lists in Python 2 | 3 | In Python, a list is a built-in data structure that represents an ordered collection of elements. Lists can contain any data type, including other lists. 4 | 5 | ## Creating a List 6 | 7 | To create a list in Python, you use square brackets `[]` and separate the elements with commas. For example: 8 | 9 | ```python 10 | my_list = [1, 2, 3, "hello", [4, 5, 6]] 11 | ``` 12 | 13 | In this example, `my_list` contains five elements: the integers 1, 2, and 3, the string "hello", and another list `[4, 5, 6]`. 14 | 15 | ## Accessing Elements 16 | 17 | You can access individual elements in a list using their index, which starts at 0. For example: 18 | 19 | ```python 20 | my_list = [1, 2, 3] 21 | print(my_list[0]) # prints 1 22 | ``` 23 | 24 | You can also use negative indexing to access elements from the end of the list: 25 | 26 | ```python 27 | my_list = [1, 2, 3] 28 | print(my_list[-1]) # prints 3 29 | ``` 30 | 31 | ## Slicing Lists 32 | 33 | You can extract a subset of a list using slicing. Slicing uses the colon `:` operator to specify a range of indices. For example: 34 | 35 | ```python 36 | my_list = [1, 2, 3, 4, 5] 37 | subset = my_list[1:4] 38 | print(subset) # prints [2, 3, 4] 39 | ``` 40 | 41 | In this example, `subset` contains the elements from index 1 (inclusive) to index 4 (exclusive). 42 | 43 | ## Modifying Lists 44 | 45 | Lists are mutable, which means you can change their contents after creation. You can modify individual elements in a list by assigning a new value to their index: 46 | 47 | ```python 48 | my_list = [1, 2, 3] 49 | my_list[0] = 0 50 | print(my_list) # prints [0, 2, 3] 51 | ``` 52 | 53 | You can also add elements to the end of a list using the `append()` method: 54 | 55 | ```python 56 | my_list = [1, 2, 3] 57 | my_list.append(4) 58 | print(my_list) # prints [1, 2, 3, 4] 59 | ``` 60 | 61 | And you can remove elements from a list using the `remove()` method: 62 | 63 | ```python 64 | my_list = [1, 2, 3] 65 | my_list.remove(2) 66 | print(my_list) # prints [1, 3] 67 | ``` 68 | 69 | ## 2d lists 70 | In Python, a two-dimensional list (often referred to as a 2D list) is a list of lists. This means that each element in the outer list is itself a list containing one or more elements. 2D lists are commonly used to represent grids, matrices, or tables of data. 71 | 72 | ## Creating a 2D List 73 | 74 | To create a 2D list in Python, you can create a list of lists, where each inner list represents a row in the 2D list. For example: 75 | 76 | ```python 77 | my_2d_list = [ 78 | [1, 2, 3], 79 | [4, 5, 6], 80 | [7, 8, 9] 81 | ] 82 | ``` 83 | 84 | In this example, `my_2d_list` is a 3x3 grid of integers. 85 | 86 | ## Conclusion 87 | 88 | Lists are a versatile and powerful data structure in Python. They can be used to store and manipulate large amounts of data efficiently. By understanding how to create, access, slice, and modify lists, you can become a more effective Python programmer. -------------------------------------------------------------------------------- /Chapter 1 Introduction to Python/Lessons/built-InFunctions&Methods.md: -------------------------------------------------------------------------------- 1 | Built-in functions and methods are both pre-defined functionalities in Python that can be used to perform certain operations. However, they differ in their syntax and usage. 2 | 3 | Built-in functions are functions that are included in Python's standard library and can be called directly without importing any external modules. Built-in functions have a specific name and syntax that must be followed in order to use them. For example, the `len()` function is a built-in function that returns the length of a sequence. To use it, you simply call the function and pass the sequence as an argument: 4 | 5 | ```python 6 | s = "hello" 7 | print(len(s)) # output: 5 8 | ``` 9 | 10 | Built-in methods, on the other hand, are methods that are associated with specific data types (e.g. strings, lists, etc.) and can be called on instances of those data types. Built-in methods have a specific syntax that must be followed in order to use them. For example, the `split()` method is a built-in method that can be called on a string to split it into a list of substrings. To use it, you call the method on the string instance and pass the delimiter as an argument: 11 | 12 | ```python 13 | s = "hello,world" 14 | words = s.split(",") 15 | print(words) # output: ['hello', 'world'] 16 | ``` 17 | 18 | The main difference between built-in functions and built-in methods is that built-in functions can operate on any data type or object, whereas built-in methods only apply to specific data types or objects. Another difference is that built-in methods are called on instances of objects, whereas built-in functions are called directly. 19 | 20 | In general, built-in methods are more specific and tailored to the data type they operate on, whereas built-in functions are more generic and can be used with a wider range of data types and objects. 21 | 22 | Both built-in functions and methods are useful in different situations, and it's important to know when to use each one. 23 | 24 | Python provides a large number of built-in functions and methods. Here are some examples: 25 | 26 | ## Built-in Functions: 27 | - print(): This function is used to display output to the console. 28 | - input(): This function is used to get input from the user. 29 | - len(): This function is used to get the length of a sequence (e.g. a string, list, or tuple). 30 | - type(): This function is used to get the data type of a variable. 31 | ## Built-in Methods: 32 | - append(): This method is used to add an element to the end of a list. 33 | - split(): This method is used to split a string into a list of substrings based on a specified delimiter. 34 | - join(): This method is used to join a list of strings into a single string, with a specified delimiter. 35 | - upper(): This method is used to convert a string to uppercase. 36 | - sort(): This method is used to sort a list in ascending order. 37 | 38 | Here are some examples of using built-in functions and methods: 39 | 40 | # using built-in functions 41 | ```python 42 | s = input("Enter the words: ") 43 | 44 | print(len(s)) # output: 13 45 | 46 | print(type(s)) # output: 47 | ``` 48 | 49 | # using built-in methods 50 | ```python 51 | fruits = ["apple", "banana", "cherry"] 52 | fruits.append("orange") 53 | print(fruits) # output: ['apple', 'banana', 'cherry', 'orange'] 54 | 55 | s = "apple,banana,cherry" 56 | fruits = s.split(",") 57 | print(fruits) # output: ['apple', 'banana', 'cherry'] 58 | 59 | s = "-".join(fruits) 60 | print(s) # output: 'apple-banana-cherry' 61 | 62 | s = "hello, world!" 63 | print(s.upper()) # output: 'HELLO, WORLD!' 64 | 65 | numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] 66 | numbers.sort() 67 | print(numbers) # output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9] 68 | ``` -------------------------------------------------------------------------------- /Chapter 2 Contorol Flow/Lessons/ConditionalStatements(if&else).md: -------------------------------------------------------------------------------- 1 | # Conditional Statements (if/elif/else) 2 | 3 | In Python, conditional statements are used to make decisions based on certain conditions. The most common type of conditional statement is the `if/elif/else` statement. 4 | 5 | ## The `if` Statement 6 | 7 | The `if` statement is used to check if a condition is true. If the condition is true, the code inside the `if` block is executed. For example: 8 | 9 | ```python 10 | x = 10 11 | 12 | if x > 5: 13 | print("x is greater than 5") 14 | ``` 15 | 16 | In this example, we're checking if `x` is greater than 5. If the condition is true, the code inside the `if` block is executed, which prints "x is greater than 5". 17 | 18 | ## The `elif` Statement 19 | 20 | The `elif` statement is used to add additional conditions to check if the first condition is false. If the first condition is false and the `elif` condition is true, the code inside the `elif` block is executed. For example: 21 | 22 | ```python 23 | x = 10 24 | 25 | if x > 15: 26 | print("x is greater than 15") 27 | elif x > 10: 28 | print("x is greater than 10 but less than or equal to 15") 29 | ``` 30 | 31 | In this example, we're checking if `x` is greater than 15 or greater than 10 but less than or equal to 15. If `x` is greater than 15, the first condition is true and the code inside the `if` block is executed. If `x` is not greater than 15 but is greater than 10, the second condition is true and the code inside the `elif` block is executed. 32 | 33 | ## The `else` Statement 34 | 35 | The `else` statement is used to provide code to execute if all the previous conditions are false. For example: 36 | 37 | ```python 38 | x = 5 39 | 40 | if x > 10: 41 | print("x is greater than 10") 42 | elif x > 5: 43 | print("x is greater than 5 but less than or equal to 10") 44 | else: 45 | print("x is less than or equal to 5") 46 | ``` 47 | 48 | In this example, we're checking if `x` is greater than 10, greater than 5 but less than or equal to 10, or less than or equal to 5. If `x` is greater than 10, the first condition is true and the code inside the `if` block is executed. If `x` is not greater than 10 but is greater than 5, the second condition is true and the code inside the `elif` block is executed. If both conditions are false, the code inside the `else` block is executed. 49 | 50 | ## Example 51 | 52 | For example, let's say we want to write a program that checks if a number is even or odd. We can use an `if/else` statement to do this: 53 | 54 | ```python 55 | number = 10 56 | 57 | if number % 2 == 0: 58 | print("The number is even") 59 | else: 60 | print("The number is odd") 61 | ``` 62 | 63 | In this example, we're checking if `number` is divisible by 2 with no remainder. If the condition is true, the code inside the `if` block is executed, which prints "The number is even". If the condition is false, the code inside the `else` block is executed, which prints "The number is odd". 64 | 65 | The `if` statement is followed by a condition. If the condition is true, the code inside the `if` block is executed. If the condition is false, the code inside the `else` block is executed. 66 | 67 | You can also add additional conditions with the `elif` keyword. For example: 68 | 69 | ```python 70 | number = 10 71 | 72 | if number < 0: 73 | print("The number is negative") 74 | elif number == 0: 75 | print("The number is zero") 76 | else: 77 | print("The number is positive") 78 | ``` 79 | 80 | In this example, we're checking if `number` is negative, zero, or positive. If `number` is less than 0, the first condition is true and the code inside the `if` block is executed. If `number` is equal to 0, the second condition is true and the code inside the `elif` block is executed. If neither condition is true, the code inside the `else` block is executed. -------------------------------------------------------------------------------- /Chapter 4 Functions/main.py: -------------------------------------------------------------------------------- 1 | # def greeting(): 2 | # print("Hello, world") 3 | 4 | # greeting() 5 | 6 | # def greeting(name): 7 | # print(f'Hello {name}!') 8 | 9 | # greeting("Omar","oksdjdf") 10 | 11 | # def add(a,b): 12 | # return a+b 13 | # result = add(3,5) 14 | # print(result) 15 | # 1,3,4,677, = 84 total 16 | 17 | # def sum_numbers(*number): 18 | # total = 0; 19 | # for num in number: 20 | # total += num 21 | # return total 22 | # result = sum_numbers(10,20,40,50,60,70,80) 23 | # print(result) 24 | 25 | 26 | # def my_function(*number): 27 | # for num in number: 28 | # print(num) 29 | 30 | # my_function(1,2,3,4,5,6,7,8) 31 | 32 | 33 | # def getNames(**kwargs): 34 | # for key, value in kwargs.items(): 35 | # print(f'{key}: {value}') 36 | 37 | 38 | # getNames(name="Omar", age= 23, city ="Mogadishu", email="Omar@gmail.com" ) 39 | 40 | 41 | 42 | 43 | # global_variable = 10; 44 | 45 | # def my_function(): 46 | # local_variable =20 47 | # print(global_variable) 48 | # print(local_variable) 49 | 50 | # my_function() 51 | 52 | # print(global_variable) 53 | 54 | 55 | 56 | # def find_maximum(*numbers): 57 | # if len(numbers) == 0: 58 | # return "No numbers provided." 59 | # maximum = numbers[0] 60 | # for num in numbers: 61 | # if num > maximum: 62 | # maximum = num 63 | # return maximum 64 | 65 | # number_List = [10,100,200,1000,10000] 66 | # maximum_number = find_maximum(*number_List) 67 | # print(f'The maximum Number is {maximum_number}') 68 | 69 | 70 | # def check_password_length(password , min_length): 71 | # if len(password) >= min_length: 72 | # return True 73 | # else: 74 | # return False 75 | 76 | # password = input("Enter Your Password: ") 77 | # minimum_length = 8; 78 | # if check_password_length(password ,minimum_length): 79 | # print("Password meets the minimum length requirement") 80 | # else: 81 | # print("Password does not meets the minimum length requirement") 82 | 83 | 84 | 85 | # def age_teller(): 86 | # current_year = 2023 87 | # birth_year = int(input('Enter Your Birth Year:')) 88 | # age = current_year - birth_year 89 | 90 | # if age < 0: 91 | # print("Invalid birth Year. Please try again") 92 | # elif age > 150: 93 | # print(f"You seem to be too old to use this system. and Your age {age}") 94 | # else: 95 | # print(f'You are {age} years old.') 96 | 97 | # age_teller() 98 | 99 | # def calculate_total_grade(grades): 100 | # total = sum(grades) 101 | # return total 102 | # grades = [100,90,89,88,90,78] 103 | # total_grades = calculate_total_grade(grades) 104 | # print(f'Total Grades: {total_grades}') 105 | 106 | 107 | 108 | balance = 0.0 109 | def deposit(amount): 110 | global balance 111 | balance += amount 112 | print(f'Deposit of {amount} successful. Current Balance: {balance}') 113 | 114 | def withdraw(amount): 115 | global balance 116 | if balance >= amount: 117 | balance -= amount 118 | print(f'Withdrawal of {amount} successful. Remaining Balance: {balance}') 119 | else: 120 | print('Insufficient funds!. Withdraw Unsuccessful') 121 | 122 | def get_balance(): 123 | return balance 124 | 125 | def perform_payment(): 126 | deposit(400) 127 | withdraw(50) 128 | withdraw(70) 129 | withdraw(280) 130 | withdraw(100) 131 | deposit(4000) 132 | current_balance = get_balance() 133 | print(f'Current Balance: {current_balance}') 134 | 135 | perform_payment() 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | -------------------------------------------------------------------------------- /Chapter 2 Contorol Flow/Lessons/ForLoops.md: -------------------------------------------------------------------------------- 1 | # For loops 2 | In Python, the for loop is used to iterate over a sequence (such as a list, tuple, or string) and perform a block of code for each item in the sequence. 3 | 4 | ## Syntax 5 | 6 | The basic syntax of a `for` loop in Python is: 7 | 8 | ```python 9 | for item in sequence: 10 | # code to be executed for each item 11 | ``` 12 | 13 | Here, `item` is a variable that is used to store the value of the current item in the sequence, and `sequence` is the sequence that is being iterated over. 14 | 15 | ## Iterating over a sequence 16 | 17 | One of the most common uses of a `for` loop in Python is to iterate over a sequence (such as a list, tuple, or string) and perform a block of code for each item in the sequence. 18 | 19 | For example, let's say we have a list of numbers and we want to print each number: 20 | 21 | ```python 22 | numbers = [1, 2, 3, 4, 5] 23 | for number in numbers: 24 | print(number) 25 | ``` 26 | 27 | Output: 28 | ``` 29 | 1 30 | 2 31 | 3 32 | 4 33 | 5 34 | ``` 35 | 36 | In this example, the `for` loop iterates over the `numbers` list and assigns each item to the `number` variable. The `print()` function is then used to print each number. 37 | 38 | We can also use the `range()` function to generate a sequence of numbers and iterate over them with a `for` loop. For example, let's print the numbers from 0 to 4: 39 | 40 | ```python 41 | for i in range(5): 42 | print(i) 43 | ``` 44 | 45 | Output: 46 | ``` 47 | 0 48 | 1 49 | 2 50 | 3 51 | 4 52 | ``` 53 | 54 | In this example, the `range()` function generates a sequence of numbers from 0 to 4, and the `for` loop iterates over each number and prints it. 55 | 56 | We can also iterate over a string and perform a block of code for each character in the string. For example, let's print each character in the string "Hello, world!": 57 | 58 | ```python 59 | string = "Hello, world!" 60 | for character in string: 61 | print(character) 62 | ``` 63 | 64 | Output: 65 | ``` 66 | H 67 | e 68 | l 69 | l 70 | o 71 | , 72 | 73 | w 74 | o 75 | r 76 | l 77 | d 78 | ! 79 | ``` 80 | 81 | In this example, the `for` loop iterates over the `string` and assigns each character to the `character` variable. The `print()` function is then used to print each character. 82 | 83 | ## Nested `for` loops 84 | 85 | We can use nested `for` loops to iterate over multiple sequences. For example, let's print all possible combinations of two colors: 86 | 87 | ```python 88 | colors1 = ["red", "green", "blue"] 89 | colors2 = ["yellow", "orange", "purple"] 90 | for color1 in colors1: 91 | for color2 in colors2: 92 | print(color1, color2) 93 | ``` 94 | 95 | Output: 96 | ``` 97 | red yellow 98 | red orange 99 | red purple 100 | green yellow 101 | green orange 102 | green purple 103 | blue yellow 104 | blue orange 105 | blue purple 106 | ``` 107 | 108 | In this example, the outer `for` loop iterates over the `colors1` list and assigns each color to the `color1` variable. The inner `for` loop iterates over the `colors2` list and assigns each color to the `color2` variable. The `print()` function is then used to print each combination of colors. 109 | 110 | ## Modifying the sequence during iteration 111 | 112 | Sometimes we may want to modify the sequence we are iterating over during the `for` loop. However, we need to be careful when doing this, as it can lead to unexpected behavior. 113 | 114 | For example, let's say we want to remove all the vowels from a list of words: 115 | 116 | ```python 117 | words = ["apple", "banana", "cherry"] 118 | for word in words: 119 | for letter in word: 120 | if letter in "aeiou": 121 | word = word.replace(letter, "") 122 | print(word) 123 | ``` 124 | 125 | Output: 126 | ``` 127 | ppl 128 | bnn 129 | chrry 130 | ``` 131 | 132 | In this example, the outer `for` loop iterates over the `words` list and assigns each word to the `word` variable. The inner `for` loop iterates over each letter in the word, and if the letter is a vowel, it is removed from the word using the `replace()` method. The `print()` function is then used to print each modified word. 133 | 134 | ## Conclusion 135 | 136 | In Python, `for` loops are used to iterate over a sequence and perform a block of code for each item in the sequence. We can also use nested `for` loops to iterate over multiple sequences. We need to be careful when modifying the sequence during iteration, as it can lead to unexpected behavior. -------------------------------------------------------------------------------- /Chapter 4 Functions/chapter4.md: -------------------------------------------------------------------------------- 1 | # Python Functions 2 | 3 | Functions in Python allow you to encapsulate reusable blocks of code and execute them whenever needed. They make your code more modular and organized. 4 | 5 | ## Function Definition 6 | 7 | To define a function in Python, you use the def keyword followed by the function name and parentheses. Here's an example of a function definition that prints "Hello, world!" when called: 8 | 9 | ```python 10 | def greet(): 11 | print("Hello, world!") 12 | ``` 13 | 14 | 15 | ## Function Invocation 16 | 17 | To call or invoke a function, you simply use its name followed by parentheses. Here's an example of calling the greet function defined above: 18 | 19 | ```python 20 | greet() 21 | ``` 22 | 23 | This will ```print "Hello, world!```. 24 | 25 | ## Function Parameters 26 | 27 | Functions can accept parameters, allowing you to pass values into the function for it to work with. Here's an example: 28 | 29 | ```python 30 | def greet(name): 31 | print("Hello, " + name + "!") 32 | 33 | greet("Omar") 34 | ``` 35 | 36 | In this example, the greet function takes a parameter called name. When calling the function, we provide the value "Alice" as an argument. 37 | 38 | ## Return Values 39 | 40 | Functions can also return values using the return statement. Here's an example: 41 | 42 | ```python 43 | def add(a, b): 44 | return a + b 45 | 46 | result = add(3, 5) 47 | print(result) 48 | ``` 49 | 50 | In this example, the add function takes two parameters, a and b, and returns their sum using the return statement. 51 | 52 | 53 | 54 | # *args and **kwargs in Python 55 | 56 | In Python, *args and **kwargs are used to handle variable-length arguments in function definitions. 57 | 58 | ## *args (Positional Arguments) 59 | 60 | The *args syntax allows a function to accept a variable number of positional arguments. It collects all extra positional arguments passed to the function as a tuple. 61 | 62 | Example: 63 | ```python 64 | def sum_numbers(*args): 65 | total = 0 66 | for num in args: 67 | total += num 68 | return total 69 | 70 | result = sum_numbers(1, 2, 3, 4, 5) 71 | print(result) # Output: 15 72 | 73 | ``` 74 | ## **kwargs (Keyword Arguments) 75 | 76 | The **kwargs syntax allows a function to accept a variable number of keyword arguments. It collects all extra keyword arguments passed to the function as a dictionary. 77 | 78 | ### Example: 79 | ```python 80 | def print_info(**kwargs): 81 | for key, value in kwargs.items(): 82 | print(key + ": " + str(value)) 83 | 84 | print_info(name="Omar", age=25, city="Mogadishu") 85 | ``` 86 | 87 | You can use *args and **kwargs together in a function definition to handle both positional and keyword arguments. 88 | 89 | ```python 90 | def example_function(*args, **kwargs): 91 | # Use args and kwargs as needed 92 | pass 93 | ``` 94 | 95 | By using *args and **kwargs, you can create functions that accept a flexible number of arguments and provide more dynamic behavior. 96 | 97 | Remember to place the parameter definitions in the following order: required parameters, *args, **kwargs. 98 | 99 | 100 | 101 | # Function Scope in Python 102 | 103 | - Variables defined outside functions have global scope. 104 | - Variables defined inside functions have local scope. 105 | - Local variables are accessible only within the function. 106 | - Global variables can be accessed from anywhere in the program. 107 | - Local variables can shadow global variables with the same name. 108 | - Use the global keyword to modify global variables within a function. 109 | 110 | Example: 111 | ```python 112 | global_var = 10 113 | 114 | def my_function(): 115 | local_var = 20 116 | print(global_var) 117 | print(local_var) 118 | 119 | my_function() # Output: 10, 20 120 | 121 | ``` 122 | 123 | 124 | 125 | Maximum Numbers Finding Program: 126 | 127 | ```python 128 | def find_maximum(*numbers): 129 | if len(numbers) == 0: 130 | return None 131 | 132 | maximum = numbers[0] 133 | for num in numbers: 134 | if num > maximum: 135 | maximum = num 136 | 137 | return maximum 138 | 139 | numbers_list = [15, 7, 42, 23, 10] 140 | maximum_number = find_maximum(*numbers_list) 141 | print("The maximum number is:", maximum_number) 142 | ``` 143 | 144 | 145 | 146 | # Example Password Length: 147 | 148 | ``` python 149 | def check_password_length(password, min_length): 150 | if len(password) >= min_length: 151 | return True 152 | else: 153 | return False 154 | 155 | password = input("Enter your password: ") 156 | minimum_length = 8 157 | 158 | if check_password_length(password, minimum_length): 159 | print("Password meets the minimum length requirement.") 160 | else: 161 | print("Password does not meet the minimum length requirement.") 162 | 163 | ``` 164 | 165 | # Example get Age: 166 | 167 | ```python 168 | def age_teller(): 169 | current_year = 2023 170 | birth_year = int(input("Enter your birth year: ")) 171 | age = current_year - birth_year 172 | 173 | if age < 0: 174 | print("Invalid birth year. Please try again.") 175 | elif age > 150: 176 | print("You seem to be too old to use this system.") 177 | else: 178 | print(f"You are {age} years old.") 179 | 180 | # Example usage 181 | age_teller() 182 | 183 | ``` 184 | 185 | # Example Calculate grade. 186 | 187 | ``` python 188 | 189 | def calculate_total_grade(grades): 190 | total = sum(grades) 191 | return total 192 | 193 | # Example usage 194 | grades = [85, 90, 78, 92, 88] 195 | total_grade = calculate_total_grade(grades) 196 | print(f"Total grade: {total_grade}") 197 | 198 | ``` 199 | 200 | 201 | # Example Payment System. 202 | 203 | ``` python 204 | balance = 0.0 205 | 206 | def deposit(amount): 207 | global balance 208 | balance += amount 209 | print(f"Deposit of {amount} successful. Current balance: {balance}") 210 | 211 | def withdraw(amount): 212 | global balance 213 | if balance >= amount: 214 | balance -= amount 215 | print(f"Withdrawal of {amount} successful. Current balance: {balance}") 216 | else: 217 | print("Insufficient funds. Withdrawal unsuccessful.") 218 | 219 | def get_balance(): 220 | return balance 221 | 222 | 223 | # Example usage 224 | def perform_payment(): 225 | deposit(100.0) # Deposit of 100.0 successful. Current balance: 100.0 226 | withdraw(50.0) # Withdrawal of 50.0 successful. Current balance: 50.0 227 | withdraw(75.0) # Insufficient funds. Withdrawal unsuccessful. 228 | current_balance = get_balance() 229 | print(f"Current balance: {current_balance}") # Current balance: 50.0 230 | 231 | 232 | perform_payment() 233 | 234 | ``` 235 | 236 | 237 | --------------------------------------------------------------------------------