├── 1. Python Introduction └── OurFirstPythonProgram.py ├── 2. Python Basics ├── 1-ExerciseOperatorPrecedence.py ├── 10-ExerciseCommonListPaterns.py ├── 11-ExerciseDictionaryMethods.py ├── 12-ExerciseSets.py ├── 2-ExerciseAugmentedAssignmentOperator.py ├── 3-ExerciseFormattedStrings.py ├── 4-ExerciseStringIndexes.py ├── 5-ExerciseTypeConversion.py ├── 6-ExercisePasswordChecker.py ├── 7-ExerciseListSlicing.py ├── 8-ExerciseMatrix.py ├── 9-ExerciseListMethods.py ├── Dictionaries.py ├── Int&Float.py ├── Lists.py ├── Sets.py ├── String.py └── Tuples.py ├── 3. Python Basics II ├── 1-ExerciseLogicalOperators.py ├── 2-ExerciseTrickyCounter.py ├── 3-ExerciseOurFirstGUI.py ├── 4-ExerciseFindDuplicates.py ├── 5-ExerciseTesla.py ├── 6-ExerciseFunctions.py ├── ArgsAndKwargs.py ├── BreakContinuePass.py ├── CleanCode.py ├── ConditionalLogic.py ├── Docstrings.py ├── Enumerate().py ├── ForLoops.py ├── Functions.py ├── GlobalKeyword.py ├── IsVs==.py ├── Iterables.py ├── NonLocalKeyword.py ├── ParametersAndArguments.py ├── Range().py ├── Return.py ├── ScopeRules.py ├── TernaryOperator.py ├── Walrus.py └── WhileLoops.py ├── 4. Advanced Python ├── 1-ExerciseCatsEverywhere.py ├── 2-ExercisePetsEverywhere.py ├── 3-ExerciseExtendingList.py ├── 4-ExerciseMap_filter_zip_reduce.py ├── 5-ExerciseLambda.py ├── 6-ExerciseComprehensions.py ├── 7-ExerciseDecorators.py ├── 8-ExerciseGenerators.py ├── AttributesAndMethods.py ├── ClassmethodAndStaticmethod.py ├── CreatingOurOwnObjects.py ├── DunderMethods.py ├── Encapsulation.py ├── Generators.py ├── Inheritance.py ├── Init.py ├── MroMethodResolutionOrder.py ├── MultipleInheritance.py ├── OOP.py ├── ObjectIntrospection.py ├── Polymorphism.py ├── PrivateVsPublicVariables.py ├── UndertheHoodGenerators.py └── super().py ├── 5. Modules in Python └── GuessingGame.py ├── 6. Testing in Python ├── GuessingGame │ ├── exerciseMain.py │ ├── main.py │ └── test.py ├── main.py └── test.py ├── 7. Scripting with Python ├── 1-ExerciseEmail.py ├── 2-ExercisePasswordChecker.py └── 3-ExerciseTweet.py └── README.md /1. Python Introduction/OurFirstPythonProgram.py: -------------------------------------------------------------------------------- 1 | name = input("what is your name?\n") 2 | print("Hello " + name) 3 | -------------------------------------------------------------------------------- /2. Python Basics/1-ExerciseOperatorPrecedence.py: -------------------------------------------------------------------------------- 1 | # Guess the output of each answer before you click RUN 2 | # Try to write down your answer before and see how you do... keep it mind I made it a little tricky for you :) 3 | 4 | print((5 + 4) * 10 / 2) 5 | 6 | print(((5 + 4) * 10) / 2) 7 | 8 | print((5 + 4) * (10 / 2)) 9 | 10 | print(5 + (4 * 10) / 2) 11 | 12 | print(5 + 4 * 10 // 2) 13 | -------------------------------------------------------------------------------- /2. Python Basics/10-ExerciseCommonListPaterns.py: -------------------------------------------------------------------------------- 1 | #fix this code so that it prints a sorted list of all of our friends (alphabetical). Scroll to see answer 2 | friends = ['Simon', 'Patty', 'Joy', 'Carrie', 'Amira', 'Chu'] 3 | 4 | new_friend = ['Stanley'] 5 | 6 | print(friends.sort() + new_friend) 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | # Solution: (keep in mind there are multiple ways to do this, so your answer may vary. As long as it works that's all that matters!) 53 | # friends.extend(new_friend) 54 | # print(sorted(friends)) 55 | 56 | 57 | -------------------------------------------------------------------------------- /2. Python Basics/11-ExerciseDictionaryMethods.py: -------------------------------------------------------------------------------- 1 | # Exercise Dictionary Methods 2 | # Scroll to see answers. 3 | 4 | # 1 Create a user profile for your new game. 5 | # This user profile will be stored in a dictionary with keys: 'age', 'username', 'weapons', 'is_active' and 'clan' 6 | 7 | # 2 iterate and print all the keys in the above user. 8 | 9 | # 3 Add a new weapon to your user 10 | 11 | # 4 Add a new key to include 'is_banned'. Set it to false 12 | 13 | # 5 Ban the user by setting the previous key to True 14 | 15 | # 6 create a new user2 my copying the previous user and update the age value and username value. 16 | 17 | 18 | #ANSWERS BELOW: 19 | 20 | # 1 Create a user profile for your new game. 21 | # This user profile will be stored in a dictionary with keys: 'age', 'username', 'weapons', 'is_active' and 'clan' 22 | user_profile = { 23 | 'age': 0, 24 | 'username': ' ', 25 | 'weapons': None, 26 | 'is_active': False, 27 | 'clan': None 28 | } 29 | 30 | # 2 iterate and print all the keys in the above user. 31 | print(user_profile.keys()) 32 | 33 | # 3 Add a new weapon to your user 34 | user_profile['weapons'] = 'Katana' 35 | 36 | # 4 Add a new key to include 'is_banned'. Set it to false 37 | user_profile.update({'is_banned': False}) 38 | 39 | # 5 Ban the user by setting the previous key to True 40 | user_profile['is_banned'] = True 41 | 42 | # 6 create a new user2 my copying the previous user and update the age value and username value. 43 | user2 = user_profile.copy() 44 | user2.update({'age': 50, 'username': 'User2'}) 45 | print(user_profile) 46 | print(user2) 47 | -------------------------------------------------------------------------------- /2. Python Basics/12-ExerciseSets.py: -------------------------------------------------------------------------------- 1 | #Scroll to bottom to see solution 2 | # You are working for the school Principal. We have a database of school students: 3 | school = {'Bobby','Tammy','Jammy','Sally','Danny'} 4 | 5 | #during class, the teachers take attendance and compile it into a list. 6 | attendance_list = ['Jammy', 'Bobby', 'Danny', 'Sally'] 7 | 8 | #using what you learned about sets, create a piece of code that the school principal can use to immediately find out who missed class so they can call the parents. (Imagine if the list had 1000s of students. The principal can use the lists generated by the teachers + the school database to use python and make his/her job easier): Find the students that miss class! 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | #Solution: Notice how we don't have to convert the attendance_list to a set...it does it for you. 53 | #print(school.difference(attendance_list)) 54 | 55 | 56 | -------------------------------------------------------------------------------- /2. Python Basics/2-ExerciseAugmentedAssignmentOperator.py: -------------------------------------------------------------------------------- 1 | # Exercise Augmented Assignment Operator 2 | # Guess what happens here before you click RUN! 3 | counter = 0 4 | 5 | counter += 1 6 | counter += 1 7 | counter += 1 8 | counter += 1 9 | counter -= 1 10 | counter *= 2 11 | 12 | print(counter) #what will this print? 13 | -------------------------------------------------------------------------------- /2. Python Basics/3-ExerciseFormattedStrings.py: -------------------------------------------------------------------------------- 1 | # 1 What would be the output of the below 4 print statements? 2 | #Try to answer these before you click RUN! 3 | 4 | print("Hello {}, your balance is {}.".format("Cindy", 50)) 5 | 6 | print("Hello {0}, your balance is {1}.".format("Cindy", 50)) 7 | 8 | print("Hello {name}, your balance is {amount}.".format(name="Cindy", amount=50)) 9 | 10 | print("Hello {0}, your balance is {amount}.".format("Cindy", amount=50)) 11 | 12 | # 2 How would you write this using f-string? (Scroll down for answer) 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | name = 'Cindy' 35 | amount = 50 36 | print(f"Hello {name}, your balance is {amount}.") 37 | 38 | 39 | -------------------------------------------------------------------------------- /2. Python Basics/4-ExerciseStringIndexes.py: -------------------------------------------------------------------------------- 1 | #Guess the output of each print statement before you click RUN! 2 | python = 'I am PYHTON' 3 | 4 | print(python[1:4]) 5 | print(python[1:]) 6 | print(python[:]) 7 | print(python[1:100]) 8 | print(python[-1]) 9 | print(python[-4]) 10 | print(python[:-3]) 11 | print(python[-3:]) 12 | print(python[::-1]) -------------------------------------------------------------------------------- /2. Python Basics/5-ExerciseTypeConversion.py: -------------------------------------------------------------------------------- 1 | # Exercise Type Conversion 2 | # Write a program which tells your age 3 | 4 | birth_year = input('What year were you born?\n') 5 | age = 2024 - int(birth_year) 6 | print(f'Your age is {age} years.') 7 | -------------------------------------------------------------------------------- /2. Python Basics/6-ExercisePasswordChecker.py: -------------------------------------------------------------------------------- 1 | # Exercise Password Checker 2 | 3 | username = input('Enter your username:\t') 4 | password = input('Enter you password:\t') 5 | 6 | secret_password = len(password) * '*' 7 | print(f'Hey {username}, your password {secret_password} is {len(password)} letters long.') 8 | -------------------------------------------------------------------------------- /2. Python Basics/7-ExerciseListSlicing.py: -------------------------------------------------------------------------------- 1 | #What is the output of this code? 2 | #Before you clikc RUN, guess the output of each print statement! 3 | new_list = ['a', 'b', 'c'] 4 | print(new_list[1]) 5 | print(new_list[-2]) 6 | print(new_list[1:3]) 7 | new_list[0] = 'z' 8 | print(new_list) 9 | 10 | my_list = [1,2,3] 11 | bonus = my_list + [5] 12 | my_list[0] = 'z' 13 | print(my_list) 14 | print(bonus) -------------------------------------------------------------------------------- /2. Python Basics/8-ExerciseMatrix.py: -------------------------------------------------------------------------------- 1 | # using this list: 2 | basket = ["Banana", ["Apples", ["Oranges"], "Blueberries"]]; 3 | # access "Oranges" and print it: 4 | # You will find the answer if you scroll down to the bottom, but attempt it yourself first! 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | # Solution: 41 | # basket[1][1][0] -------------------------------------------------------------------------------- /2. Python Basics/9-ExerciseListMethods.py: -------------------------------------------------------------------------------- 1 | # Exercise List Methods 2 | # SCROLL FOR ANSWERS! 3 | # using this list, 4 | basket = ["Banana", "Apples", "Oranges", "Blueberries"] 5 | 6 | # 1. Remove the Banana from the list 7 | 8 | # 2. Remove "Blueberries" from the list. 9 | 10 | # 3. Put "Kiwi" at the end of the list. 11 | 12 | # 4. Add "Apples" at the beginning of the list 13 | 14 | # 5. Count how many apples in the basket 15 | 16 | # 6. empty the basket 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | # 1. Remove the Banana from the list 28 | basket.remove('Banana') 29 | # 2. Remove "Blueberries" from the list. 30 | basket.remove('Blueberries') 31 | # 3. Put "Kiwi" at the end of the list. 32 | basket.append('Kiwi') 33 | # 4. Add "Apples" at the beginning of the list 34 | basket.insert(0, 'Apples') 35 | # 5. Count how many apples in the basket 36 | basket.count('Apples') 37 | # 6. empty the basket 38 | basket.clear() 39 | print(basket) 40 | -------------------------------------------------------------------------------- /2. Python Basics/Dictionaries.py: -------------------------------------------------------------------------------- 1 | # Dictionaries 2 | 3 | dictionary = { 4 | 'a': [1, 2, 3], 5 | 'b': 'Hello', 6 | 'c': True 7 | } 8 | 9 | print(dictionary['a'][1]) 10 | print(dictionary) 11 | print('\n') 12 | 13 | 14 | # Dictionary Methods 15 | 16 | user = { 17 | 'basket': [1, 2, 3], 18 | 'greet': 'Hello', 19 | 'age': 20 20 | } 21 | 22 | print(user.get('age', 55)) 23 | 24 | user2 = dict(name='JohnJohn') 25 | print(user2) 26 | 27 | print('basket' in user) 28 | print('size' in user) 29 | print('age' in user.keys()) 30 | print('Hello' in user.values()) 31 | print(user.items()) 32 | 33 | user2 = user.copy() 34 | user.clear() 35 | print(user) 36 | print(user2) 37 | print(user2.pop('age')) 38 | print(user2.popitem()) 39 | user2.update({'age': 55}) 40 | print(user2) 41 | print('\n') 42 | -------------------------------------------------------------------------------- /2. Python Basics/Int&Float.py: -------------------------------------------------------------------------------- 1 | # Integers and Floating point numbers 2 | # int & float 3 | 4 | print(2 + 4) 5 | print(2 - 4) 6 | print(2 * 4) 7 | print(2 / 4) 8 | print("\n") 9 | 10 | print(type(2 + 4)) 11 | print(type(2 - 4)) 12 | print(type(2 * 4)) 13 | print(type(2 / 4)) 14 | print(type(0)) 15 | print("\n") 16 | 17 | print(type(20 + 1.1)) 18 | print(type(9.9 + 1.1)) 19 | print(9.9 + 1.1) 20 | print("\n") 21 | 22 | print((2 ** 3)) # to the power of 23 | print(5 // 3) # integer division rounded down 24 | print(5 % 3) # modulo / remainder 25 | print("\n") 26 | 27 | # Maths functions 28 | # Round 29 | print(round(3.1)) 30 | print(round(3.9)) 31 | 32 | # Absolute values 33 | print(abs(-20)) 34 | print("\n") 35 | 36 | # Complex Numbers 37 | complex() 38 | 39 | # Binary numbers 40 | print(bin(5)) 41 | print(int("0b101", 2)) # ("number", base of number) 42 | print("\n") 43 | -------------------------------------------------------------------------------- /2. Python Basics/Lists.py: -------------------------------------------------------------------------------- 1 | # Lists 2 | 3 | li = [1, 2, 3, 4, 5] 4 | li2 = ['a', 'b', 'c'] 5 | li3 = [1, 2.5, 'a', True] 6 | amazon_cart = ['notebooks', 'sunglasses'] 7 | print(amazon_cart[0]) 8 | print('\n') 9 | 10 | 11 | # List Slicing 12 | # [Start : Stop : Step-Over] 13 | 14 | amazon_cart = ['notebooks', 'sunglasses', 'toys', 'grapes'] 15 | print(amazon_cart) 16 | print(amazon_cart[0:2]) 17 | print(amazon_cart[0::2]) 18 | print(amazon_cart[::-1]) 19 | 20 | amazon_cart[0] = 'laptop' 21 | print(amazon_cart) 22 | 23 | new_cart = amazon_cart[:] 24 | new_cart[0] = 'gum' 25 | print(new_cart) 26 | print(amazon_cart) 27 | 28 | new_cart1 = amazon_cart 29 | new_cart1[0] = 'gum' 30 | print(new_cart1) 31 | print(amazon_cart) 32 | print('\n') 33 | 34 | 35 | # Matrix 36 | 37 | matrix = [ 38 | [1, 0, 1], 39 | [0, 1, 0], 40 | [1, 0, 1] 41 | ] 42 | print(matrix) 43 | print(matrix[0][2]) 44 | print('\n') 45 | 46 | 47 | # List Methods 48 | 49 | basket = [1, 2, 3, 4, 5] 50 | 51 | # Adding 52 | new_list = basket.append(100) 53 | print(basket) 54 | print(new_list) 55 | basket.insert(4, 50) 56 | print(basket) 57 | basket.extend([10, 20, 30, 40]) 58 | print(basket) 59 | print('\n') 60 | 61 | # Removing 62 | basket.pop() 63 | print(basket) 64 | basket.pop(4) 65 | print(basket) 66 | basket.remove(100) 67 | print(basket) 68 | # basket.clear() 69 | # print(basket) 70 | print('\n') 71 | 72 | print(basket.index(5)) 73 | print(5 in basket) 74 | print(basket.count(4)) 75 | print('\n') 76 | 77 | basket.sort() 78 | print(basket) 79 | new_basket = basket.copy() 80 | new_basket.sort(reverse=True) 81 | print(new_basket) 82 | print(sorted(new_basket)) 83 | basket.reverse() 84 | print(basket) 85 | print('\n') 86 | 87 | 88 | # Common List Patterns 89 | 90 | print(basket[::-1]) 91 | print(range(1, 100)) 92 | print(list(range(101))) 93 | 94 | sentence = '! ' 95 | new_sentence = sentence.join(['Hi', 'my', 'name', 'is', 'JOJO']) 96 | print(new_sentence) 97 | print('\n') 98 | 99 | 100 | # List Unpacking 101 | 102 | a, b, c, *other, d = [1, 2, 3, 4, 5, 6, 7, 8, 9] 103 | print(a) 104 | print(b) 105 | print(c) 106 | print(other) 107 | print(d) 108 | -------------------------------------------------------------------------------- /2. Python Basics/Sets.py: -------------------------------------------------------------------------------- 1 | # Sets 2 | 3 | my_set = {1, 2, 3, 4, 5, 5} 4 | my_set.add(100) 5 | my_set.add(2) 6 | print(my_set) 7 | 8 | my_list = [1, 2, 3, 4, 4, 5, 5] 9 | print(set(my_list)) 10 | print(list(my_set)) 11 | 12 | new_set = my_set.copy() 13 | my_set.clear() 14 | print(my_set) 15 | print(new_set) 16 | print('\n') 17 | 18 | 19 | # Set Methods 20 | 21 | my_set = {1, 2, 3, 4, 5} 22 | your_set = {4, 5, 6, 7, 8, 9, 10} 23 | 24 | print(my_set.difference(your_set)) 25 | print(my_set.intersection(your_set)) 26 | print(my_set.isdisjoint(your_set)) 27 | print(my_set.issubset(your_set)) 28 | print(my_set.issuperset(your_set)) 29 | print(my_set.union(your_set)) 30 | my_set.difference_update(your_set) 31 | print(my_set) 32 | my_set.discard(5) 33 | print(my_set) 34 | 35 | -------------------------------------------------------------------------------- /2. Python Basics/String.py: -------------------------------------------------------------------------------- 1 | # Strings 2 | 3 | print(type('Hi Hello there!')) 4 | username = 'SuperCoder' 5 | password = "SuperSecret" 6 | long_string = ''' 7 | WOW 8 | o_o 9 | ___ 10 | ''' 11 | print(long_string) 12 | 13 | first_name = 'Nitesh' 14 | last_name = 'Kumar' 15 | full_name = first_name + ' ' + last_name 16 | print(full_name) 17 | print("\n") 18 | 19 | # String Concatenation 20 | 21 | print('hello' + ' Nitesh') 22 | print('hello ' + str(5)) 23 | print("\n") 24 | 25 | # Type Conversion 26 | 27 | print(type(int(str(100)))) 28 | 29 | a = str(100) 30 | b = int(a) 31 | c = type(b) 32 | print(c) 33 | print("\n") 34 | 35 | 36 | # Escape Sequences 37 | 38 | weather = "\t It\'s \"kind of\" sunny \n Hope you have a good day!" 39 | print(weather) 40 | print("\n") 41 | 42 | 43 | # Formatted Strings 44 | 45 | name = 'Nitesh' 46 | age = 27 47 | print('Hi' + name + '. You are' + str(age) + ' years olf.') 48 | print(f'Hi {name}. You are {age} years old.') 49 | 50 | # Python2 Formatted Strings 51 | print('Hi {}. Your are {} years old.'.format(name, age)) 52 | print('Hi {1}. You are {0} years olf.'.format(age, name)) 53 | print('Hi {new_name}. You are {age} years old.'.format(new_name='Sally', age=100)) 54 | print('\n') 55 | 56 | 57 | # String Indexes 58 | # String Slicing 59 | # [Start : Stop : Step-over] 60 | 61 | selfish = '01234567' 62 | # 01234567 63 | print((selfish[0])) 64 | print((selfish[7])) 65 | print((selfish[0:2])) 66 | print((selfish[0:7])) 67 | print((selfish[0:8])) 68 | print((selfish[0:8:2])) 69 | print((selfish[1:5])) 70 | print((selfish[::1])) 71 | print((selfish[-1])) 72 | print((selfish[-2])) 73 | print((selfish[::-1])) 74 | print((selfish[::-2])) 75 | print('\n') 76 | 77 | 78 | # Built-in Functions and Methods 79 | 80 | print(len('Helllooooo')) 81 | quote = 'to be or not to be' 82 | print(quote.upper()) 83 | print(quote.capitalize()) 84 | print(quote.find('be')) 85 | print(quote.replace('be', 'me')) 86 | print(quote) 87 | print('\n') 88 | -------------------------------------------------------------------------------- /2. Python Basics/Tuples.py: -------------------------------------------------------------------------------- 1 | # Tuples 2 | 3 | my_tuple = (1, 2, 3, 4, 5) 4 | print(my_tuple[1]) 5 | print(5 in my_tuple) 6 | print(my_tuple) 7 | 8 | x, y, z, *other = (1, 2, 3, 4, 5) 9 | print(x) 10 | print(z) 11 | 12 | print(my_tuple.count(5)) 13 | print(my_tuple.index(5)) 14 | -------------------------------------------------------------------------------- /3. Python Basics II/1-ExerciseLogicalOperators.py: -------------------------------------------------------------------------------- 1 | # Exercise Logical Operators 2 | 3 | is_magician = False 4 | is_expert = True 5 | 6 | # Check if magician and expert: "you are a master magician" 7 | if is_magician and is_expert: 8 | print("You are a master magician") 9 | 10 | # Check if magician but not expert: "at least you're getting there" 11 | if is_magician and not is_expert: 12 | print("At least you\'re getting there.") 13 | 14 | # Check if not a magician: "You need magic powers" 15 | if not is_magician: 16 | print("You need magic powers.") 17 | -------------------------------------------------------------------------------- /3. Python Basics II/2-ExerciseTrickyCounter.py: -------------------------------------------------------------------------------- 1 | # Exercise Tricky Counter 2 | # Write a program to find the sum of items in the list 3 | 4 | my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 5 | 6 | counter = 0 7 | for item in my_list: 8 | counter += item 9 | 10 | print(counter) 11 | -------------------------------------------------------------------------------- /3. Python Basics II/3-ExerciseOurFirstGUI.py: -------------------------------------------------------------------------------- 1 | #Exercise! 2 | #Display the image below to the right hand side where the 0 is going to be ' ', and the 1 is going to be '*'. This will reveal an image! 3 | picture = [ 4 | [0,0,0,1,0,0,0], 5 | [0,0,1,1,1,0,0], 6 | [0,1,1,1,1,1,0], 7 | [1,1,1,1,1,1,1], 8 | [0,0,0,1,0,0,0], 9 | [0,0,0,1,0,0,0] 10 | ] 11 | 12 | 13 | 14 | #Answer: 15 | for image in picture: 16 | for pixel in image: 17 | if (pixel): 18 | print('*', end ="") 19 | else: 20 | print(' ', end ="") 21 | print('') -------------------------------------------------------------------------------- /3. Python Basics II/4-ExerciseFindDuplicates.py: -------------------------------------------------------------------------------- 1 | # Exercise Find Duplicates 2 | # Check for duplicates in the list. 3 | # Print the characters which have duplicates in the list. 4 | 5 | some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n'] 6 | duplicates = [] 7 | 8 | for value in some_list: 9 | if some_list.count(value) > 1: 10 | if value not in duplicates: 11 | duplicates.append(value) 12 | 13 | print(duplicates) 14 | 15 | # for i in range(len(some_list)): 16 | # for j in range(i+1, len(some_list)): 17 | # if some_list[i] == some_list[j]: 18 | # duplicates.append(some_list[i]) 19 | # 20 | # print(duplicates) 21 | # 22 | # 23 | # 24 | # duplicates = set() 25 | # 26 | # list_set = set(some_list) 27 | # 28 | # for char in list_set: 29 | # count = 0 30 | # for item in some_list: 31 | # if item == char: 32 | # count += 1 33 | # if count > 1: 34 | # duplicates.add(char) 35 | # 36 | # print(duplicates) 37 | -------------------------------------------------------------------------------- /3. Python Basics II/5-ExerciseTesla.py: -------------------------------------------------------------------------------- 1 | 2 | #1. Wrap the above code in a function called checkDriverAge(). Whenever you call this function, you will get prompted for age. 3 | # Notice the benefit in having checkDriverAge() instead of copying and pasting the function everytime? 4 | def checkDriverAge(): 5 | age = input("What is your age?: ") 6 | if int(age) < 18: 7 | print("Sorry, you are too young to drive this car. Powering off") 8 | elif int(age) > 18: 9 | print("Powering On. Enjoy the ride!"); 10 | elif int(age) == 18: 11 | print("Congratulations on your first year of driving. Enjoy the ride!") 12 | checkDriverAge() 13 | 14 | #2 Instead of using the input(). Now, make the checkDriverAge() function accept an argument of age, so that if you enter: 15 | #checkDriverAge(92); 16 | #it returns "Powering On. Enjoy the ride!" 17 | #also make it so that the default age is set to 0 if no argument is given. 18 | def checkDriverAge(age=0): 19 | if int(age) < 18: 20 | print("Sorry, you are too yound to drive this car. Powering off") 21 | elif int(age) > 18: 22 | print("Powering On. Enjoy the ride!"); 23 | elif int(age) == 18: 24 | print("Congratulations on your first year of driving. Enjoy the ride!") 25 | checkDriverAge() -------------------------------------------------------------------------------- /3. Python Basics II/6-ExerciseFunctions.py: -------------------------------------------------------------------------------- 1 | # Exercise Functions 2 | # Highest Even: Write a function to find the highest even number from the list. 3 | 4 | 5 | def highest_even(li): 6 | evens = [] 7 | for item in li: 8 | if not item % 2 and item not in evens: 9 | evens.append(item) 10 | return max(evens) 11 | 12 | 13 | print(highest_even([10, 2, 3, 4, 8, 11])) 14 | -------------------------------------------------------------------------------- /3. Python Basics II/ArgsAndKwargs.py: -------------------------------------------------------------------------------- 1 | # *args and **kwargs 2 | 3 | 4 | def super_func(name, *args, i='hi', **kwargs): 5 | total = 0 6 | for item in kwargs.values(): 7 | total += item 8 | print(i, name) 9 | return sum(args) + total 10 | 11 | 12 | print(super_func('nitesh', 1, 2, 3, 4, 5, i='hello', num1=5, num2=10)) 13 | 14 | # Rule: params, *args, default parameters, **kwargs 15 | -------------------------------------------------------------------------------- /3. Python Basics II/BreakContinuePass.py: -------------------------------------------------------------------------------- 1 | # Break, Continue, Pass 2 | 3 | my_list = [1, 2, 3] 4 | i = 0 5 | while i < len(my_list): 6 | print(my_list[i]) 7 | i += 1 8 | continue 9 | print() 10 | 11 | i = 0 12 | while i < len(my_list): 13 | print(my_list[i]) 14 | i += 1 15 | break 16 | print() 17 | 18 | i = 0 19 | while i < len(my_list): 20 | i += 1 21 | pass 22 | 23 | print("No error") 24 | -------------------------------------------------------------------------------- /3. Python Basics II/CleanCode.py: -------------------------------------------------------------------------------- 1 | # Clean Code 2 | # Write a function to check if number is odd or not. 3 | 4 | 5 | def is_odd(num): 6 | return num % 2 == 1 7 | 8 | 9 | print(is_odd(5)) 10 | print(is_odd(10)) 11 | -------------------------------------------------------------------------------- /3. Python Basics II/ConditionalLogic.py: -------------------------------------------------------------------------------- 1 | # Conditional Logic 2 | 3 | is_old = True 4 | is_licenced = True 5 | 6 | if is_old: 7 | print('You are old enough to drive!') 8 | elif is_licenced: 9 | print('You can drive now!') 10 | else: 11 | print('You are not of age!') 12 | 13 | print('ok ok') 14 | print() 15 | 16 | # improved version 17 | if is_old and is_licenced: 18 | print('You are old enough to drive, and you have a licence!') 19 | else: 20 | print('You are not of age!') 21 | 22 | print('ok ok') 23 | -------------------------------------------------------------------------------- /3. Python Basics II/Docstrings.py: -------------------------------------------------------------------------------- 1 | # Docstrings 2 | 3 | def test(a): 4 | """ 5 | Info : This function tests and prints param a 6 | :param a: 7 | :return: 8 | """ 9 | 10 | print(a) 11 | 12 | 13 | test('!!!') 14 | 15 | help(test) 16 | print() 17 | print(test.__doc__) 18 | -------------------------------------------------------------------------------- /3. Python Basics II/Enumerate().py: -------------------------------------------------------------------------------- 1 | # Enumerate() 2 | 3 | for i, char in enumerate('Helllooo'): 4 | print(i, char) 5 | 6 | for i, char in enumerate([1, 2, 3]): 7 | print(i, char) 8 | 9 | for i, char in enumerate(range(100)): 10 | if char == 50: 11 | print(f"index of 50 is: {i}") 12 | -------------------------------------------------------------------------------- /3. Python Basics II/ForLoops.py: -------------------------------------------------------------------------------- 1 | # For Loops 2 | 3 | for item in 'Zero to Mastery': 4 | print(item, end=' ') 5 | print() 6 | 7 | for item in [1, 2, 3, 4, 5]: 8 | print(item, end=' ') 9 | print() 10 | 11 | for item in {1, 2, 3, 4, 5}: 12 | print(item, end=' ') 13 | print() 14 | 15 | for item in (1, 2, 3, 4, 5): 16 | print(item, end=' ') 17 | print(item) 18 | print() 19 | 20 | # Nested Loops 21 | for item in (1, 2, 3, 4, 5): 22 | for x in ['a', 'b', 'c']: 23 | print(item, x, end='\t') 24 | -------------------------------------------------------------------------------- /3. Python Basics II/Functions.py: -------------------------------------------------------------------------------- 1 | # Functions 2 | 3 | def say_hello(): 4 | print('Helllooooo!') 5 | 6 | 7 | say_hello() 8 | print() 9 | 10 | picture = [ 11 | [0, 0, 0, 1, 0, 0, 0], 12 | [0, 0, 1, 1, 1, 0, 0], 13 | [0, 1, 1, 1, 1, 1, 0], 14 | [1, 1, 1, 1, 1, 1, 1], 15 | [0, 0, 0, 1, 0, 0, 0], 16 | [0, 0, 0, 1, 0, 0, 0] 17 | ] 18 | 19 | 20 | def show_tree(): 21 | for array in picture: 22 | for item in array: 23 | if item: 24 | print('*', end='') 25 | else: 26 | print(' ', end='') 27 | print() 28 | 29 | 30 | show_tree() 31 | print() 32 | show_tree() 33 | print() 34 | show_tree() 35 | print() 36 | -------------------------------------------------------------------------------- /3. Python Basics II/GlobalKeyword.py: -------------------------------------------------------------------------------- 1 | # Global Keyword 2 | 3 | total = 0 4 | 5 | 6 | def count(): 7 | global total 8 | total += 1 9 | return total 10 | 11 | 12 | count() 13 | count() 14 | print(count()) 15 | -------------------------------------------------------------------------------- /3. Python Basics II/IsVs==.py: -------------------------------------------------------------------------------- 1 | # Is vs == 2 | 3 | print(True == 1) 4 | print('' == 1) 5 | print([] == 1) 6 | print(10 == 10.0) 7 | print([] == []) 8 | print() 9 | 10 | print(True == True) 11 | print('1' == 1) 12 | print([1, 2, 3] == [1, 2, 3]) 13 | print() 14 | 15 | print(True is 1) 16 | print('1' is 1) 17 | print([] is 1) 18 | print(10 is 10.0) 19 | print([1, 2, 3] is [1, 2, 3]) 20 | print() 21 | 22 | print(True is True) 23 | print('1' is '1') 24 | print([] is []) 25 | -------------------------------------------------------------------------------- /3. Python Basics II/Iterables.py: -------------------------------------------------------------------------------- 1 | # Iterables 2 | 3 | user = { 4 | 'name': 'Golem', 5 | 'age': 5006, 6 | 'can_swim': False 7 | } 8 | 9 | for item in user: 10 | print(item) 11 | 12 | for item in user.items(): 13 | print(item) 14 | 15 | for item in user.keys(): 16 | print(item) 17 | 18 | for item in user.values(): 19 | print(item) 20 | 21 | for key, value in user.items(): 22 | print(key, value) 23 | -------------------------------------------------------------------------------- /3. Python Basics II/NonLocalKeyword.py: -------------------------------------------------------------------------------- 1 | # Nonlocal Keyword 2 | 3 | 4 | def outer(): 5 | x = 'local' 6 | 7 | def inner(): 8 | nonlocal x 9 | x = 'nonlocal' 10 | print('inner:', x) 11 | 12 | inner() 13 | print('outer:', x) 14 | 15 | 16 | outer() 17 | -------------------------------------------------------------------------------- /3. Python Basics II/ParametersAndArguments.py: -------------------------------------------------------------------------------- 1 | # Parameters and Arguments 2 | 3 | # Parameters // Positional Parameters 4 | def say_hello(name, emoji): 5 | print(f'helllooooo {name} {emoji}') 6 | 7 | 8 | # Arguments // Positional Arguments 9 | say_hello('Nitesh', ':)') 10 | say_hello('Emily', ':p') 11 | say_hello('Dah', ':\'(') 12 | print() 13 | 14 | 15 | # Default Parameters 16 | def say_hello(name='Darth Vader', emoji='>:('): 17 | print(f'helllooooo {name} {emoji}') 18 | 19 | 20 | # Keyword Arguments 21 | say_hello(emoji=':)', name='Bibi') 22 | say_hello() 23 | say_hello('Timmy') 24 | -------------------------------------------------------------------------------- /3. Python Basics II/Range().py: -------------------------------------------------------------------------------- 1 | # Range() 2 | 3 | print(range(100)) 4 | print(range(0, 100)) 5 | 6 | for number in range(10): 7 | print(number, end=' ') 8 | print() 9 | 10 | for _ in range(10): 11 | print('Hi', end=' ') 12 | print() 13 | 14 | for number in range(0, 10, 2): 15 | print(number, end=' ') 16 | print() 17 | 18 | for number in range(0, 10, -1): 19 | print(number, end=' ') 20 | print() 21 | 22 | for number in range(10, 0, -1): 23 | print(number, end=' ') 24 | print() 25 | 26 | for number in range(10, 0): 27 | print(number, end=' ') 28 | print() 29 | 30 | for number in range(10, 0, -2): 31 | print(number, end=' ') 32 | print() 33 | 34 | for _ in range(2): 35 | print(list(range(10))) 36 | -------------------------------------------------------------------------------- /3. Python Basics II/Return.py: -------------------------------------------------------------------------------- 1 | # Return 2 | 3 | def sum1(num1, num2): 4 | return num1 + num2 5 | 6 | 7 | total = sum1(10, 5) 8 | print(sum1(10, total)) 9 | print() 10 | 11 | 12 | def sum2(num1, num2): 13 | def another_func(n1, n2): 14 | return n1 + n2 15 | return another_func(num1, num2) 16 | 17 | 18 | total = sum2(10, 20) 19 | print(total) 20 | -------------------------------------------------------------------------------- /3. Python Basics II/ScopeRules.py: -------------------------------------------------------------------------------- 1 | # Scope Rules 2 | 3 | a = 1 4 | 5 | 6 | def parent(): 7 | a = 10 8 | 9 | def confusion(): 10 | a = 5 11 | return a 12 | return confusion() 13 | 14 | 15 | print(a) 16 | print(parent()) 17 | print(sum) 18 | -------------------------------------------------------------------------------- /3. Python Basics II/TernaryOperator.py: -------------------------------------------------------------------------------- 1 | # Ternary Operator 2 | 3 | is_friend = True 4 | can_message = "message allowed" if is_friend else "not allowed to message" 5 | print(can_message) 6 | -------------------------------------------------------------------------------- /3. Python Basics II/Walrus.py: -------------------------------------------------------------------------------- 1 | a = 'helloooooooooo' 2 | 3 | if ((n := len(a)) > 10): 4 | print(f"too long {n} elements") 5 | 6 | while ((n := len(a)) > 1): 7 | print(n) 8 | a = a[:-1] 9 | 10 | print(a) 11 | -------------------------------------------------------------------------------- /3. Python Basics II/WhileLoops.py: -------------------------------------------------------------------------------- 1 | # While loops 2 | 3 | i = 0 4 | while i < 50: 5 | print(i, end='\t') 6 | i += 1 7 | else: 8 | print('\nDone with all the work.') 9 | print() 10 | 11 | my_list = [1, 2, 3] 12 | i = 0 13 | while i < len(my_list): 14 | print(my_list[i]) 15 | i += 1 16 | print() 17 | 18 | while True: 19 | response = input('Say Something: ') 20 | if response == 'bye': 21 | break 22 | -------------------------------------------------------------------------------- /4. Advanced Python/1-ExerciseCatsEverywhere.py: -------------------------------------------------------------------------------- 1 | # Exercise Cats Everywhere 2 | 3 | # Given the below class: 4 | 5 | class Cat: 6 | species = 'mammal' 7 | 8 | def __init__(self, name, age): 9 | self.name = name 10 | self.age = age 11 | #SCROLL FOR ANSWERS 12 | 13 | # 1 Instantiate the Cat object with 3 cats. 14 | 15 | 16 | # 2 Create a function that finds the oldest cat. 17 | 18 | 19 | 20 | # 3 Print out: "The oldest cat is x years old.". 21 | # x will be the oldest cat age by using the function in #2 22 | 23 | 24 | 25 | 26 | 27 | 28 | #Answers: 29 | # 1 Instantiate the Cat object with 3 cats. 30 | cat1 = Cat('cat1', 5) 31 | cat2 = Cat('Cat2', 7) 32 | cat3 = Cat('Cat3', 3) 33 | 34 | 35 | # 2 Create a function that finds the oldest cat. 36 | def oldest_cat(*args): 37 | return max(args) 38 | 39 | 40 | # 3 Print out: "The oldest cat is x years old.". 41 | # x will be the oldest cat age by using the function in #2 42 | print(f'Oldest Cat is {oldest_cat(cat1.age, cat2.age, cat3.age)} years old.') 43 | -------------------------------------------------------------------------------- /4. Advanced Python/2-ExercisePetsEverywhere.py: -------------------------------------------------------------------------------- 1 | # Exercise Pets Everywhere 2 | 3 | 4 | class Pets: 5 | animals = [] 6 | 7 | def __init__(self, animals): 8 | self.animals = animals 9 | 10 | def walk(self): 11 | for animal in self.animals: 12 | print(animal.walk()) 13 | 14 | 15 | class Cat: 16 | is_lazy = True 17 | 18 | def __init__(self, name, age): 19 | self.name = name 20 | self.age = age 21 | 22 | def walk(self): 23 | return f'{self.name} is just walking around' 24 | 25 | 26 | class Simon(Cat): 27 | def sing(self, sounds): 28 | return f'{sounds}' 29 | 30 | 31 | class Sally(Cat): 32 | def sing(self, sounds): 33 | return f'{sounds}' 34 | 35 | 36 | # 1 Add another Cat 37 | class Chilli(Cat): 38 | def sing(self, sounds): 39 | return f'{sounds}' 40 | 41 | 42 | # 2 Create a list of all the pets (create 3 cat instances from the above). 43 | my_cats = [Simon(Simon, 5), Sally(Sally, 7), Chilli(Chilli, 3)] 44 | 45 | # 3 Instantiate the Pet class with all your cats use variable my_pets. 46 | my_pets = Pets(my_cats) 47 | 48 | # 4 Output all the cats walking using the my_pets instance. 49 | my_pets.walk() 50 | -------------------------------------------------------------------------------- /4. Advanced Python/3-ExerciseExtendingList.py: -------------------------------------------------------------------------------- 1 | # Exercise Extending List 2 | 3 | class SuperList(list): 4 | 5 | def __len__(self): 6 | return 1000 7 | 8 | 9 | super_list1 = SuperList() 10 | print(len(super_list1)) 11 | 12 | super_list1.append(5) 13 | print(super_list1[0]) 14 | print(issubclass(SuperList, list)) 15 | print(issubclass(list, object)) 16 | -------------------------------------------------------------------------------- /4. Advanced Python/4-ExerciseMap_filter_zip_reduce.py: -------------------------------------------------------------------------------- 1 | from functools import reduce 2 | 3 | #1 Capitalize all of the pet names and print the list 4 | my_pets = ['sisi', 'bibi', 'titi', 'carla'] 5 | 6 | def capitalize(string): 7 | return string.upper() 8 | 9 | print(list(map(capitalize, my_pets))) 10 | 11 | 12 | #2 Zip the 2 lists into a list of tuples, but sort the numbers from lowest to highest. 13 | my_strings = ['a', 'b', 'c', 'd', 'e'] 14 | my_numbers = [5,4,3,2,1] 15 | 16 | print(list(zip(my_strings, sorted(my_numbers)))) 17 | 18 | 19 | #3 Filter the scores that pass over 50% 20 | scores = [73, 20, 65, 19, 76, 100, 88] 21 | 22 | def is_smart_student(score): 23 | return score > 50 24 | 25 | print(list(filter(is_smart_student, scores))) 26 | 27 | 28 | #4 Combine all of the numbers that are in a list on this file using reduce (my_numbers and scores). What is the total? 29 | def accumulator(acc, item): 30 | return acc + item 31 | 32 | print(reduce(accumulator, (my_numbers + scores))) -------------------------------------------------------------------------------- /4. Advanced Python/5-ExerciseLambda.py: -------------------------------------------------------------------------------- 1 | # Square 2 | my_list = [5, 4, 3] 3 | 4 | print(list(map(lambda item: item*item, my_list))) 5 | 6 | # List Sorting 7 | a = [(0, 2), (4, 3), (9, 9), (10, -2)] 8 | 9 | a.sort(key=lambda x: x[1]) 10 | print(a) 11 | 12 | -------------------------------------------------------------------------------- /4. Advanced Python/6-ExerciseComprehensions.py: -------------------------------------------------------------------------------- 1 | some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n'] 2 | 3 | duplicates = [] 4 | for value in some_list: 5 | if some_list.count(value) > 1: 6 | if value not in duplicates: 7 | duplicates.append(value) 8 | 9 | print(duplicates) 10 | 11 | 12 | #Solution: 13 | some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n'] 14 | duplicates = list(set([x for x in some_list if some_list.count(x) > 1])) 15 | print(duplicates) -------------------------------------------------------------------------------- /4. Advanced Python/7-ExerciseDecorators.py: -------------------------------------------------------------------------------- 1 | # Create an @authenticated decorator that only allows the function to run is user1 has 'valid' set to True: 2 | user1 = { 3 | 'name': 'Sorna', 4 | 'valid': True #changing this will either run or not run the message_friends function. 5 | } 6 | 7 | def authenticated(fn): 8 | # code here 9 | 10 | @authenticated 11 | def message_friends(user): 12 | print('message has been sent') 13 | 14 | message_friends(user1) 15 | 16 | 17 | #Solution: 18 | 19 | def authenticated(fn): 20 | # code here 21 | def wrapper(*args, **kwargs): 22 | if args[0]["valid"]: 23 | return fn(*args, **kwargs) 24 | else: 25 | return print("invalid user") 26 | 27 | return wrapper 28 | 29 | 30 | @authenticated 31 | def message_friends(user): 32 | print("message has been sent") 33 | 34 | 35 | message_friends(user1) -------------------------------------------------------------------------------- /4. Advanced Python/8-ExerciseGenerators.py: -------------------------------------------------------------------------------- 1 | def fib(number): 2 | n1 = 0 3 | n2 = 1 4 | for i in range(number): 5 | yield n1 6 | temp = n1 7 | n1 = n2 8 | n2 = temp + n2 9 | 10 | 11 | for x in fib(10000): 12 | print(x) -------------------------------------------------------------------------------- /4. Advanced Python/AttributesAndMethods.py: -------------------------------------------------------------------------------- 1 | # Attributes And Methods 2 | 3 | class PlayerCharacter: 4 | # Class Object Attribute 5 | membership = True 6 | 7 | def __init__(self, name, age): 8 | if self.membership: # Or PLayerCharacter.membership 9 | self.name = name 10 | self.age = age 11 | 12 | def shout(self): 13 | print(f'My name is {self.name}') 14 | 15 | def run(self, hello): 16 | print(f'{hello} {self.name}') 17 | 18 | 19 | player1 = PlayerCharacter('Cindy', 44) 20 | player1.shout() 21 | player1.run('Hi') 22 | print(player1.membership, '\t', player1.name, '\t', player1.age) 23 | -------------------------------------------------------------------------------- /4. Advanced Python/ClassmethodAndStaticmethod.py: -------------------------------------------------------------------------------- 1 | # @classmethod and @staticmethod 2 | 3 | class PlayerCharacter: 4 | def __init__(self, name, age): 5 | self.name = name 6 | self.age = age 7 | 8 | @classmethod 9 | def adding_things(cls, num1, num2): 10 | return cls('Teddy', num1 + num2) 11 | 12 | @staticmethod 13 | def adding_things2(num1, num2): 14 | return num1 + num2 15 | 16 | 17 | player3 = PlayerCharacter.adding_things(2, 3) # Instantiated class using classmethod 18 | print(player3) 19 | print(PlayerCharacter.adding_things2(5, 9)) 20 | -------------------------------------------------------------------------------- /4. Advanced Python/CreatingOurOwnObjects.py: -------------------------------------------------------------------------------- 1 | # Creating Our Own Objects 2 | 3 | class PlayerCharacter: 4 | def __init__(self, name, age): 5 | self.name = name 6 | self.age = age 7 | 8 | def run(self): 9 | print('Run') 10 | 11 | 12 | player1 = PlayerCharacter('Cindy', 44) 13 | player2 = PlayerCharacter('Tom', 21) 14 | player2.attack = 50 15 | 16 | print(player1.name) 17 | print(player2.name) 18 | print(player1.age) 19 | print(player2.age) 20 | player1.run() 21 | print(player2.attack) 22 | -------------------------------------------------------------------------------- /4. Advanced Python/DunderMethods.py: -------------------------------------------------------------------------------- 1 | # Dunder Methods 2 | 3 | class Toy: 4 | def __init__(self, color, age): 5 | self.color = color 6 | self.age = age 7 | self.my_dict= { 8 | 'name': 'Yoyo', 9 | 'has_pets': False 10 | } 11 | 12 | def __str__(self): 13 | return f'{self.color}' 14 | 15 | def __len__(self): 16 | return 5 17 | 18 | # def __del__(self): 19 | # print('deleted!') 20 | 21 | def __call__(self): 22 | return 'Yess?' 23 | 24 | def __getitem__(self, i): 25 | return self.my_dict[i] 26 | 27 | def __abs__(self, num): 28 | return num 29 | 30 | def __hex__(self): 31 | return 6 32 | 33 | def __set__(self): 34 | return 'done setting' 35 | 36 | 37 | action_figure = Toy('red', 0) 38 | print(action_figure.__str__()) 39 | print(str(action_figure)) 40 | print(len(action_figure)) 41 | # del action_figure 42 | print(action_figure()) 43 | print(action_figure['name']) 44 | print(action_figure.__abs__(-50)) 45 | print(action_figure.__hex__()) 46 | print(action_figure.__set__()) 47 | -------------------------------------------------------------------------------- /4. Advanced Python/Encapsulation.py: -------------------------------------------------------------------------------- 1 | # Encapsulation 2 | 3 | class PlayerCharacter: 4 | def __init__(self, name, age): 5 | if age > 18: 6 | self.name = name 7 | self.age = age 8 | 9 | def speak(self): 10 | print(f'My name is {self.name} and I am {self.age} years old.') 11 | 12 | 13 | player1 = PlayerCharacter('Tom', 20) 14 | player1.speak() 15 | -------------------------------------------------------------------------------- /4. Advanced Python/Generators.py: -------------------------------------------------------------------------------- 1 | #generators. 2 | 3 | #generators are much more performant than lists. (i.e range > list in performance.) 4 | 5 | #So generators are really, really useful when calculating large sets of data. 6 | 7 | from time import time 8 | 9 | def performance(fn): 10 | def wrapper(*args, **kwargs): 11 | t1 = time() 12 | result = fn(*args, *kwargs) 13 | t2 = time() 14 | print(f'took {t2-t1} s') 15 | return result 16 | return wrapper 17 | 18 | @performance 19 | def long_time(): 20 | print('1') 21 | for i in range(1000000): #it finishes after. 22 | i*5 23 | 24 | long_time() 25 | print() 26 | 27 | @performance 28 | def long_time2(): 29 | print('2') 30 | for i in list(range(1000000)): #it took longer. 31 | i*5 32 | 33 | long_time2() 34 | print() -------------------------------------------------------------------------------- /4. Advanced Python/Inheritance.py: -------------------------------------------------------------------------------- 1 | # Inheritance 2 | 3 | # Parent Class 4 | class User: 5 | def sign_in(self): 6 | print('logged in') 7 | 8 | 9 | # Sub Class/ Child Class/ Derived Class 10 | class Wizard(User): 11 | def __init__(self, name, power): 12 | self.name = name 13 | self.power = power 14 | 15 | def attack(self): 16 | print(f'Attacking with power of {self.power}') 17 | 18 | 19 | class Archer(User): 20 | def __init__(self, name, num_arrows): 21 | self.name = name 22 | self.num_arrows = num_arrows 23 | 24 | def attack(self): 25 | print(f'Attacking with arrows: Arrows left- {self.num_arrows}') 26 | 27 | 28 | wizard1 = Wizard('Merlin', 50) 29 | archer1 = Archer('Robbin', 100) 30 | wizard1.attack() 31 | archer1.attack() 32 | 33 | print(isinstance(wizard1, Wizard)) 34 | print(isinstance(wizard1, User)) 35 | print(isinstance(wizard1, object)) 36 | -------------------------------------------------------------------------------- /4. Advanced Python/Init.py: -------------------------------------------------------------------------------- 1 | # __init__ 2 | 3 | class PlayerCharacter: 4 | # Class Object Attribute 5 | membership = True 6 | 7 | def __init__(self, name, age): 8 | if age > 18: 9 | self.name = name 10 | self.age = age 11 | 12 | def shout(self): 13 | print(f'My name is {self.name}') 14 | 15 | 16 | player1 = PlayerCharacter('Tom', 20) 17 | print(player1.shout()) 18 | -------------------------------------------------------------------------------- /4. Advanced Python/MroMethodResolutionOrder.py: -------------------------------------------------------------------------------- 1 | # MRO - Method Resolution Order 2 | 3 | class A: 4 | num = 10 5 | 6 | 7 | class B(A): 8 | pass 9 | 10 | 11 | class C(A): 12 | num = 1 13 | 14 | 15 | class D(B, C): 16 | pass 17 | 18 | 19 | print(D.num) 20 | print(D.mro()) 21 | 22 | 23 | class X: 24 | pass 25 | 26 | 27 | class Y: 28 | pass 29 | 30 | 31 | class Z: 32 | pass 33 | 34 | 35 | class A(X, Y): 36 | pass 37 | 38 | 39 | class B(Y, Z): 40 | pass 41 | 42 | 43 | class M(B, A, Z): 44 | pass 45 | 46 | 47 | print(M.mro()) 48 | -------------------------------------------------------------------------------- /4. Advanced Python/MultipleInheritance.py: -------------------------------------------------------------------------------- 1 | # Multiple Inheritance 2 | 3 | class User: 4 | def sign_in(self): 5 | print('logged in') 6 | 7 | 8 | class Wizard(User): 9 | def __init__(self, name, power): 10 | self.name = name 11 | self.power = power 12 | 13 | def attack(self): 14 | print(f'Attacking with power of {self.power}') 15 | 16 | 17 | class Archer(User): 18 | def __init__(self, name, num_arrows): 19 | self.name = name 20 | self.num_arrows = num_arrows 21 | 22 | def check_arrows(self): 23 | print(f'{self.num_arrows} remaining') 24 | 25 | def run(self): 26 | print('Ran really fast.') 27 | 28 | 29 | class HybridBorg(Wizard, Archer): 30 | def __init__(self, name, power, arrows): 31 | Archer.__init__(self, name, arrows) 32 | Wizard.__init__(self, name, power) 33 | 34 | 35 | hb1 = HybridBorg('Borgie', 50, 100) 36 | print(hb1.run()) 37 | print(hb1.check_arrows()) 38 | hb1.attack() 39 | -------------------------------------------------------------------------------- /4. Advanced Python/OOP.py: -------------------------------------------------------------------------------- 1 | # OOP 2 | 3 | class BigObject: 4 | pass 5 | 6 | 7 | obj1 = BigObject() 8 | obj2 = BigObject() 9 | obj3 = BigObject() 10 | 11 | print(type(None)) 12 | print(type(True)) 13 | print(type(5)) 14 | print(type(5.5)) 15 | print(type('hi')) 16 | print(type([])) 17 | print(type(())) 18 | print(type({})) 19 | print(type(obj1)) 20 | -------------------------------------------------------------------------------- /4. Advanced Python/ObjectIntrospection.py: -------------------------------------------------------------------------------- 1 | # Object Introspection 2 | 3 | class User: 4 | def __init__(self, email): 5 | self.email = email 6 | 7 | def sign_in(self): 8 | print('logged in') 9 | 10 | 11 | # Sub Class/ Child Class/ Derived Class 12 | class Wizard(User): 13 | def __init__(self, name, power, email): 14 | super().__init__(email) 15 | # same as:: User.__init__(self, email) 16 | self.name = name 17 | self.power = power 18 | 19 | def attack(self): 20 | print(f'Attacking with power of {self.power}') 21 | 22 | 23 | wizard1 = Wizard('Merlin', 60, 'merlin@gmail.com') 24 | print(dir(wizard1)) 25 | -------------------------------------------------------------------------------- /4. Advanced Python/Polymorphism.py: -------------------------------------------------------------------------------- 1 | # Polymorphism 2 | 3 | # Parent Class 4 | class User: 5 | def sign_in(self): 6 | print('logged in') 7 | 8 | def attack(self): 9 | print('Do nothing.') 10 | 11 | 12 | # Sub Class/ Child Class/ Derived Class 13 | class Wizard(User): 14 | def __init__(self, name, power): 15 | self.name = name 16 | self.power = power 17 | 18 | def attack(self): 19 | print(f'Attacking with power of {self.power}') 20 | 21 | 22 | class Archer(User): 23 | def __init__(self, name, num_arrows): 24 | self.name = name 25 | self.num_arrows = num_arrows 26 | 27 | def attack(self): 28 | print(f'Attacking with arrows: Arrows left- {self.num_arrows}') 29 | 30 | 31 | wizard1 = Wizard('Merlin', 50) 32 | archer1 = Archer('Robbin', 30) 33 | 34 | 35 | def player_attack(char_): 36 | char_.attack() 37 | 38 | 39 | player_attack(wizard1) 40 | player_attack(archer1) 41 | 42 | for char in [wizard1, archer1]: 43 | char.attack() 44 | -------------------------------------------------------------------------------- /4. Advanced Python/PrivateVsPublicVariables.py: -------------------------------------------------------------------------------- 1 | # Private Vs Public Variables 2 | 3 | class PlayerCharacter: 4 | def __init__(self, name, age): 5 | if age > 18: 6 | self._name = name 7 | self._age = age 8 | 9 | def speak(self): 10 | print(f'My name is {self._name} and I am {self._age} years old.') 11 | 12 | 13 | player1 = PlayerCharacter('Tom', 20) 14 | player1.speak() 15 | -------------------------------------------------------------------------------- /4. Advanced Python/UndertheHoodGenerators.py: -------------------------------------------------------------------------------- 1 | def special_for(iterable): 2 | iterator = iter(iterable) 3 | while True: 4 | try: 5 | iterator*5 6 | next(iterator) 7 | except StopIteration: 8 | break 9 | 10 | 11 | class MyGen: 12 | current = 0 13 | def __init__(self, first, last): 14 | self.first = first 15 | self.last = last 16 | MyGen.current = self.first #this line allows us to use the current number as the starting point for the iteration 17 | 18 | def __iter__(self): 19 | return self 20 | 21 | def __next__(self): 22 | if MyGen.current < self.last: 23 | num = MyGen.current 24 | MyGen.current += 1 25 | return num 26 | raise StopIteration 27 | 28 | gen = MyGen(1,100) 29 | for i in gen: 30 | print(i) -------------------------------------------------------------------------------- /4. Advanced Python/super().py: -------------------------------------------------------------------------------- 1 | # super() 2 | 3 | class User: 4 | def __init__(self, email): 5 | self.email = email 6 | 7 | def sign_in(self): 8 | print('logged in') 9 | 10 | 11 | # Sub Class/ Child Class/ Derived Class 12 | class Wizard(User): 13 | def __init__(self, name, power, email): 14 | super().__init__(email) 15 | # same as:: User.__init__(self, email) 16 | self.name = name 17 | self.power = power 18 | 19 | def attack(self): 20 | print(f'Attacking with power of {self.power}') 21 | 22 | 23 | wizard1 = Wizard('Merlin', 60, 'merlin@gmail.com') 24 | print(wizard1.email) 25 | -------------------------------------------------------------------------------- /5. Modules in Python/GuessingGame.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | from random import randint 4 | 5 | random_number = randint(int(sys.argv[1]), int(sys.argv[2])) 6 | 7 | while True: 8 | try: 9 | number = int( 10 | input('Please choose a number that falls between those two you just chose: ')) 11 | if number >= int(sys.argv[1]) and number <= int(sys.argv[2]): 12 | if number == random_number: 13 | print("You're a genius!") 14 | break 15 | except ValueError: 16 | print("Please enter a number") 17 | continue -------------------------------------------------------------------------------- /6. Testing in Python/GuessingGame/exerciseMain.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | import sys 3 | # generate a number 1~10 4 | answer = randint(1, 10) 5 | 6 | # input from user? 7 | # check that input is a number 1~10 8 | while True: 9 | try: 10 | guess = int(input('guess a number 1~10: ')) 11 | if 0 < guess < 11: 12 | if guess == answer: 13 | print('you are a genius!') 14 | break 15 | else: 16 | print('hey bozo, I said 1~10') 17 | except ValueError: 18 | print('please enter a number') 19 | continue -------------------------------------------------------------------------------- /6. Testing in Python/GuessingGame/main.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def run_guess(guess, answer): 4 | if 0 < guess < 11: 5 | if guess == answer: 6 | print('you are a genius!') 7 | return True 8 | else: 9 | print('hey bozo, I said 1~10') 10 | return False 11 | 12 | if __name__ == '__main__': 13 | answer = random.randint(1, 10) 14 | while True: 15 | try: 16 | guess = int(input('guess a number 1~10: ')) 17 | if (run_guess(guess, answer)): 18 | break 19 | except ValueError: 20 | print('please enter a number') 21 | continue -------------------------------------------------------------------------------- /6. Testing in Python/GuessingGame/test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import main 3 | 4 | class TestGame(unittest.TestCase): 5 | def test_input(self): 6 | # please note in the video, I had the parameters flipped it should be the "guess" parameter 1st and "answer" parameter 2nd 7 | result = main.run_guess(5, 5) 8 | self.assertTrue(result) 9 | 10 | def test_input_wrong_guess(self): 11 | result = main.run_guess(0, 5) 12 | self.assertFalse(result) 13 | 14 | def test_input_wrong_number(self): 15 | result = main.run_guess(11, 5) 16 | self.assertFalse(result) 17 | 18 | def test_input_wrong_type(self): 19 | result = main.run_guess('11', 5) 20 | self.assertFalse(result) 21 | 22 | 23 | if __name__ == '__main__': 24 | unittest.main() -------------------------------------------------------------------------------- /6. Testing in Python/main.py: -------------------------------------------------------------------------------- 1 | def do_stuff(num=0): 2 | try: 3 | if num: # try to test for when input is 0. How can you fix this? 4 | return int(num) + 5 5 | else: 6 | return 'please enter number' 7 | except ValueError as err: 8 | return err -------------------------------------------------------------------------------- /6. Testing in Python/test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import main 3 | 4 | class TestGame(unittest.TestCase): 5 | def test_input(self): 6 | # please note in the video, I had the parameters flipped it should be the "guess" parameter 1st and "answer" parameter 2nd 7 | result = main.run_guess(5, 5) 8 | self.assertTrue(result) 9 | 10 | def test_input_wrong_guess(self): 11 | result = main.run_guess(0, 5) 12 | self.assertFalse(result) 13 | 14 | def test_input_wrong_number(self): 15 | result = main.run_guess(11, 5) 16 | self.assertFalse(result) 17 | 18 | def test_input_wrong_type(self): 19 | result = main.run_guess('11', 5) 20 | self.assertFalse(result) #although this works, it does not test for the error which you should test for. 21 | #Try to improve this by actually testing for the ValueError it triggers. Hint: 22 | #self.assertRaises(ValueError) 23 | 24 | 25 | if __name__ == '__main__': 26 | unittest.main() 27 | -------------------------------------------------------------------------------- /7. Scripting with Python/1-ExerciseEmail.py: -------------------------------------------------------------------------------- 1 | import smtplib 2 | from email.message import EmailMessage 3 | from string import Template 4 | from pathlib import Path 5 | 6 | html = Template(Path('index.html').read_text()) 7 | email = EmailMessage() 8 | email['from'] = 'Andrei Neagoie' 9 | email['to'] = ' 10 | email['subject'] = 'You won 1,000,000 dollars!' 11 | 12 | email.set_content(html.substitute({'name': 'TinTin'}), 'html') 13 | 14 | with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp: 15 | smtp.ehlo() 16 | smtp.starttls() 17 | smtp.login('', '') 18 | smtp.send_message(email) 19 | print('all good boss!') -------------------------------------------------------------------------------- /7. Scripting with Python/2-ExercisePasswordChecker.py: -------------------------------------------------------------------------------- 1 | #You will not be able to run this file here and will need to copy it onto your computer and run it on your machine. 2 | #You will also need to make sure you have installed the requests module from PyPi (pip install) 3 | import requests 4 | import hashlib 5 | import sys 6 | 7 | def request_api_data(query_char): 8 | url = 'https://api.pwnedpasswords.com/range/' + query_char 9 | res = requests.get(url) 10 | if res.status_code != 200: 11 | raise RuntimeError(f'Error fetching: {res.status_code}, check the api and try again') 12 | return res 13 | 14 | def get_password_leaks_count(hashes, hash_to_check): 15 | hashes = (line.split(':') for line in hashes.text.splitlines()) 16 | for h, count in hashes: 17 | if h == hash_to_check: 18 | return count 19 | return 0 20 | 21 | def pwned_api_check(password): 22 | sha1password = hashlib.sha1(password.encode('utf-8')).hexdigest().upper() 23 | first5_char, tail = sha1password[:5], sha1password[5:] 24 | response = request_api_data(first5_char) 25 | return get_password_leaks_count(response, tail) 26 | 27 | def main(args): 28 | for password in args: 29 | count = pwned_api_check(password) 30 | if count: 31 | print(f'{password} was found {count} times... you should probably change your password!') 32 | else: 33 | print(f'{password} was NOT found. Carry on!') 34 | return 'done!' 35 | 36 | if __name__ == '__main__': 37 | sys.exit(main(sys.argv[1:])) 38 | 39 | -------------------------------------------------------------------------------- /7. Scripting with Python/3-ExerciseTweet.py: -------------------------------------------------------------------------------- 1 | #You will need to PIP INSTALL tweepy for this to work and also create a twitter API. Run this on your own machine, not in this Repl. 2 | import tweepy 3 | import time 4 | 5 | consumer_key = '' 6 | consumer_secret = '' 7 | access_token = '' 8 | access_token_secret = '' 9 | auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 10 | auth.set_access_token(access_token, access_token_secret) 11 | api = tweepy.API(auth) 12 | 13 | user = api.me() 14 | print (user.name) #prints your name. 15 | print (user.screen_name) 16 | print (user.followers_count) 17 | 18 | search = "zerotomastery" 19 | numberOfTweets = 2 20 | 21 | def limit_handle(cursor): 22 | while True: 23 | try: 24 | yield cursor.next() 25 | except tweepy.RateLimitError: 26 | time.sleep(1000) 27 | 28 | #Be nice to your followers. Follow everyone! 29 | for follower in limit_handle(tweepy.Cursor(api.followers).items()): 30 | if follower.name == 'Usernamehere': 31 | print(follower.name) 32 | follower.follow() 33 | 34 | 35 | # Be a narcisist and love your own tweets. or retweet anything with a keyword! 36 | for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets): 37 | try: 38 | tweet.favorite() 39 | print('Retweeted the tweet') 40 | except tweepy.TweepError as e: 41 | print(e.reason) 42 | except StopIteration: 43 | break -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Complete-Python-Developer-ZTM 2 | 3 | Includes Replit coding exercises and code notes for Complete Python Developer Zero to Mastery course. 4 | 5 | --------------------------------------------------------------------------------