├── .gitignore ├── python-exercises ├── while_loop.py ├── mileage.py ├── bouncer.py ├── loops.py ├── guessing.py ├── lists.py ├── data_modelling.py ├── game_5.py ├── functions.py ├── game.py ├── elo.py └── game_2.py ├── docs ├── OOPS │ ├── Reference_variable_2.py │ ├── Constructor1.py │ ├── Pass_by_reference1.py │ ├── Reference_variable.py │ ├── Pass_by_reference4.py │ ├── static6.py │ ├── Reference_variable_5.py │ ├── self_in_methods.py │ ├── Printing_objects.py │ ├── Reference_variable_4.py │ ├── static9.py │ ├── static8.py │ ├── dict_of_objects.py │ ├── Pass_by_reference3.py │ ├── Pass_by_reference5.py │ ├── Reference_variable_3.py │ ├── static7.py │ ├── static4.py │ ├── static3.py │ ├── static5.py │ ├── static1.py │ ├── Self_and_Reference_Variable.py │ ├── Pass_by_reference2.py │ ├── Accessing_pvt_var1.py │ ├── Encapsulation.py │ ├── Behavior_in_class.py │ ├── Accessing_pvt_var2.py │ ├── Classes and Objects.md │ ├── collection_of_objects.py │ ├── static2.py │ ├── Shopping_app.py │ └── What_is_self(full).py ├── expressions_and_statements.md ├── index.md ├── tuples_and_sets.md ├── data-types.md ├── variables.md ├── strings.md ├── loops.md ├── booleans.md ├── lambdas.md ├── dictionary.md ├── lists.md ├── source │ └── conf.py └── functions.md ├── markdown-version ├── oop.md ├── expressions_and_statements.md ├── iterators-generators.md ├── tuples_and_sets.md ├── data-types.md ├── variables.md ├── debugging.md ├── modules.md ├── strings.md ├── loops.md ├── booleans.md ├── dictionary.md ├── lists.md ├── lambdas.md └── functions.md ├── LICENSE.md └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | Pipfile 2 | Pipfile.lock 3 | -------------------------------------------------------------------------------- /python-exercises/while_loop.py: -------------------------------------------------------------------------------- 1 | # A simple while loop example 2 | user_input = input('Hey how are you ') 3 | while user_input != 'stop copying me': 4 | print(user_input) 5 | user_input = input() 6 | else: 7 | print('UGHH Fine') -------------------------------------------------------------------------------- /python-exercises/mileage.py: -------------------------------------------------------------------------------- 1 | #This is simple excercise part of the course. In this exercise I will build a conversion calculator 2 | user_input = input("How many km did you run today ") 3 | miles = int(user_input)/1.6 4 | print(f"Today you ran {miles} miles. Good Job") 5 | -------------------------------------------------------------------------------- /python-exercises/bouncer.py: -------------------------------------------------------------------------------- 1 | # A Simple Bouncer Program 2 | age = input('What is your age ') 3 | x = int(age) 4 | if x < 18: 5 | print('Sorry You are too young') 6 | elif x >= 18 and x <= 21: 7 | print('You are allowed to go') 8 | else: 9 | print('You are old enough for this') 10 | -------------------------------------------------------------------------------- /python-exercises/loops.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | if x == 4: 5 | print('{} is unlucky').format(x) 6 | elif x == 13: 7 | print('{} is unlucky').format(x) 8 | elif x % 2 == 0: 9 | print('{} is an even number').format(x) 10 | elif x%2 != 0: 11 | print('{} is an odd number').format(x) 12 | else: 13 | print(x) 14 | -------------------------------------------------------------------------------- /python-exercises/guessing.py: -------------------------------------------------------------------------------- 1 | # #This is a simple guessing game in Python. 2 | from random import * 3 | number = randint(1,10) 4 | while True: 5 | guess = input('Pick a number from 1 to 10: ') 6 | guess = int(guess) 7 | if guess < number: 8 | print('Its too low') 9 | elif guess > number: 10 | print('its to high') 11 | else: 12 | print('You Won') 13 | break -------------------------------------------------------------------------------- /docs/OOPS/Reference_variable_2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Just like a balloon without a ribbon, an object without a reference variable cannot be used later. 3 | ''' 4 | class Mobile: 5 | def __init__(self, price, brand): 6 | self.price = price 7 | self.brand = brand 8 | 9 | Mobile(1000, "Apple") 10 | #After the above line the Mobile 11 | # object created is lost and unusable 12 | -------------------------------------------------------------------------------- /docs/OOPS/Constructor1.py: -------------------------------------------------------------------------------- 1 | class Mobile: 2 | def __init__(self, brand, price): 3 | print("Inside constructor") 4 | self.brand = brand 5 | self.price = price 6 | 7 | mob1=Mobile("Apple", 20000) 8 | print("Mobile 1 has brand", mob1.brand, "and price", mob1.price) 9 | 10 | mob2=Mobile("Samsung",3000) 11 | print("Mobile 2 has brand", mob2.brand, "and price", mob2.price) 12 | -------------------------------------------------------------------------------- /python-exercises/lists.py: -------------------------------------------------------------------------------- 1 | # A simple shopping list program that uses python lists 2 | shopping_list = [] 3 | print('Hi Welcome to Personalized Shopping List ') 4 | user_input = input('What items would you like to add ') 5 | while True: 6 | shopping_list.append(user_input) 7 | user_input = input('Would you like to add more or list ') 8 | if user_input == 'list': 9 | for item in shopping_list: 10 | print(item) 11 | else: 12 | break -------------------------------------------------------------------------------- /docs/OOPS/Pass_by_reference1.py: -------------------------------------------------------------------------------- 1 | ''' 2 | What happens when we pass an object as a parameter to a function? In the below code, what will be the output? 3 | ''' 4 | 5 | 6 | class Mobile: 7 | def __init__(self, price, brand): 8 | self.price = price 9 | self.brand = brand 10 | 11 | def change_price(mobile_obj): 12 | mobile_obj.price = 3000 13 | 14 | mob1=Mobile(1000, "Apple") 15 | change_price(mob1) 16 | print (mob1.price) 17 | -------------------------------------------------------------------------------- /python-exercises/data_modelling.py: -------------------------------------------------------------------------------- 1 | #In this file I am going to model a Spotify playlist 2 | playlist ={ 3 | 'name':'hip-hop', 4 | 'author':'John', 5 | 'songs' : [ 6 | { 7 | 'title':'Walk it Talk it', 8 | 'artist': 'Migos', 9 | }, 10 | { 11 | 'title':'New Freezer', 12 | 'artist' : 'Rich Kid', 13 | }, 14 | { 15 | 'title':'New Freezer', 16 | 'artist':'Chris Brown', 17 | } 18 | ], 19 | } 20 | 21 | for song in playlist['songs']: 22 | print(song['title']) -------------------------------------------------------------------------------- /markdown-version/oop.md: -------------------------------------------------------------------------------- 1 | # What is Object Oriented Programming 2 | In simple words `OOP` is used to represent things that don't exist in a programming language such as a player, car, processor and etc. 3 | 4 | We represent things using `classes` and `objects`. 5 | 6 | ## What is a Class 7 | A `Class` is a blueprint for objects.It can contain methods (functions) and attributes. 8 | An `instance` or `object` they are constructed from a class blueprint that contains their class methods and properties. 9 | -------------------------------------------------------------------------------- /docs/OOPS/Reference_variable.py: -------------------------------------------------------------------------------- 1 | ''' 2 | An object is like a balloon and the reference variable is like the ribbon connecting it to the ground. 3 | ''' 4 | 5 | class Mobile: 6 | def __init__(self, price, brand): 7 | self.price = price 8 | self.brand = brand 9 | 10 | mob1=Mobile(1000, "Apple") 11 | print(mob1.price) 12 | #We are able to access the object 13 | #in subsequent lines because we 14 | #have a reference variable. This is 15 | #like holding a balloon with a ribbon 16 | -------------------------------------------------------------------------------- /docs/OOPS/Pass_by_reference4.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Can you guess what is the output of the below code? Discuss your output. 3 | ''' 4 | 5 | def change_function(data): 6 | print ("Id of list received in method", id(data)) 7 | data = [200, 300, 400] 8 | print ("Id of list after list assignment in method", id(data)) 9 | 10 | value = [100, 200, 300] 11 | print ("List and its id before method call", value, id(value)) 12 | change_function(value) 13 | print ("List and its id after method call ", value, id(value)) 14 | -------------------------------------------------------------------------------- /docs/OOPS/static6.py: -------------------------------------------------------------------------------- 1 | #Static Variables and Encapsulation 2 | 3 | ''' 4 | We can make our static variable as a private variable by adding a double underscore in front of it. 5 | We can also create getter and setter methods to access or modify it. 6 | ''' 7 | 8 | class Mobile: 9 | __discount = 50 10 | 11 | def get_discount(self): 12 | return Mobile.__discount 13 | 14 | def set_discount(self,discount): 15 | Mobile.__discount = discount 16 | 17 | m1=Mobile() 18 | print(m1.get_discount()) 19 | -------------------------------------------------------------------------------- /python-exercises/game_5.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import random 3 | 4 | try: 5 | input = raw_input # Python 2 6 | except NameError: 7 | pass # Python 3 8 | 9 | min = 1 10 | max = 6 11 | 12 | roll_again = "yes" 13 | 14 | while roll_again in ("yes", "y"): 15 | print("Rolling the dices...") 16 | print("The values are....") 17 | print(random.randint(min, max)) 18 | print(random.randint(min, max)) 19 | 20 | roll_again = input("Roll the dices again?").strip().lower() -------------------------------------------------------------------------------- /python-exercises/functions.py: -------------------------------------------------------------------------------- 1 | # #Heads & Tail 2 | # from random import random 3 | 4 | # def heads_tails(): 5 | # r = random() 6 | # if r > 0.5: 7 | # return "HEADS" 8 | # else: 9 | # return "TAILS" 10 | 11 | # print(heads_tails()) 12 | 13 | # This function generates even numbers 14 | # def generate_evens(): 15 | # even = [x for x in range(1,50) if x % 2==0] 16 | # return even 17 | 18 | # print(generate_evens()) 19 | 20 | # def add(a,b): 21 | # return a+b 22 | # def math(a,b,fn=add): 23 | # return add(a,b) 24 | # print(math(10,10)) -------------------------------------------------------------------------------- /docs/OOPS/Reference_variable_5.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Just like the balloons and ribbons, we can make one reference variable refer to another object. 3 | Now any change made through this reference variable will not affect the old object. 4 | ''' 5 | 6 | class Mobile: 7 | def __init__(self, price, brand): 8 | self.price = price 9 | self.brand = brand 10 | 11 | mob1=Mobile(1000, "Apple") 12 | 13 | mob2=mob1 14 | mob2=Mobile(2000, "Samsung") 15 | mob2.price=3000 16 | 17 | print("Mobile", "Id","Price") 18 | print("mob1", id(mob1), mob1.price) 19 | print("mob2", id(mob2), mob2.price) 20 | -------------------------------------------------------------------------------- /docs/expressions_and_statements.md: -------------------------------------------------------------------------------- 1 | #### Expressions 2 | * An expression is a combination of variables, values and operators. 3 | * Python Interpreter evalutes the expression to get the values. 4 | 5 | ```Python3 6 | # some examples of Expressions 7 | >>> 44 8 | 44 9 | >>> a = 43 + 32 10 | >>> a 11 | 75 12 | 13 | ``` 14 | 15 | 16 | #### Statements 17 | * An statement is a piece of code that do some actions. 18 | * Python Interpreter executes the statements. 19 | 20 | ```Python3 21 | # some examples of Statements 22 | >>> print('hello world') 23 | 'hello world' 24 | >>> day = 'monday' 25 | 26 | ``` 27 | -------------------------------------------------------------------------------- /docs/OOPS/self_in_methods.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In the below code, how does return_product() method know which mobile object we are using? 3 | ''' 4 | 5 | class Mobile: 6 | def __init__(self,price,brand): 7 | print ("Mobile created with id", id(self)) 8 | self.price = price 9 | self.brand = brand 10 | 11 | def return_product(self): 12 | print ("Mobile being returned has id", id(self)) 13 | print ("Brand being returned is ",self.brand," and price is ",self.price) 14 | 15 | mob1=Mobile(1000,"Apple") 16 | 17 | mob2=Mobile(2000,"Samsung") 18 | 19 | mob2.return_product() 20 | -------------------------------------------------------------------------------- /docs/OOPS/Printing_objects.py: -------------------------------------------------------------------------------- 1 | ''' 2 | For a readable output when printing an object we can use the inbuilt special __str__ method. 3 | This method MUST return a string and this string will be used when the object is printed. 4 | This is useful in debugging as we can print the values of the attributes 5 | ''' 6 | 7 | class Shoe: 8 | def __init__(self, price, material): 9 | self.price = price 10 | self.material = material 11 | 12 | def __str__(self): 13 | return "Shoe with price: " + str(self.price) + " and material: " + self.material 14 | 15 | s1=Shoe(1000, "Canvas") 16 | print(s1) 17 | -------------------------------------------------------------------------------- /docs/OOPS/Reference_variable_4.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Just like the balloon with multiple ribbons, if we change the attribute of an object 3 | through one reference variable, it immediately reflects in other reference variable as 4 | there is only one balloon ultimately! 5 | ''' 6 | 7 | class Mobile: 8 | def __init__(self, price, brand): 9 | self.price = price 10 | self.brand = brand 11 | 12 | mob1=Mobile(1000, "Apple") 13 | print("Price of mobile 1 :", mob1.price) 14 | 15 | mob2=mob1 16 | mob2.price=3000 17 | 18 | print("Price of mobile 1 :", mob1.price) 19 | print("Price of mobile 2 :", mob2.price) 20 | -------------------------------------------------------------------------------- /markdown-version/expressions_and_statements.md: -------------------------------------------------------------------------------- 1 | #### Expressions 2 | * An expression is a combination of variables, values and operators. 3 | * Python Interpreter evalutes the expression to get the values. 4 | 5 | ```Python3 6 | # some examples of Expressions 7 | >>> 44 8 | 44 9 | >>> a = 43 + 32 10 | >>> a 11 | 75 12 | 13 | ``` 14 | 15 | 16 | #### Statements 17 | * An statement is a piece of code that do some actions. 18 | * Python Interpreter executes the statements. 19 | 20 | ```Python3 21 | # some examples of Statements 22 | >>> print('hello world') 23 | 'hello world' 24 | >>> day = 'monday' 25 | 26 | ``` 27 | -------------------------------------------------------------------------------- /docs/OOPS/static9.py: -------------------------------------------------------------------------------- 1 | ''' 2 | We can access static methods directly using the class name, even without creating objects. 3 | ''' 4 | 5 | class Mobile: 6 | __discount = 50 7 | def __init__(self, price, brand): 8 | self.price = price 9 | self.brand = brand 10 | 11 | def purchase(self): 12 | total = self.price - self.price * Mobile.__discount / 100 13 | print ("Total is ",total) 14 | 15 | @staticmethod 16 | def get_discount(): 17 | return Mobile.__discount 18 | 19 | @staticmethod 20 | def set_discount(discount): 21 | Mobile.__discount = discount 22 | 23 | print (Mobile.get_discount()) 24 | -------------------------------------------------------------------------------- /docs/OOPS/static8.py: -------------------------------------------------------------------------------- 1 | #Static Method continued 2 | 3 | ''' 4 | Since static variable is object independent, we need a way to access the getter setter methods without an object. This is possible by creating static methods. Static methods are those methods which can be accessed without an object. They are accessed using the class name. 5 | 6 | There are two rules in creating such static methods: 7 | 8 | The methods should not have self 9 | @staticmethod must be written on top of it 10 | 11 | ''' 12 | 13 | 14 | @staticmethod 15 | def get_discount(): 16 | return Mobile.__discount 17 | @staticmethod 18 | def set_discount(discount): 19 | Mobile.__discount=discount 20 | -------------------------------------------------------------------------------- /docs/OOPS/dict_of_objects.py: -------------------------------------------------------------------------------- 1 | ''' 2 | We can also store objects in a dictionary. 3 | For example, in the below code we are storing all the mobile objects in a dictionary 4 | and printing only those mobiles whose price is greater than 3000 5 | ''' 6 | 7 | class Mobile: 8 | def __init__(self,brand,price): 9 | self.brand = brand 10 | self.price = price 11 | 12 | mob1=Mobile("Apple", 1000) 13 | mob2=Mobile("Samsung", 5000) 14 | mob3=Mobile("Apple", 3000) 15 | 16 | mob_dict={ 17 | "m1":mob1, 18 | "m2":mob2, 19 | "m3":mob3 20 | } 21 | 22 | for key,value in mob_dict.items(): 23 | if value.price > 3000: 24 | print (value.brand,value.price) 25 | -------------------------------------------------------------------------------- /python-exercises/game.py: -------------------------------------------------------------------------------- 1 | #Its a simple Rock paper scissor game 2 | print('...Rock...') 3 | print('...Paper...') 4 | print('...Scissor...') 5 | x = input('Enter Player 1 Choice ') 6 | print('No Cheating\n\n' * 20) 7 | y = input('Enter Play 2 Choice ') 8 | if x == 'paper' and y == 'rock': 9 | print('Player 1 won') 10 | elif x == 'rock' and y == 'paper': 11 | print('Player 2 wins') 12 | elif x == 'scissor' and y == 'paper': 13 | print('Player 1 wins') 14 | elif x == 'paper' and y == 'scissor': 15 | print('Player 2 wins ') 16 | elif x == 'rock' and y == 'scissor': 17 | print('Player 1 wins') 18 | elif x == 'scissor' and y == 'rock': 19 | print('Player 2 wins ') 20 | else: 21 | print('Something else went wrong') -------------------------------------------------------------------------------- /docs/OOPS/Pass_by_reference3.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In python, everything is an object. 3 | Hence when we pass a list to a function and when we modify the list, 4 | the changes are reflected outside the function as well. 5 | For example, we can see that there is only one object and value and data are references to that object. 6 | ''' 7 | 8 | def change_function(data): 9 | print ("Id of list received in method", id(data)) 10 | data[1] = 500 11 | print ("Id of list after element modification in method", id(data)) 12 | 13 | value = [100, 200, 300] 14 | print ("List and its id before method call", value, id(value)) 15 | change_function(value) 16 | print ("List and its id after method call ", value, id(value)) 17 | -------------------------------------------------------------------------------- /docs/OOPS/Pass_by_reference5.py: -------------------------------------------------------------------------------- 1 | ''' 2 | For changes to reflect outside the function, the object must be mutable object. 3 | All objects created through custom classes are mutable objects. 4 | If the objects are immutable, the changes don't reflect outside the function. 5 | This is because any changes made to a immutable object creates a new object. 6 | In the below code you can see that when we try to modify the string, it creates 7 | a new string object and the original string object is unchanged. 8 | ''' 9 | 10 | def change(strng): 11 | print("Object ID before modification ",id(strng)) 12 | strng=strng.upper() 13 | print("Object ID after modification ",id(strng)) 14 | 15 | s1="hello" 16 | change(s1) 17 | print(s1) 18 | -------------------------------------------------------------------------------- /docs/OOPS/Reference_variable_3.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Just like a balloon can have multiple ribbons, an object can also have multiple reference variables. 3 | Both the references are referring to the same object. 4 | When you assign an already created object to a variable, a new object is not created. 5 | ''' 6 | 7 | class Mobile: 8 | def __init__(self, price, brand): 9 | print ("Inside constructor") 10 | self.price = price 11 | self.brand = brand 12 | 13 | mob1=Mobile(1000, "Apple") 14 | mob2=mob1 15 | print ("Id of object referred by mob1 reference variable is :", id(mob1)) 16 | print ("Id of object referred by mob2 reference variable is :", id(mob2)) 17 | #mob1 and mob2 are reference variables to the same object 18 | -------------------------------------------------------------------------------- /docs/OOPS/static7.py: -------------------------------------------------------------------------------- 1 | #Static Method 2 | 3 | ''' 4 | In the below code we are invoking the getter method using a reference variable. 5 | But the self is not used inside the method at all. 6 | ''' 7 | 8 | 9 | class Mobile: 10 | __discount = 50 11 | def __init__(self, price, brand): 12 | self.price = price 13 | self.brand = brand 14 | 15 | def purchase(self): 16 | total = self.price - self.price * Mobile.__discount / 100 17 | print ("Total is ",total) 18 | 19 | def get_discount(self): 20 | return Mobile.__discount 21 | 22 | def set_discount(self,discount): 23 | Mobile.__discount = discount 24 | 25 | mob1=Mobile(20000, "Apple") 26 | mob2=Mobile(30000, "Apple") 27 | mob3=Mobile(5000, "Samsung") 28 | 29 | print (mob1.get_discount()) 30 | -------------------------------------------------------------------------------- /docs/OOPS/static4.py: -------------------------------------------------------------------------------- 1 | #Accessing Static Variables 2 | 3 | ''' 4 | Now that we have created static variables, we can access them using the Class name itself. 5 | Static variable belong to the class and not an object. 6 | Hence we don’t need self to access static variables. 7 | ''' 8 | 9 | class Mobile: 10 | discount = 50 11 | def __init__(self, price, brand): 12 | self.price = price 13 | self.brand = brand 14 | 15 | def purchase(self): 16 | total = self.price - self.price * Mobile.discount / 100 17 | print (self.brand, "mobile with price", self.price, "is available after discount at", total) 18 | 19 | mob1=Mobile(20000, "Apple") 20 | mob2=Mobile(30000, "Apple") 21 | mob3=Mobile(5000, "Samsung") 22 | 23 | mob1.purchase() 24 | mob2.purchase() 25 | mob3.purchase() 26 | -------------------------------------------------------------------------------- /python-exercises/elo.py: -------------------------------------------------------------------------------- 1 | def elo(player_rating, opponent_rating, won, k=32): 2 | q1 = 10**(player_rating / 400) 3 | q2 = 10**(opponent_rating / 400) 4 | 5 | expected_score = q1 / (q1 + q2) 6 | true_score = int(won) 7 | 8 | final_score = player_rating + k * (true_score - expected_score) 9 | return int(final_score) 10 | 11 | 12 | rating1 = int(input('First player score: ')) 13 | rating2 = int(input('Second player score: ')) 14 | player1_won = int(input('Which player won? [1/2]: ')) == 1 15 | 16 | new_rating1 = elo(rating1, rating2, player1_won) 17 | new_rating2 = elo(rating2, rating1, not player1_won) 18 | 19 | print('Player 1 new score: {}. Change: {}'.format(new_rating1, new_rating1 - rating1)) 20 | print('Player 2 new score: {}. Change: {}'.format(new_rating2, new_rating2 - rating2)) 21 | -------------------------------------------------------------------------------- /docs/OOPS/static3.py: -------------------------------------------------------------------------------- 1 | #Shared variables 2 | 3 | ''' 4 | What we need is a way to make an attribute shared across objects. 5 | The data is shared by all objects, not owned by each object. 6 | Thus, by making a single change, it should reflect in all objects at one go. 7 | ''' 8 | 9 | #Static 10 | 11 | ''' 12 | We can create shared attributes by placing them directly inside the class and not inside the constructor. 13 | And since this attribute is not owned by any one object, we don’t need the self to create this attribute. 14 | Such variables which are created at a class level are called static variables. 15 | Here discount is a static value. 16 | ''' 17 | 18 | 19 | class Mobile: 20 | discount = 50 21 | def __init__(self, price, brand): 22 | self.price = price 23 | self.brand = brand 24 | -------------------------------------------------------------------------------- /docs/OOPS/static5.py: -------------------------------------------------------------------------------- 1 | #Updating Static Values 2 | 3 | 4 | ''' 5 | We can update the static value using the class name. 6 | ''' 7 | 8 | 9 | class Mobile: 10 | discount = 50 11 | def __init__(self, price, brand): 12 | self.price = price 13 | self.brand = brand 14 | 15 | def purchase(self): 16 | total = self.price - self.price * Mobile.discount / 100 17 | print (self.brand, "mobile with price", self.price, "is available after discount at", total) 18 | 19 | def enable_discount(): 20 | Mobile.discount = 50 21 | 22 | def disable_discount(): 23 | Mobile.discount = 0 24 | 25 | mob1=Mobile(20000, "Apple") 26 | mob2=Mobile(30000, "Apple") 27 | mob3=Mobile(5000, "Samsung") 28 | 29 | enable_discount() 30 | mob1.purchase() 31 | mob2.purchase() 32 | 33 | disable_discount() 34 | mob3.purchase() 35 | -------------------------------------------------------------------------------- /docs/OOPS/static1.py: -------------------------------------------------------------------------------- 1 | #Need for static 2 | 3 | ''' 4 | Let us assume that in our online shopping app, we want to provide a limited 50% flat off on all mobile phones. 5 | How can we write our code so that all mobile objects get a 50% off? 6 | One solution is to create a discount attribute and hard code the value as 50% as shown below: 7 | ''' 8 | 9 | class Mobile: 10 | def __init__(self, price, brand): 11 | self.price = price 12 | self.brand = brand 13 | self.discount = 50 14 | 15 | def purchase(self): 16 | total = self.price - self.price * self.discount / 100 17 | print (self.brand, "mobile with price", self.price, "is available after discount at", total) 18 | 19 | mob1=Mobile(20000, "Apple") 20 | mob2=Mobile(30000, "Apple") 21 | mob3=Mobile(5000, "Samsung") 22 | 23 | mob1.purchase() 24 | mob2.purchase() 25 | -------------------------------------------------------------------------------- /docs/OOPS/Self_and_Reference_Variable.py: -------------------------------------------------------------------------------- 1 | ''' 2 | mob2.return_product() can also be invoked as Mobile.return_product(mob2) 3 | 4 | Thus self now refers to mob2, as this is actually pass by reference. 5 | For simplicity sake and for better readability we use mob2.return_product() instead of Mobile.return_product(mob2) 6 | ''' 7 | 8 | class Mobile: 9 | def __init__(self,price,brand): 10 | print (id(self)) 11 | self.price = price 12 | self.brand = brand 13 | 14 | def return_product(self): 15 | print (id(self)) 16 | print ("Brand being returned is ",self.brand," and price is ",self.price) 17 | 18 | mob1 = Mobile(1000, "Apple") 19 | print ("Mobile 1 has id", id(mob1)) 20 | 21 | mob2=Mobile(2000, "Samsung") 22 | print ("Mobile 2 has id", id(mob2)) 23 | 24 | mob2.return_product() 25 | Mobile.return_product(mob2) 26 | -------------------------------------------------------------------------------- /docs/OOPS/Pass_by_reference2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | When we pass an object to a parameter, the parameter name becomes a reference variable. 3 | 4 | Recollecting the balloon example, it is like creating one more ribbon to the same balloon. 5 | Thus there is one object with two reference variable, one the formal parameter and the actual parameter. 6 | Thus any change made through one reference variable will affect the other as well. 7 | ''' 8 | 9 | class Mobile: 10 | def __init__(self, price, brand): 11 | self.price = price 12 | self.brand = brand 13 | 14 | def change_price(mobile_obj): 15 | print ("Id of object inside function", id(mobile_obj)) 16 | mobile_obj.price=3000 17 | 18 | mob1=Mobile(1000, "Apple") 19 | print ("Id of object in driver code", id(mob1)) 20 | 21 | mob1.change_price() 22 | print ("Price of mob1 ", mob1.price) 23 | -------------------------------------------------------------------------------- /docs/OOPS/Accessing_pvt_var1.py: -------------------------------------------------------------------------------- 1 | ''' 2 | When we put a double underscore in front of the attribute name, python will internally change its name to _Classname__attribute. 3 | 4 | Since we know that the name of the variable changes when we make it private, we can access it using its modified name as shown below: 5 | ''' 6 | class Customer: 7 | def __init__(self, cust_id, name, age, wallet_balance): 8 | self.cust_id = cust_id 9 | self.name = name 10 | self.age = age 11 | self.__wallet_balance = wallet_balance 12 | 13 | def update_balance(self, amount): 14 | if amount < 1000 and amount > 0: 15 | self.__wallet_balance += amount 16 | 17 | def show_balance(self): 18 | print ("The balance is ",self.__wallet_balance) 19 | 20 | c1=Customer(100, "Gopal", 24, 1000) 21 | c1._Customer__wallet_balance = 10000000000 22 | c1.show_balance() 23 | -------------------------------------------------------------------------------- /docs/OOPS/Encapsulation.py: -------------------------------------------------------------------------------- 1 | ''' 2 | We can put a lock on that data by adding a double underscore in front of it. 3 | 4 | Adding a double underscore makes the attribute a private attribute. 5 | Private attributes are those which are accessible only inside the class. 6 | This method of restricting access to our data is called encapsulation. 7 | ''' 8 | 9 | class Customer: 10 | def __init__(self, cust_id, name, age, wallet_balance): 11 | self.cust_id = cust_id 12 | self.name = name 13 | self.age = age 14 | self.__wallet_balance = wallet_balance 15 | 16 | def update_balance(self, amount): 17 | if amount < 1000 and amount > 0: 18 | self.__wallet_balance += amount 19 | 20 | def show_balance(self): 21 | print ("The balance is ",self.__wallet_balance) 22 | 23 | c1=Customer(100, "Gopal", 24, 1000) 24 | print(c1.__wallet_balance) 25 | -------------------------------------------------------------------------------- /python-exercises/game_2.py: -------------------------------------------------------------------------------- 1 | # Its a simple rock paper scissor game that uses the random module to play instead of a human 2 | from random import * 3 | x = randint(1,3) 4 | if x == 1: 5 | computer = 'rock' 6 | elif x == 2: 7 | computer = 'scissor' 8 | else: 9 | computer = 'paper' 10 | player_1 = input('What is your pick ') 11 | if player_1 == computer: 12 | print('Its a tie') 13 | elif player_1 == 'scissor': 14 | if computer == 'rock': 15 | print('Computer won') 16 | elif player_1 == 'rock': 17 | if computer == 'scissor': 18 | print('You won') 19 | elif player_1 == 'scissor': 20 | if computer == 'paper': 21 | print('You won') 22 | elif player_1 == 'paper': 23 | if computer == 'scissor': 24 | print('Computer Won') 25 | elif player_1 == 'paper': 26 | if computer == 'rock': 27 | print('You Won') 28 | elif player_1 == 'rock': 29 | if computer == 'paper': 30 | print('Computer Won') 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /docs/OOPS/Behavior_in_class.py: -------------------------------------------------------------------------------- 1 | ''' 2 | We can access an attribute in a method by using self. 3 | Value of the attribute accessed inside the method is determined by the object used to invoke the method. 4 | For example, in the code below when we invoke purchase using mob1, attribute values (Apple and 20000) of mob1 are accessed. 5 | Similarly, when mob2 is used to invoke purchase, attribute values (Samsung and 3000) of mob2 are accessed in purchase(). 6 | ''' 7 | 8 | class Mobile: 9 | def __init__(self, brand, price): 10 | print("Inside constructor") 11 | self.brand = brand 12 | self.price = price 13 | 14 | def purchase(self): 15 | print("Purchasing a mobile") 16 | print("This mobile has brand", self.brand, "and price", self.price) 17 | 18 | print("Mobile-1") 19 | mob1=Mobile("Apple", 20000) 20 | mob1.purchase() 21 | 22 | print("Mobile-2") 23 | mob2=Mobile("Samsung",3000) 24 | mob2.purchase() 25 | -------------------------------------------------------------------------------- /markdown-version/iterators-generators.md: -------------------------------------------------------------------------------- 1 | # Iterators and Generators 2 | 3 | ### Iterator 4 | Iterator is an object that can be iterated upon. An object which returns data,one element at a time when next() is called on it. 5 | 6 | ### Iterable 7 | An object which will return an Iterator when `iter()` is called on it. 8 | 9 | For example `"HELLO"` is an iterable but its not an iterator but `iter("HELLO")` returns an iterator. 10 | 11 | ### `NEXT()` 12 | When `next()` is called on an iterator, the iterator returns the next item. It keeps doing so until it raises a `StopIteration` error. 13 | 14 | ```python 15 | def custom_iter(iterable): 16 | iterator = iter(iterable) 17 | while True: 18 | try: 19 | print(next(interator)) 20 | except StopIteration: 21 | print("END") 22 | break 23 | ``` 24 | 25 | ### Generators 26 | - Generators are iterators. 27 | - Generator can be created with generator functions -------------------------------------------------------------------------------- /docs/OOPS/Accessing_pvt_var2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | To have a error free way of accessing and updating private variables, we create specific methods for this. 3 | Those methods which are meant to set a value to a private variable are called setter methods and methods 4 | meant to access private variable values are called getter methods. 5 | 6 | The below code is an example of getter and setter methods: 7 | ''' 8 | 9 | class Customer: 10 | def __init__(self, id, name, age, wallet_balance): 11 | self.id = id 12 | self.name = name 13 | self.age = age 14 | self.__wallet_balance = wallet_balance 15 | 16 | def set_wallet_balance(self, amount): 17 | if amount < 1000 and amount> 0: 18 | self.__wallet_balance = amount 19 | 20 | def get_wallet_balance(self): 21 | return self.__wallet_balance 22 | 23 | c1=Customer(100, "Gopal", 24, 1000) 24 | c1.set_wallet_balance(120) 25 | print(c1.get_wallet_balance()) 26 | -------------------------------------------------------------------------------- /docs/OOPS/Classes and Objects.md: -------------------------------------------------------------------------------- 1 | Objects are real world entities. Anything you can describe in this world is an object. 2 | Classes on the other hand are not real. They are just a concept. Class is a short form of Classification. 3 | A class is a classification of certain objects and it is just a description of the properties and behavior all objects of that classification should possess. 4 | 5 | Class is a like a recipe and the object is like the cupcake we bake using it. 6 | All cupcakes created from a recipe share similar characteristics like shape, sweetness, etc. 7 | But they are all unique as well. One cupcake may have strawberry frosting while another might have vanilla. 8 | Similarly, objects of a class share similar characteristics but they differ in their values for those characteristics. 9 | 10 | A class is defined using the class keyword in python. For example, the below code creates a class called Mobile 11 | without any attributes or behavior. 12 | 13 | class Mobile: 14 | pass 15 | 16 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | ## Python For Beginners 2 | The goal for creating this was to help people who are learning Python. I was already learning Python But then this idea sparked in my mind that why not I should document the process of learning Python and help beginners like me so they don't struggle with topics that I did. 3 | That was the main goal in my mind while creating this repository. 4 | 5 | ## Who this is for 6 | 7 | * This is mainly aimed toward beginners but I will be adding more topics to this and even exercises. 8 | * Anyone can use this repository to study/learn python. 9 | 10 | ## Your Help 11 | * In order to make this better I need your help to add more stuff to it and It can be anything related to python. 12 | * [Repo Link](https://github.com/mraza007/Python-for-beginners) 13 | 14 | 15 | #### Note 16 | * If you liked it please star this repo it will help me motivate to work on this more. 17 | * Feel free to join our chatroom [Chatroom](https://gitter.im/python_4beginners/Lobby#) 18 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Muhammad 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /docs/OOPS/collection_of_objects.py: -------------------------------------------------------------------------------- 1 | ''' 2 | We can also store a number of objects inside a list or a dictionary. 3 | The below example, we have a list of mobile objects and we are iterating over the list and printing the values 4 | ''' 5 | 6 | class Mobile: 7 | def __init__(self, brand, price): 8 | self.brand = brand 9 | self.price = price 10 | 11 | mob1=Mobile("Apple", 1000) 12 | mob2=Mobile("Samsung", 2000) 13 | mob3=Mobile("Apple", 3000) 14 | mob4=Mobile("Samsung", 4000) 15 | mob5=Mobile("Apple", 5000) 16 | 17 | list_of_mobiles=[mob1, mob2, mob3, mob4, mob5] 18 | 19 | for mobile in list_of_mobiles: 20 | print (mobile.brand,mobile.price) 21 | 22 | 23 | 24 | ''' 25 | What do you think will be the output of the below code? 26 | ''' 27 | 28 | class Mobile: 29 | def __init__(self,brand,price): 30 | self.brand = brand 31 | self.price = price 32 | 33 | mob1=Mobile("Apple", 1000) 34 | mob2=Mobile("Samsung", 2000) 35 | mob3=Mobile("Apple", 3000) 36 | 37 | 38 | list_of_mobiles=[mob1, mob2, mob3] 39 | 40 | mob3.brand="Samsung" 41 | 42 | for mobile in list_of_mobiles: 43 | print (mobile.brand, mobile.price) 44 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python For Beginners 2 | This repo is focused towards people who are learning Python for the first time. Therefore I have created this repo to save Python-related notes that will help beginners like me. 3 | 5 | 6 | # Table of Contents 7 | 8 | * [Variables](markdown-version/variables.md) 9 | * [DataTypes](markdown-version/data-types.md) 10 | * [Strings](markdown-version/strings.md) 11 | * [Booleans](markdown-version/booleans.md) 12 | * [Loops](markdown-version/loops.md) 13 | * [Lists](markdown-version/lists.md) 14 | * [Dictionaries](markdown-version/dictionary.md) 15 | * [Tuples & Sets](markdown-version/tuples_and_sets.md) 16 | * [Functions](markdown-version/functions.md) 17 | * [Lambdas](markdown-version/lambdas.md) 18 | * [Debugging](markdown-version/debugging.md) 19 | * [Modules](markdown-version/modules.md) 20 | * [Iterators & Generators](markdown-version/iterators-generators.md) 21 | 22 | ## Additional Sections 23 | * [Object Oriented Programming](docs/OOP) 24 | 25 | 26 | ## Contribute 27 | Feel Free to fork this repo and contribute if you think I missed something important. 28 | This is available under MIT License. 29 | 30 | 31 | If you have any questions dm me on [twitter](http://www.twitter.com/muhammad_o7) I would be happy to help you out with your queries. 32 | 33 | -------------------------------------------------------------------------------- /docs/tuples_and_sets.md: -------------------------------------------------------------------------------- 1 | # Tuples and Sets 2 | * Tuples are different from lists they use parenthesis 3 | * They are immmutable and they can't be change or you can't delete a value from it. 4 | 5 | ```Python 6 | x = (1,2,3,4,5) 7 | #Its a tuple 8 | ``` 9 | 10 | ### Why use a Tuple 11 | * They are faster than a list. 12 | * They are safer less bugs and problems 13 | * You can also use tuples as the keys in dictionary 14 | 15 | ### Different Methods on Tuples 16 | * .count() to see the repetitive element in the list 17 | * .index() 18 | 19 | # Sets in Python 20 | * There is no order and they don't have duplicate values 21 | * You can't use index to access the items because there is no order 22 | 23 | ```Python 24 | set = {1,2,3,4} 25 | # This is how a set looks like 26 | a = set{(1,2,3)} 27 | ``` 28 | 29 | 30 | ### Set Methods 31 | * .add() it is used to add something to a set 32 | * .remove() it is used to remove something from the set 33 | * .discard() It is also used remove the element from the set 34 | * .clear() it removes everything from the set 35 | 36 | ### Mathematical Methods in Sets 37 | * | This symbol represents union 38 | * & This represents intersection 39 | 40 | ```Python 41 | a = {1,2,3,4} 42 | b = {2,3,5} 43 | a | b #This will print {1,2,3,4,5} 44 | a & b # This will print {2,3} 45 | ``` 46 | 47 | 48 | ### Set Comprehension 49 | * basically its like every other comprehension we have seen 50 | ```Python 51 | x = {1,2,3,4} 52 | b = {num+2 for num in x} 53 | ``` 54 | -------------------------------------------------------------------------------- /markdown-version/tuples_and_sets.md: -------------------------------------------------------------------------------- 1 | # Tuples and Sets 2 | * Tuples are different from lists they use parenthesis 3 | * They are immmutable and they can't be change or you can't delete a value from it. 4 | 5 | ```Python 6 | x = (1,2,3,4,5) 7 | #Its a tuple 8 | ``` 9 | 10 | ### Why use a Tuple 11 | * They are faster than a list. 12 | * They are safer less bugs and problems 13 | * You can also use tuples as the keys in dictionary 14 | 15 | ### Different Methods on Tuples 16 | * .count() to see the repetitive element in the list 17 | * .index() 18 | 19 | # Sets in Python 20 | * There is no order and they don't have duplicate values 21 | * You can't use index to access the items because there is no order 22 | 23 | ```Python 24 | set = {1,2,3,4} 25 | # This is how a set looks like 26 | a = set{(1,2,3)} 27 | ``` 28 | 29 | 30 | ### Set Methods 31 | * .add() it is used to add something to a set 32 | * .remove() it is used to remove something from the set 33 | * .discard() It is also used remove the element from the set 34 | * .clear() it removes everything from the set 35 | 36 | ### Mathematical Methods in Sets 37 | * | This symbol represents union 38 | * & This represents intersection 39 | 40 | ```Python 41 | a = {1,2,3,4} 42 | b = {2,3,5} 43 | a | b #This will print {1,2,3,4,5} 44 | a & b # This will print {2,3} 45 | ``` 46 | 47 | 48 | ### Set Comprehension 49 | * basically its like every other comprehension we have seen 50 | ```Python 51 | x = {1,2,3,4} 52 | b = {num+2 for num in x} 53 | ``` 54 | -------------------------------------------------------------------------------- /docs/OOPS/static2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | However, the solution of hardcoding the value in the attribute is not a good one. 3 | For example, since this is a limited time discount we should be able to programmatically 4 | enable and disable the discount using functions like this: 5 | ''' 6 | 7 | 8 | class Mobile: 9 | def __init__(self, price, brand): 10 | self.price = price 11 | self.brand = brand 12 | self.discount = 0 13 | 14 | def purchase(self): 15 | total = self.price - self.price * self.discount / 100 16 | print (self.brand, "mobile with price", self.price, "is available after discount at", total) 17 | 18 | def enable_discount(list_of_mobiles): 19 | for mobile in list_of_mobiles: 20 | mobile.discount=50 21 | 22 | def disable_discount(list_of_mobiles): 23 | for mobile in list_of_mobiles: 24 | mobile.discount=0 25 | 26 | mob1=Mobile(20000, "Apple") 27 | mob2=Mobile(30000, "Apple") 28 | mob3=Mobile(5000, "Samsung") 29 | mob4=Mobile(6000, "Samsung") 30 | 31 | list_of_mobiles=[mob1,mob2,mob3,mob4] 32 | 33 | mob1.purchase() 34 | 35 | enable_discount(list_of_mobiles) 36 | 37 | mob2.purchase() 38 | mob3.purchase() 39 | 40 | disable_discount(list_of_mobiles) 41 | 42 | mob4.purchase() 43 | 44 | 45 | ''' 46 | However, in our current approach, each object has discount as an attribute. 47 | If we change the value for one object, it does not affect the other object. 48 | If we have to change, we have to change for all the objects, one by one. 49 | ''' 50 | -------------------------------------------------------------------------------- /docs/OOPS/Shopping_app.py: -------------------------------------------------------------------------------- 1 | class Mobile: 2 | def __init__(self, brand, price): 3 | print("Inside the Mobile constructor") 4 | self.brand = brand 5 | self.price = price 6 | self.total_price = None 7 | 8 | def purchase(self): 9 | if self.brand == "Apple": 10 | discount = 10 11 | else: 12 | discount = 5 13 | self.total_price = self.price - self.price * discount / 100 14 | print("Total price of", self.brand, "mobile is", self.total_price) 15 | 16 | def return_product(self): 17 | print("Refund Amount for", self.brand, "mobile is", self.total_price) 18 | 19 | class Shoe: 20 | def __init__(self, material, price): 21 | print("Inside the Shoe constructor") 22 | self.material = material 23 | self.price = price 24 | self.total_price = None 25 | 26 | def purchase(self): 27 | if self.material == "leather": 28 | tax = 5 29 | else: 30 | tax = 2 31 | self.total_price = self.price + self.price * tax / 100 32 | print("Total price of", self.material, "shoe is", self.total_price) 33 | 34 | def return_product(self): 35 | print("Refund Amount for", self.material, "shoe is", self.total_price) 36 | 37 | mob1=Mobile("Apple", 20000) 38 | mob2=Mobile("Samsung", 10000) 39 | 40 | shoe1=Shoe("leather",3000) 41 | shoe2=Shoe("canvas",200) 42 | 43 | mob1.purchase() 44 | mob2.purchase() 45 | 46 | shoe1.purchase() 47 | shoe2.purchase() 48 | 49 | mob2.return_product() 50 | 51 | shoe1.return_product() 52 | -------------------------------------------------------------------------------- /docs/data-types.md: -------------------------------------------------------------------------------- 1 | #### Python Data Types 2 | 3 | * Bool: True or False values 4 | * int : It's an integer like 5,3,4 5 | * str : It's a sequence of characters for example "Your name" this is a string 6 | * list : It's an ordered sequence of different data types for example ['1','apple','10.5'] 7 | * tuple : It's an immutable ordered sequence of different data types: ('1', 'apple', '10.5') 8 | * dict : It's a collection of key value pairs {'name':'john'} 9 | * set : It's a collection of unique data: {1, 'apple', 10.5} 10 | * frozenset : It's an immutable collection of unique data: frozenset({1, 'apple', 10.5}) 11 | ```Python 12 | x = true # Boolean 13 | y = "Hello World" # This is a string 14 | numbers = [1, 2, 3, 'four'] # this is a list 15 | letters = ('a', 'b', 'c', 'd') # this is a tuple 16 | v = { 17 | 'name':'john', 18 | 'address':'xyz street' 19 | } # Its a dictionary in python 20 | 21 | my_set = {1, 'apple', 10.5} # this is a set 22 | my_set.add('banana') # this adds 'banana' to my set : my_set = {1, 'apple', 10.5, 'banana'} 23 | my_set.add('apple') # this won't add nothing because apple is already in the set 24 | my_set.remove('apple') # this removes 'apple' from the set: my_set = {1, 10.5, 'banana'} 25 | 26 | my_frozen_set = frozenset(my_set) # this freezes my_set 27 | ``` 28 | 29 | ##### Important Note 30 | * Python is dynamically typed language it means that variable can be changed readily but its different in languages like JAVA, C++ C or etc where we have to specify the variable type thats why they are called statically typed languages 31 | * **None Key Word in Python is just like Null** 32 | * **We can use type() Function to see the data type** 33 | -------------------------------------------------------------------------------- /markdown-version/data-types.md: -------------------------------------------------------------------------------- 1 | #### Python Data Types 2 | 3 | * Bool: True or False values 4 | * int : It's an integer like 5,3,4 5 | * str : It's a sequence of characters for example "Your name" this is a string 6 | * list : It's an ordered sequence of different data types for example ['1','apple','10.5'] 7 | * tuple : It's an immutable ordered sequence of different data types: ('1', 'apple', '10.5') 8 | * dict : It's a collection of key value pairs {'name':'john'} 9 | * set : It's a collection of unique data: {1, 'apple', 10.5} 10 | * frozenset : It's an immutable collection of unique data: frozenset({1, 'apple', 10.5}) 11 | ```Python 12 | x = true # Boolean 13 | y = "Hello World" # This is a string 14 | numbers = [1, 2, 3, 'four'] # this is a list 15 | letters = ('a', 'b', 'c', 'd') # this is a tuple 16 | v = { 17 | 'name':'john', 18 | 'address':'xyz street' 19 | } # Its a dictionary in python 20 | 21 | my_set = {1, 'apple', 10.5} # this is a set 22 | my_set.add('banana') # this adds 'banana' to my set : my_set = {1, 'apple', 10.5, 'banana'} 23 | my_set.add('apple') # this won't add nothing because apple is already in the set 24 | my_set.remove('apple') # this removes 'apple' from the set: my_set = {1, 10.5, 'banana'} 25 | 26 | my_frozen_set = frozenset(my_set) # this freezes my_set 27 | ``` 28 | 29 | ##### Important Note 30 | * Python is dynamically typed language it means that variable can be changed readily but its different in languages like JAVA, C++ C or etc where we have to specify the variable type thats why they are called statically typed languages 31 | * **None Key Word in Python is just like Null** 32 | * **We can use type() Function to see the data type** 33 | -------------------------------------------------------------------------------- /docs/variables.md: -------------------------------------------------------------------------------- 1 | ### Variable in Python 2 | In this section we are going to learn how to represent variables in the Python language. Please note that variables in Python are dynamically typed, which means unlike languages like Java and C++, you don't need to specify whether the variable is a string, integer, etc. 3 | 4 | There are some basic conveniences Python variables provide: 5 | 6 | * Variables can be reassigned at any time 7 | * We can also assign variables together (more on this later) 8 | * We can also assign variables to each other 9 | 10 | ```Python 11 | x = 100 12 | y = 10 13 | all, us , about = 10, 11 ,12 14 | # In this case we have assigned variables at once 15 | print(x+y) # This will print 110 16 | print(us) # To see if it is going to print the us variable that we declared 17 | ``` 18 | #### Variable Naming Conventions 19 | 20 | There are some naming variable conventions used in python language: 21 | 22 | * A variable name cannot start with a number. For instance, if you write something like `2morrow = 'day after'`, Python will complain loudly. 23 | * Variable names are case-sensitive. `total` and `Total` are _not_ the same variable. 24 | * Variables should be snake_case (that is, small caps with words joined by underscores). Please note that this is just a convention in the Python community, as we believe this lends to clearer, easily readable code. 25 | * Camelcase is usually used for class names. For instance, `RssReader`. 26 | * There are some predefined variables in Python that start with dunder (double underscores), for example, `__dir__`. **Don't Touch Them. Ever.** 27 | 28 | ```Python 29 | 2cats = 10 #This is wrong 30 | _cats = 10 #This is totally fine 31 | hey@hey = 10 # This is not good 32 | 33 | cats != CATS 34 | # In this case python language reads them differently 35 | 36 | __dont_touch__ #Dunder Variable 37 | ``` 38 | -------------------------------------------------------------------------------- /markdown-version/variables.md: -------------------------------------------------------------------------------- 1 | ### Variable in Python 2 | In this section we are going to learn how to represent variables in the Python language. Please note that variables in Python are dynamically typed, which means unlike languages like Java and C++, you don't need to specify whether the variable is a string, integer, etc. 3 | 4 | There are some basic conveniences Python variables provide: 5 | 6 | * Variables can be reassigned at any time 7 | * We can also assign variables together (more on this later) 8 | * We can also assign variables to each other 9 | 10 | ```Python 11 | x = 100 12 | y = 10 13 | all, us , about = 10, 11 ,12 14 | # In this case we have assigned variables at once 15 | print(x+y) # This will print 110 16 | print(us) # To see if it is going to print the us variable that we declared 17 | ``` 18 | #### Variable Naming Conventions 19 | 20 | There are some naming variable conventions used in python language: 21 | 22 | * A variable name cannot start with a number. For instance, if you write something like `2morrow = 'day after'`, Python will complain loudly. 23 | * Variable names are case-sensitive. `total` and `Total` are _not_ the same variable. 24 | * Variables should be snake_case (that is, small caps with words joined by underscores). Please note that this is just a convention in the Python community, as we believe this lends to clearer, easily readable code. 25 | * Camelcase is usually used for class names. For instance, `RssReader`. 26 | * There are some predefined variables in Python that start with dunder (double underscores), for example, `__dir__`. **Don't Touch Them. Ever.** 27 | 28 | ```Python 29 | 2cats = 10 #This is wrong 30 | _cats = 10 #This is totally fine 31 | hey@hey = 10 # This is not good 32 | 33 | cats != CATS 34 | # In this case python language reads them differently 35 | 36 | __dont_touch__ #Dunder Variable 37 | ``` 38 | -------------------------------------------------------------------------------- /markdown-version/debugging.md: -------------------------------------------------------------------------------- 1 | # Debugging Python Code 2 | - Try and Else Block 3 | - Pdb 4 | - set trace method 5 | 6 | ## Common Python Errors 7 | - `SyntaxError` 8 | - `NameError` This usually occurs when a variable is not defined or it hasn't been assigned yet. 9 | - `TypeError` This usually occurs when an operation or function is applied to a wrong type. 10 | - `IndexError` This occurs when we are trying to access an element in a list using invalid index. 11 | - `ValueError` This occurs when a built in operation or function receives an arguement that has the right type but an inappropiate value 12 | - `KeyError` This occurs when a dictionary doesn't have a specific key. 13 | - `AttributeError` This occurs when a variable doesn't have an attribute. 14 | 15 | ## Raising Our own Exceptions 16 | - We can raise our own error exceptions 17 | 18 | ```python 19 | raise ValueError('invalid Error') 20 | ``` 21 | 22 | - Lets say we have a simple function and we want it to have our own exception. 23 | 24 | ```python 25 | def color(text,color): 26 | if type(text) is not str: 27 | raise TypeError('Enter a valid String') 28 | print(f'This {text} is using {color}.') 29 | ``` 30 | 31 | ## Handling Errors 32 | - In python we can handle errors using `try` and `except` 33 | 34 | ```python 35 | try: 36 | x 37 | except ValueError: 38 | print("there's a error") 39 | ``` 40 | 41 | `Else` and `Finally`. 42 | `Finally` would run no matter what. 43 | 44 | ```python 45 | # a small program 46 | try: 47 | x = int(input("Enter a number")) 48 | except: 49 | print("Enter a valid Number") 50 | else: 51 | print("Thanks for a valid number") 52 | finally: 53 | print("I will run no matter what hehehe") 54 | ``` 55 | 56 | ## Debugging our code using `PDB` 57 | 58 | - In order to set a breakpoint we use `pdb.set_trace()` 59 | - After setting a breakpoint then we can go line by line through our code. 60 | 61 | #### Common `PDB` commands 62 | - `l` List 63 | - `n` next line 64 | - `p` print 65 | - `c` continue 66 | -------------------------------------------------------------------------------- /markdown-version/modules.md: -------------------------------------------------------------------------------- 1 | # Modules 2 | Python modules allows us to reuse our own code or sometimes use somebody else's code. 3 | We can write our own modules or we can use modules written by someone else like `requests`,`datetime` and `etc`. 4 | 5 | **Note**: It's just a `python` file. 6 | 7 | ## Built-in Modules 8 | There built-in python modules that come by default. 9 | List can be found here [LIST OF MODULES](https://docs.python.org/3/py-modindex.html) 10 | 11 | - We can import modules by using `import` keyword 12 | - We can also give modules an `alias` when we have long module names like `import random as r`. 13 | - We can also import few functions from the modules `from random import randint`. 14 | - If you want to import everything from random we do something like this `from random import *` 15 | 16 | ## Custom Modules 17 | Custom module is just file with python code. 18 | 19 | ##### For Example 20 | 21 | ```python 22 | # file1.py 23 | def hello(): 24 | return "Hello" 25 | def hey(name): 26 | return f'Hey {name}' 27 | ``` 28 | 29 | ```python 30 | # Importing a custom module 31 | import file1 as fn 32 | fn.hello() 33 | fn.hey('Jake') 34 | ``` 35 | 36 | ## External Modules 37 | External modules can be found here [PyPi](https://pypi.org/) 38 | - We can install modules using `pip`, `pip install `. 39 | - Pip comes default in `Python 3.4` we can run using `python3 -m pip install `. 40 | - `print(dir())` This tells us about the attributes. 41 | - `print(help(package_name))` This tells us everything about the package 42 | 43 | ## Using PEP8 to cleanup Code 44 | 45 | - We can use `autopep8` to fix whitespaces and ident our code 46 | - We can use `autopep8 --in-place ` 47 | 48 | 49 | ## The `__name__` variable 50 | - The `__name__` variable usually refers to the file name if its the file then it will interpreted as `__main__` 51 | - If it's a module then `__name__` will be interpreted as the `__file_name__`. 52 | 53 | **Note** : use `if __name__ = '__main__' ` 54 | -------------------------------------------------------------------------------- /docs/OOPS/What_is_self(full).py: -------------------------------------------------------------------------------- 1 | ''' 2 | 3 | 4 | 5 | self is not a keyword. self refers to the current object being executed. 6 | ''' 7 | 8 | class Mobile: 9 | def __init__(self, price, brand): 10 | print("Id of self in constructor", id(self)) 11 | self.price = price 12 | self.brand = brand 13 | 14 | mob1=Mobile(1000, "Apple") 15 | print("Id of mob1 in driver code", id(mob1)) 16 | 17 | mob2=Mobile(1000, "Apple") 18 | print("Id of mob2 in driver code", id(mob2)) 19 | 20 | 21 | 22 | ''' 23 | 24 | 25 | 26 | We have already seen that reference_variable.attribute_name creates an attribute for that object. 27 | By using self.attribute_name and assigning a value we are creating attributes to the current object. 28 | The best practice is to create attributes inside the constructor. 29 | ''' 30 | 31 | class Mobile: 32 | def __init__(self, price, brand): 33 | print("Id of self in constructor", id(self)) 34 | self.price = price 35 | self.brand = brand 36 | 37 | mob1=Mobile(1000, "Apple") 38 | print("Id of mob1 in driver code", id(mob1)) 39 | 40 | mob2=Mobile(1000, "Apple") 41 | print("Id of mob2 in driver code", id(mob2)) 42 | 43 | 44 | 45 | ''' 46 | 47 | 48 | 49 | Attributes can be created only by using the self variable and the dot operator. 50 | Without self we are only creating a local variable and not an attribute. 51 | ''' 52 | 53 | class Mobile: 54 | def __init__(self): 55 | print ("Inside the Mobile constructor") 56 | self.brand = None 57 | brand = "Apple" #This is a local variable. 58 | #Variables without self are local and they dont 59 | #affect the attributes. 60 | 61 | #Local varaibles cannot be accessed outside the init 62 | #Using self creates attributes which are 63 | #accessible in other methods as well 64 | 65 | mob1=Mobile() 66 | print(mob1.brand)#This does not print Apple 67 | #This prints None because brand=Apple creates 68 | #a local variable and it does not affect the attribute 69 | -------------------------------------------------------------------------------- /docs/strings.md: -------------------------------------------------------------------------------- 1 | ### Strings in Python 2 | * Strings in python can be in either double quotes or single quotes 3 | ```Python 4 | my_str = 'Hello World' 5 | string = "Hello" 6 | ``` 7 | 8 | #### String Concatenation 9 | * We Concatenate strings using **+** operator 10 | ```Python 11 | str1 = 'Hello' 12 | str2 = 'World' 13 | print(str1+str2) 14 | #This will print out Hello World 15 | ``` 16 | * You cannot concatenate strings with integers 17 | 18 | ```Python 19 | 8 + 'hello' 20 | # This will give an error 21 | but we can do this using an str() function and it will convert the the int into str then you can concatenate 22 | ``` 23 | 24 | * You can also use the **+=** operator to concatenate strings 25 | 26 | ```Python 27 | string = "Cat" 28 | string += " Dogs" 29 | print(string) 30 | #This will print out Cat Dogs 31 | ``` 32 | 33 | #### Formatting Strings 34 | There's a new method to interpolate the strings 35 | * The method is called the F-strings this will help you convert the int value into a string 36 | ```Python 37 | x = 10 38 | print(f"I have told you " {x} times to clean the floor correctly") 39 | # This will print I have told you 10 times to clean the floor correctly 40 | # This a new way of interpolating string 41 | y = 'I have told you {x} times to clean the floor correctly'.format(x) 42 | # This an old way of doing it and its applicable in python 2.7 43 | ``` 44 | 45 | #### String Index 46 | ```Python3 47 | x = "Hello" 48 | print(x[0]) 49 | #This will print out H 50 | # [] We use this for index 51 | # This is useful for lists 52 | ``` 53 | 54 | #### Converting DataTypes 55 | * We use built-in functions to convert the data types. 56 | * For example int() str() float() 57 | * int () this is a built-in function that is used to convert a number into an integer. 58 | * float() This is used to convert the number into a float 59 | * str() This is used to convert to a string 60 | **Note: We used input() function to get the user input** 61 | ```Python3 62 | x = input('What is your age') #this will prompt to the user 63 | print(x) # whatever user types it will be printed out 64 | ``` 65 | -------------------------------------------------------------------------------- /markdown-version/strings.md: -------------------------------------------------------------------------------- 1 | ### Strings in Python 2 | * Strings in python can be in either double quotes or single quotes 3 | ```Python 4 | my_str = 'Hello World' 5 | string = "Hello" 6 | ``` 7 | 8 | #### String Concatenation 9 | * We Concatenate strings using **+** operator 10 | ```Python 11 | str1 = 'Hello' 12 | str2 = 'World' 13 | print(str1+str2) 14 | #This will print out Hello World 15 | ``` 16 | * You cannot concatenate strings with integers 17 | 18 | ```Python 19 | 8 + 'hello' 20 | # This will give an error 21 | but we can do this using an str() function and it will convert the the int into str then you can concatenate 22 | ``` 23 | 24 | * You can also use the **+=** operator to concatenate strings 25 | 26 | ```Python 27 | string = "Cat" 28 | string += " Dogs" 29 | print(string) 30 | #This will print out Cat Dogs 31 | ``` 32 | 33 | #### Formatting Strings 34 | There's a new method to interpolate the strings 35 | * The method is called the F-strings this will help you convert the int value into a string 36 | ```Python 37 | x = 10 38 | print(f"I have told you {x} times to clean the floor correctly") 39 | # This will print I have told you 10 times to clean the floor correctly 40 | # This a new way of interpolating string 41 | y = 'I have told you {x} times to clean the floor correctly'.format(x) 42 | # This an old way of doing it and its applicable in **python 2.7** 43 | ``` 44 | 45 | #### String Index 46 | ```Python3 47 | x = "Hello" 48 | print(x[0]) 49 | #This will print out H 50 | # [] We use this for index 51 | # This is useful for lists 52 | ``` 53 | 54 | #### Converting DataTypes 55 | * We use built-in functions to convert the data types. 56 | * For example int() str() float() 57 | * int () this is a built-in function that is used to convert a number into an integer. 58 | * float() This is used to convert the number into a float 59 | * str() This is used to convert to a string 60 | **Note: We used input() function to get the user input** 61 | ```Python3 62 | x = input('What is your age') #this will prompt to the user 63 | print(x) # whatever user types it will be printed out 64 | ``` 65 | -------------------------------------------------------------------------------- /docs/loops.md: -------------------------------------------------------------------------------- 1 | ### Loops in Python 2 | * What loops are in Python 3 | * While loops and For Loops in Python 4 | 5 | ### For Loops 6 | * They can be used to iterate the number of elements in the lists, 7 | * They can also be used to iterate the strings 8 | * range function is used to iterate through numbers 9 | ```Python3 10 | for item in iterable_object: 11 | print(item) 12 | # This is the syntax for loops in python 13 | # Item represents the iterator's position 14 | # You can call it anything you want 15 | # printing numbers using for loops 16 | for number in range(1,100): 17 | print(number) 18 | # This will print numbers from 1 to 99 19 | for letter in "Hello": 20 | print(letter) 21 | # This for loop will print out the characters in the word hello 22 | ``` 23 | 24 | #### Ranges 25 | * They are usually used with for loops 26 | * range(7) if we give in one parameter this will only print out numbers 0 to 6 27 | * range(1,8) if we give in two parameters this will print out numbers 1 to 7 28 | * range(1,10,2) In this example the thir parameter is used to tell how many steps should be skipped and this will print odd numbers 29 | * range helps you generate the sequence of number its a python built in function 30 | 31 | ```Python3 32 | x = input('How many times I have told you clean the room ') 33 | y = int(x) 34 | for time in range(y): 35 | print(f'{time}: Clean Your room') 36 | # A simple example of loops 37 | 38 | ``` 39 | 40 | ### While Loops 41 | * While loops are just like for loops 42 | * While loops only run if the conditional statement is true otherwise it will stop 43 | ```Python3 44 | while some_condition: 45 | #do this 46 | # An example 47 | user_input = None 48 | while user_input != 'please': 49 | print('Sorry Access Denied') 50 | ``` 51 | * We need to be careful with while loops since they will continue forever if the condition is not true **It will ruin the program** 52 | 53 | ```Python3 54 | #Another While Loop Example 55 | num = 0 56 | while num < 10: 57 | num +=1 58 | print(num) 59 | ``` 60 | 61 | 62 | #### Importance of Break keyword in Python 63 | * It gives us the ability to get out of the loop 64 | ```Python 65 | while True: 66 | command = input('Type exit to get out of this') 67 | if command == 'exit': 68 | break 69 | 70 | 71 | for x in range(1,10): 72 | if x == 3: 73 | break 74 | ``` -------------------------------------------------------------------------------- /markdown-version/loops.md: -------------------------------------------------------------------------------- 1 | ### Loops in Python 2 | * What loops are in Python 3 | * While loops and For Loops in Python 4 | 5 | ### For Loops 6 | * They can be used to iterate the number of elements in the lists, 7 | * They can also be used to iterate the strings 8 | * range function is used to iterate through numbers 9 | ```Python3 10 | for item in iterable_object: 11 | print(item) 12 | # This is the syntax for loops in python 13 | # Item represents the iterator's position 14 | # You can call it anything you want 15 | # printing numbers using for loops 16 | for number in range(1,100): 17 | print(number) 18 | # This will print numbers from 1 to 99 19 | for letter in "Hello": 20 | print(letter) 21 | # This for loop will print out the characters in the word hello 22 | ``` 23 | 24 | #### Ranges 25 | * They are usually used with for loops 26 | * range(7) if we give in one parameter this will only print out numbers 0 to 6 27 | * range(1,8) if we give in two parameters this will print out numbers 1 to 7 28 | * range(1,10,2) In this example the thir parameter is used to tell how many steps should be skipped and this will print odd numbers 29 | * range helps you generate the sequence of number its a python built in function 30 | 31 | ```Python3 32 | x = input('How many times I have told you clean the room ') 33 | y = int(x) 34 | for time in range(y): 35 | print(f'{time}: Clean Your room') 36 | # A simple example of loops 37 | 38 | ``` 39 | 40 | ### While Loops 41 | * While loops are just like for loops 42 | * While loops only run if the conditional statement is true otherwise it will stop 43 | ```Python3 44 | while some_condition: 45 | #do this 46 | # An example 47 | user_input = None 48 | while user_input != 'please': 49 | print('Sorry Access Denied') 50 | ``` 51 | * We need to be careful with while loops since they will continue forever if the condition is not true **It will ruin the program** 52 | 53 | ```Python3 54 | #Another While Loop Example 55 | num = 0 56 | while num < 10: 57 | num +=1 58 | print(num) 59 | ``` 60 | 61 | 62 | #### Importance of Break keyword in Python 63 | * It gives us the ability to get out of the loop 64 | ```Python 65 | while True: 66 | command = input('Type exit to get out of this') 67 | if command == 'exit': 68 | break 69 | 70 | 71 | for x in range(1,10): 72 | if x == 3: 73 | break 74 | ``` -------------------------------------------------------------------------------- /docs/booleans.md: -------------------------------------------------------------------------------- 1 | #### Booleans and Conditionals 2 | ```Python3 3 | # A psuedo code example 4 | if some condition is true: 5 | do this 6 | elif Some other condition is true: 7 | Do this 8 | else: 9 | do something else 10 | 11 | ``` 12 | 13 | ```Python3 14 | # A real example of Conditonals 15 | if x == 5: 16 | print('Five') 17 | elif x == 6: 18 | print('Six') 19 | else: 20 | print('Nothing is valid') 21 | ``` 22 | 23 | #### Falsiness and Truthiness 24 | * This really matter 25 | * Empty strings, None , 0 has a false value 26 | * Everything else has true value 27 | ```Python 28 | x = input('Whats your favorite TV Show') 29 | if x: 30 | print('Wow I like that too !') 31 | else: 32 | print('You have entered nothing') 33 | # This is an example of the truthiness and falsiness 34 | # if user enters nothing it will print out nothing 35 | ``` 36 | 37 | #### Comparison Operators 38 | 39 | | Op | What it does | Example | 40 | | ------------- | ------------- | ------------- | 41 | | == | Truthy if a has the same value as b | a == b # True 42 | | != | Truthy if a does NOT have the same value as b | a != b # False 43 | | > | Truthy if a is greater than b | a > b # False 44 | | < | Truthy if a is less than be b | a < b # False 45 | | >= | Truthy if a is greater than or equal to b | a >= b # True 46 | | <= | Truthy if a is less than or equal to b | a <= b # True 47 | 48 | #### Logical Operators 49 | | Operator | What it does | 50 | | ------------- | ------------- | 51 | | And | Both values have to be true in order to be true | 52 | | Or | If one of the value is true then the entire thing is true | 53 | | Not | Its is like negation | 54 | 55 | ```Python3 56 | state = input('Enter the state where you live') 57 | if state == 'NJ' or state == 'NY': 58 | print('You live close to East Coast') 59 | else: 60 | print('You live far away from the coast') 61 | # In this one of them has to be true 62 | ``` 63 | 64 | ```Python3 65 | #Not operator Example 66 | age = 10 67 | not age < 5 68 | # This will be true 69 | ``` 70 | 71 | #### is vs == 72 | * is and == operators are not the same 73 | * is operator compares two things and checks if they are stored at the same location in the memory 74 | * == operator checks if both values are true 75 | 76 | ```Python3 77 | a = [1,2,3] 78 | b = [1,2,3] 79 | a == b #returns true 80 | a is b # returns false 81 | ``` 82 | **Indentation really matters in Python Language and (:) These colons help us indent the blocks** 83 | **You can have multiple (elifs)** -------------------------------------------------------------------------------- /markdown-version/booleans.md: -------------------------------------------------------------------------------- 1 | #### Booleans and Conditionals 2 | ```Python3 3 | # A psuedo code example 4 | if some condition is true: 5 | do this 6 | elif Some other condition is true: 7 | Do this 8 | else: 9 | do something else 10 | 11 | ``` 12 | 13 | ```Python3 14 | # A real example of Conditonals 15 | if x == 5: 16 | print('Five') 17 | elif x == 6: 18 | print('Six') 19 | else: 20 | print('Nothing is valid') 21 | ``` 22 | 23 | #### Falsiness and Truthiness 24 | * This really matter 25 | * Empty strings, None , 0 has a false value 26 | * Everything else has true value 27 | ```Python 28 | x = input('Whats your favorite TV Show') 29 | if x: 30 | print('Wow I like that too !') 31 | else: 32 | print('You have entered nothing') 33 | # This is an example of the truthiness and falsiness 34 | # if user enters nothing it will print out nothing 35 | ``` 36 | 37 | #### Comparison Operators 38 | 39 | | Op | What it does | Example | 40 | | ------------- | ------------- | ------------- | 41 | | == | Truthy if a has the same value as b | a == b # True 42 | | != | Truthy if a does NOT have the same value as b | a != b # False 43 | | > | Truthy if a is greater than b | a > b # False 44 | | < | Truthy if a is less than be b | a < b # False 45 | | >= | Truthy if a is greater than or equal to b | a >= b # True 46 | | <= | Truthy if a is less than or equal to b | a <= b # True 47 | 48 | #### Logical Operators 49 | | Operator | What it does | 50 | | ------------- | ------------- | 51 | | And | Both values have to be true in order to be true | 52 | | Or | If one of the value is true then the entire thing is true | 53 | | Not | Its is like negation | 54 | 55 | ```Python3 56 | state = input('Enter the state where you live') 57 | if state == 'NJ' or state == 'NY': 58 | print('You live close to East Coast') 59 | else: 60 | print('You live far away from the coast') 61 | # In this one of them has to be true 62 | ``` 63 | 64 | ```Python3 65 | #Not operator Example 66 | age = 10 67 | not age < 5 68 | # This will be true 69 | ``` 70 | 71 | #### is vs == 72 | * is and == operators are not the same 73 | * is operator compares two things and checks if they are stored at the same location in the memory 74 | * == operator checks if both values are true 75 | 76 | ```Python3 77 | a = [1,2,3] 78 | b = [1,2,3] 79 | a == b #returns true 80 | a is b # returns false 81 | ``` 82 | **Indentation really matters in Python Language and (:) These colons help us indent the blocks** 83 | **You can have multiple (elifs)** -------------------------------------------------------------------------------- /docs/lambdas.md: -------------------------------------------------------------------------------- 1 | # Lambdas Functions in Python 2 | Lambdas are one line functions. They are also known as anonymous functions in some other languages. You might want to use lambdas when you don’t want to use a function twice in a program. They are just like normal functions and even behave like them. 3 | 4 | ```python3 5 | def square(x): 6 | return x * x 7 | # But Lamdas are totally different 8 | 9 | square = lambda x:x*x 10 | print(square(2)) 11 | # You can also store lamda inside of a variable 12 | # In this case we are passing x as an parameter. Basically they are short and # anonymous functions 13 | # Lambdas don't have a name' 14 | ``` 15 | 16 | #### Map() function in Lambdas 17 | * It's a standard function that accepts at least two arguements a function and an iterable 18 | * Iterable can be lists tuples or dictionary 19 | * Runs lambda for each value and then returns 20 | ```python3 21 | nums = [1,2,3,4,5] 22 | x = map(lambda x:x*x,nums) 23 | print(list(x)) 24 | # This shows how map() function works. We are passing lamda function that will square each number in the list nums 25 | ``` 26 | 27 | #### filter() Function 28 | * It takes a list/tuple and filters based on the given condition 29 | * The lambda function needs to be a boolean it can be either true or false 30 | ```python3 31 | x = [1,2,3,4,5,6,7,8] 32 | names = ['alex','john','aneesa','aidan','amina','jill','jackson'] 33 | data = [ 34 | {'username' : 'alex_1'}, 35 | {'username' : 'axis_07'}, 36 | {'username' : 'aaa'}, 37 | {'username' : 'asthetic'}, 38 | {'username' : 'bob'}, 39 | {'username' : 'jason_07'}, 40 | {'username' : 'razer_07'}, 41 | {'username' : 'pythonista'} 42 | ] 43 | # A function that will print the usernames with more than 4 characters 44 | usernames = list(filter(lambda u:len(u['username']) > 4 , data)) 45 | for name in usernames: 46 | print(name['username']) 47 | 48 | # A new list with the multiples of two and less than 10 49 | print('\n') 50 | new_list = list(map(lambda num: num*2, filter(lambda num: num < 6 ,x))) 51 | print(new_list) 52 | print('\n') 53 | for nums in new_list: 54 | print(nums) 55 | 56 | # filter names starting with J and adding them to group 1 and names starting with a goes to group_2 57 | 58 | group_1 = filter(lambda n:n[0]=='j',names) 59 | print(list(group_1)) 60 | 61 | group_2 = filter(lambda n:n[0]=='a',names) 62 | print(list(group_2)) 63 | 64 | # We can also use the list comprehension but it's better to understand how the map() and filter() works 65 | ``` 66 | 67 | #### Any() and all() built in function 68 | * all() takes the iterables and return of they are true or not 69 | ```python 70 | list = [1,2,3,4] 71 | all(list) 72 | #This will return true since all the values are true 73 | # You can also check if all numbers are divisible by two in list 74 | ``` 75 | 76 | Lets say you want to check if every name started in the list with the character C 77 | 78 | ```python 79 | list = ['Casey','Charlie','Courtney','Cashmere'] 80 | x = [name[0] == 'C' for name in list] 81 | print(all(x)) 82 | #This will return True since every name starts with C 83 | ``` -------------------------------------------------------------------------------- /docs/dictionary.md: -------------------------------------------------------------------------------- 1 | ### Dictionaries in Python 2 | * Dictionaries vs List. Lists have its own limitations like it can contain one data type and data can't be modeled correctly if we are using lists 3 | * Dictionary is a data structure that contains key value pairs 4 | * Keys are used to describe the data 5 | * Values are used to represent the data 6 | 7 | #### This is how a dictionary looks like 8 | **Note: key-value pairs are separated by the commas ** 9 | 10 | ```Python 11 | info = { 12 | 'name':'John', 13 | 'city':'New York', 14 | 'own_a_car':True, 15 | } 16 | #We can also use the dict() built in python function to generate keys 17 | x = dict(name='John',age='21') 18 | print(x) 19 | #This will print x 20 | { 21 | 'name':'John' 22 | 'age':'24' 23 | } 24 | ``` 25 | 26 | * To access the values in the dictionary we pass in the value 27 | 28 | ```Python 29 | info = { 30 | 'name':'John', 31 | 'city':'New York', 32 | 'own_a_car':True, 33 | } 34 | info['name'] #This will print John 35 | ``` 36 | 37 | * To iterate values and keys at once we use this function .keys() and .values() 38 | 39 | ```Python 40 | info = { 41 | 'name':'John', 42 | 'city':'New York', 43 | 'own_a_car':True, 44 | } 45 | for x in info.keys(): #This will print keys 46 | print(x) 47 | print(' ') 48 | for y in info.values(): #This will print valuesq 49 | print(y) 50 | ``` 51 | 52 | * To iterate both values and keys together we use .items() 53 | ```Python 54 | info = { 55 | 'name':'John', 56 | 'city':'New York', 57 | 'own_a_car':True, 58 | } 59 | for keys,values in info.items(): 60 | print(keys,values) 61 | #This will print keys and values 62 | ``` 63 | 64 | #### To check if keys and values are present in the dictionary 65 | 66 | ```Python 67 | info = { 68 | 'name':'John', 69 | 'city':'New York', 70 | 'own_a_car':True, 71 | } 72 | name in info 73 | # This will print true because name is key in info 74 | 75 | John in info.values() 76 | #This will also print true because its present in the dictionary 77 | ``` 78 | 79 | ### Dictionary Methods 80 | * .clear() method clears the entire dictionary 81 | * .copy() makes the entire copy of the list 82 | * .fromkeys([]) 83 | 84 | ```Python 85 | info = { 86 | 'name':'John', 87 | 'city':'New York', 88 | 'own_a_car':True, 89 | } 90 | info.clear() # This will clear the whole dictionary 91 | a = info.copy() 92 | print(a) 93 | #This will print the entire info dictionary 94 | 95 | new_user = {}.fromkeys(['name','email','city'],'False') 96 | # This will create a new dictionary 97 | new_user = { 98 | 'name':'False' 99 | 'email':'False' 100 | 'city':'False' 101 | } 102 | ``` 103 | 104 | * .get() is used to retrieve the value from the dictionary 105 | 106 | ```Python 107 | info = { 108 | 'name':'John', 109 | 'city':'New York', 110 | 'own_a_car':True, 111 | } 112 | info.get('name') 113 | #This will print John 114 | ``` 115 | 116 | ### More Dictionary Methods 117 | 118 | * .pop() In this method we have to provide the key 119 | * .popitem()removes a random key in the dictionary 120 | * .update() 121 | 122 | ### Dictionary Comprehension 123 | * They use the same syntax like the lists we just use the dictionary brackets 124 | * It will iterate over keys by default by we can use the .items() to iterate over values too 125 | 126 | ```Python 127 | a = dict(a=1,b=2,c=3,d=4) 128 | b = {key:value **2 for key,value in a.items()} 129 | #This will print out the the square of each number in b 130 | # This will allow us to make dictionaries out of a dictionary that's one of the reason we use the dictionary comprehension. 131 | #Another example of dictionary comprehension. 132 | c = {key:value+2 for key,value in a.items()} 133 | 134 | ``` -------------------------------------------------------------------------------- /markdown-version/dictionary.md: -------------------------------------------------------------------------------- 1 | ### Dictionaries in Python 2 | * Dictionaries vs List. Lists have its own limitations like it can contain one data type and data can't be modeled correctly if we are using lists 3 | * Dictionary is a data structure that contains key value pairs 4 | * Keys are used to describe the data 5 | * Values are used to represent the data 6 | 7 | #### This is how a dictionary looks like 8 | **Note: key-value pairs are separated by the commas ** 9 | 10 | ```Python 11 | info = { 12 | 'name':'John', 13 | 'city':'New York', 14 | 'own_a_car':True, 15 | } 16 | #We can also use the dict() built in python function to generate keys 17 | x = dict(name='John',age='21') 18 | print(x) 19 | #This will print x 20 | { 21 | 'name':'John' 22 | 'age':'24' 23 | } 24 | ``` 25 | 26 | * To access the values in the dictionary we pass in the value 27 | 28 | ```Python 29 | info = { 30 | 'name':'John', 31 | 'city':'New York', 32 | 'own_a_car':True, 33 | } 34 | info['name'] #This will print John 35 | ``` 36 | 37 | * To iterate values and keys at once we use this function .keys() and .values() 38 | 39 | ```Python 40 | info = { 41 | 'name':'John', 42 | 'city':'New York', 43 | 'own_a_car':True, 44 | } 45 | for x in info.keys(): #This will print keys 46 | print(x) 47 | print(' ') 48 | for y in info.values(): #This will print valuesq 49 | print(y) 50 | ``` 51 | 52 | * To iterate both values and keys together we use .items() 53 | ```Python 54 | info = { 55 | 'name':'John', 56 | 'city':'New York', 57 | 'own_a_car':True, 58 | } 59 | for keys,values in info.items(): 60 | print(keys,values) 61 | #This will print keys and values 62 | ``` 63 | 64 | #### To check if keys and values are present in the dictionary 65 | 66 | ```Python 67 | info = { 68 | 'name':'John', 69 | 'city':'New York', 70 | 'own_a_car':True, 71 | } 72 | name in info 73 | # This will print true because name is key in info 74 | 75 | John in info.values() 76 | #This will also print true because its present in the dictionary 77 | ``` 78 | 79 | ### Dictionary Methods 80 | * .clear() method clears the entire dictionary 81 | * .copy() makes the entire copy of the list 82 | * .fromkeys([]) 83 | 84 | ```Python 85 | info = { 86 | 'name':'John', 87 | 'city':'New York', 88 | 'own_a_car':True, 89 | } 90 | info.clear() # This will clear the whole dictionary 91 | a = info.copy() 92 | print(a) 93 | #This will print the entire info dictionary 94 | 95 | new_user = {}.fromkeys(['name','email','city'],'False') 96 | # This will create a new dictionary 97 | new_user = { 98 | 'name':'False' 99 | 'email':'False' 100 | 'city':'False' 101 | } 102 | ``` 103 | 104 | * .get() is used to retrieve the value from the dictionary 105 | 106 | ```Python 107 | info = { 108 | 'name':'John', 109 | 'city':'New York', 110 | 'own_a_car':True, 111 | } 112 | info.get('name') 113 | #This will print John 114 | ``` 115 | 116 | ### More Dictionary Methods 117 | 118 | * .pop() In this method we have to provide the key 119 | * .popitem()removes a random key in the dictionary 120 | * .update() 121 | 122 | ### Dictionary Comprehension 123 | * They use the same syntax like the lists we just use the dictionary brackets 124 | * It will iterate over keys by default by we can use the .items() to iterate over values too 125 | 126 | ```Python 127 | a = dict(a=1,b=2,c=3,d=4) 128 | b = {key:value **2 for key,value in a.items()} 129 | #This will print out the the square of each number in b 130 | # This will allow us to make dictionaries out of a dictionary that's one of the reason we use the dictionary comprehension. 131 | #Another example of dictionary comprehension. 132 | c = {key:value+2 for key,value in a.items()} 133 | 134 | ``` -------------------------------------------------------------------------------- /markdown-version/lists.md: -------------------------------------------------------------------------------- 1 | ## Lists in Python 2 | * Lists is a way of combining different data structures.Its is more like grouping elements together. 3 | * They are usually becuase they make your code more readable. 4 | ```Python 5 | x = [1,2,3,4,'five'] 6 | #This is how a list looks like 7 | # They can hold different data such as numbers strings and floats 8 | # Values in the lists are seperated by the commas 9 | ``` 10 | 11 | ### List built in Functions 12 | * Len() This function tells how many items are there in the list 13 | ```Python 14 | x = ['one,'two','three'] 15 | print(len(x)) 16 | # This will printout the number of items present in the list 17 | ``` 18 | * list() function converts to list 19 | ```Python 20 | x = range(1,4) 21 | print(list(x)) 22 | # this print [1,2,3] 23 | ``` 24 | 25 | ### Different way of accessing the data in the lists 26 | * Every element in the list starts at 0 27 | * You can also use negative numbers but it will get the data from backwards 28 | ```Python 29 | x = ['john','jason','tony'] 30 | print(x[0]) # This will john 31 | print(x[1]) # This will jason 32 | print(x[2]) # This will tony 33 | ``` 34 | 35 | * We use built in python **in** keyword to see if the item exists in the list 36 | ```Python 37 | x = [1,2,3] 38 | 1 in x 39 | # this will print true 40 | 4 in x 41 | #this will print false because 4 is not in the list 42 | ``` 43 | 44 | ### We can also iterate throught the list using loops 45 | ```Python 46 | list = ['blue','yellow','green','orange','black'] 47 | for color in list: 48 | print(list) 49 | # Using while loop 50 | i = 0 51 | while i < len(list): 52 | print(list[i]) 53 | i += 1 54 | #len() function tells us how many items are there in the list 55 | ``` 56 | **Note: len() can also be used on the strings** 57 | ### List Methods 58 | * Built-in python list methods 59 | 60 | #### These methods are used to add items to the list 61 | * append () this method will add the item to the end of the list. 62 | * extend() this method adds all the values at the end of the list 63 | ```Python 64 | x = [1,2,3,4,5] 65 | x.append([5,6,7,8]) 66 | # This print [1,2,3,4,5,[5,6,7,8]] 67 | #Lets use the extend method on this 68 | x.extend([5,6,7,8,9]) 69 | #This will print out [1,2,3,4,5,5,6,7,8,9] 70 | ``` 71 | * if want to add one item to the end of the list use append() if you are adding more than one item use extend() 72 | * insert() method is used to add the item to the given position in the list 73 | ```Python 74 | x = [1,2,3,4] 75 | x.insert(1,'hi') 76 | [1,'hi',2,3,4] 77 | ``` 78 | 79 | #### Methods that are used to delete items from the list 80 | * clear() method will remove all the items in the list at once 81 | * pop() method removes the element at the given position 82 | ```Python 83 | x = [1,2,3,4] 84 | x.pop()# this will remove the last item by default 85 | x.pop(1) 86 | #this will remove the item at index [1] 87 | ``` 88 | * remove() method this takes in the value 89 | ```Python 90 | x = [1,2,3,4] 91 | x.remove(1) 92 | #this will remove 1 in the list 93 | [2,3,4] 94 | ``` 95 | 96 | #### Other List Methods 97 | * index() 98 | * count(), This method is used to count the duplicates in the list 99 | * reverse () this will reverse the list. This doesn't take arguements 100 | * sort() This function will sort the list in ascending order' 101 | * .join () this is string method **Only works if there are strings in the lists** 102 | ```Python 103 | x = [1,'hi',2,3,4] 104 | x.index(1) 105 | #this will print the index of the 1 which is 0 106 | x = [1,1,2,3,4,5] 107 | x.count(1) 108 | #This will check if the element is being repeated 109 | x.reverse() 110 | #This method will reverse the list 111 | # the output is going to be like [4,3,2,'hi',1] 112 | x = [3,2,4,1] 113 | x.sort() 114 | #This will sort out the list 115 | # The output will be [1,2,3,4] 116 | x = ['1','2','3'] 117 | ' '.join(x) 118 | #Output 1 2 3 119 | #this will add the space 120 | ``` 121 | 122 | ### Lists Slicing 123 | * It is used to make new lists from old lists 124 | ```Python 125 | #lists slicing 126 | # some_list[start:end:step] 127 | # start is to where to start 128 | # end is to where to end 129 | # Step is the intervals 130 | 131 | x = [1,2,3,4,5,6] 132 | x[0:2] 133 | # This will print [1,2] 3 is not included becuase its exclusive 134 | x[0:7:2] 135 | #This will print [2,4,6] 136 | # Easy way to reverse a list x[::-1] 137 | #Swapping Lists 138 | y = ['John','Jason'] 139 | y[0],y[1] = y[1],y[0] 140 | ``` 141 | 142 | ### List Comprehension 143 | * List comprehensions are used for creating new list from another iterables. 144 | * Interesting articles on [List Comprehension](https://hackernoon.com/list-comprehension-in-python-8895a785550b) 145 | ```Python 146 | nums = [1,2,3,4,5,6,7,8] 147 | y = [x*x for x in nums] 148 | # This will print 149 | [1,4,9,16,25] 150 | # We can also use a loop 151 | new_list =[] 152 | for x in nums: 153 | sqaure = x*x 154 | new_list.append(square) 155 | #This piece of code is doing the same thing but the only difference is that the other method is much easier 156 | # This can also be used to convert into strings 157 | [str(x) for x in nums] 158 | # This will print everything in the list that was present in int. 159 | # We can also use the conditonal statements in lists 160 | [x for x in num if x%2==0] 161 | #This will print all the even numbers in the lists 162 | ``` 163 | 164 | -------------------------------------------------------------------------------- /docs/lists.md: -------------------------------------------------------------------------------- 1 | ## Lists in Python 2 | * Lists is a way of combining different data structures.Its is more like grouping elements together. 3 | * They are usually becuase they make your code more readable. 4 | ```Python 5 | x = [1,2,3,4,'five'] 6 | #This is how a list looks like 7 | # They can hold different data such as numbers strings and floats 8 | # Values in the lists are seperated by the commas 9 | ``` 10 | 11 | ### List built in Functions 12 | * Len() This function tells how many items are there in the list 13 | ```Python 14 | x = ['one,'two','three'] 15 | print(len(x)) 16 | # This will printout the number of items present in the list 17 | ``` 18 | * list() function converts to list 19 | ```Python 20 | x = range(1,4) 21 | print(list(x)) 22 | # this print [1,2,3] 23 | ``` 24 | 25 | ### Different way of accessing the data in the lists 26 | * Every element in the list starts at 0 27 | * You can also use negative numbers but it will get the data from backwards 28 | ```Python 29 | x = ['john','jason','tony'] 30 | print(x[0]) # This will john 31 | print(x[0]) # This will jason 32 | print(x[0]) # This will tony 33 | print(x[1]) 34 | print(x[2]) 35 | ``` 36 | 37 | * We use built in python **in** keyword to see if the item exists in the list 38 | ```Python 39 | x = [1,2,3] 40 | 1 in x 41 | # this will print true 42 | 4 in x 43 | #this will print false because 4 is not in the list 44 | ``` 45 | 46 | ### We can also iterate throught the list using loops 47 | ```Python 48 | list = ['blue','yellow','green','orange','black'] 49 | for color in list: 50 | print(list) 51 | # Using while loop 52 | i = 0 53 | while i < len(list): 54 | print(list[i]) 55 | i += 1 56 | #len() function tells us how many items are there in the list 57 | ``` 58 | **Note: len() can also be used on the strings** 59 | ### List Methods 60 | * Built-in python list methods 61 | 62 | #### These methods are used to add items to the list 63 | * append () this method will add the item to the end of the list. 64 | * extend() this method adds all the values at the end of the list 65 | ```Python 66 | x = [1,2,3,4,5] 67 | x.append([5,6,7,8]) 68 | # This print [1,2,3,4,5,[6,7,8,9]] 69 | #Lets use the extend method on this 70 | x.extend([5,6,7,8,9]) 71 | #This will print out [1,2,3,4,5,6,7,8,9] 72 | ``` 73 | * if want to add one item to the end of the list use append() if you are adding more than one item use extend() 74 | * insert() method is used to add the item to the given position in the list 75 | ```Python 76 | x = [1,2,3,4] 77 | x.insert(1,'hi') 78 | [1,'hi',2,3,4] 79 | ``` 80 | 81 | #### Methods that are used to delete items from the list 82 | * clear() method will remove all the items in the list at once 83 | * pop() method removes the element at the given position 84 | ```Python 85 | x = [1,2,3,4] 86 | x.pop()# this will remove the last item by default 87 | x.pop(1) 88 | #this will remove the item at index [1] 89 | ``` 90 | * remove() method this takes in the value 91 | ```Python 92 | x = [1,2,3,4] 93 | x.remove(1) 94 | #this will remove 1 in the list 95 | [2,3,4] 96 | ``` 97 | 98 | #### Other List Methods 99 | * index() 100 | * count(), This method is used to count the duplicates in the list 101 | * reverse () this will reverse the list. This doesn't take arguements 102 | * sort() This function will sort the list in ascending order' 103 | * .join () this is string method **Only works if there are strings in the lists** 104 | ```Python 105 | x = [1,'hi',2,3,4] 106 | x.index(1) 107 | #this will print the index of the 1 which is 0 108 | x = [1,1,2,3,4,5] 109 | x.count(1) 110 | #This will check if the element is being repeated 111 | x.reverse() 112 | #This method will reverse the list 113 | # the output is going to be like [4,3,2,'hi',1] 114 | x = [3,2,4,1] 115 | x.sort() 116 | #This will sort out the list 117 | # The output will be [1,2,3,4] 118 | x = ['1','2','3'] 119 | ' '.join(x) 120 | #Output 1 2 3 121 | #this will add the space 122 | ``` 123 | 124 | ### Lists Slicing 125 | * It is used to make new lists from old lists 126 | ```Python 127 | #lists slicing 128 | # some_list[start:end:step] 129 | # start is to where to start 130 | # end is to where to end 131 | # Step is the intervals 132 | 133 | x = [1,2,3,4,5,6] 134 | x[0:2] 135 | # This will print [1,2] 3 is not included becuase its exclusive 136 | x[0:7:2] 137 | #This will print [2,4,6] 138 | # Easy way to reverse a list x[::-1] 139 | #Swapping Lists 140 | y = ['John','Jason'] 141 | y[0],y[1] = y[1],y[0] 142 | ``` 143 | 144 | ### List Comprehension 145 | * List comprehensions are used for creating new list from another iterables. 146 | * Interesting articles on [List Comprehension](https://hackernoon.com/list-comprehension-in-python-8895a785550b) 147 | ```Python 148 | nums = [1,2,3,4,5,6,7,8] 149 | y = [x*x for x in nums] 150 | # This will print 151 | [1,4,9,16,25] 152 | # We can also use a loop 153 | new_list =[] 154 | for x in nums: 155 | sqaure = x*x 156 | new_list.append(square) 157 | #This piece of code is doing the same thing but the only difference is that the other method is much easier 158 | # This can also be used to convert into strings 159 | [str(x) for x in nums] 160 | # This will print everything in the list that was present in int. 161 | # We can also use the conditonal statements in lists 162 | [x for x in num if x%2==0] 163 | #This will print all the even numbers in the lists 164 | ``` 165 | 166 | -------------------------------------------------------------------------------- /markdown-version/lambdas.md: -------------------------------------------------------------------------------- 1 | # Lambdas Functions in Python 2 | Lambdas are one line functions. They are also known as anonymous functions in some other languages. You might want to use lambdas when you don’t want to use a function twice in a program. They are just like normal functions and even behave like them. 3 | 4 | ```python3 5 | def square(x): 6 | return x * x 7 | # But Lamdas are totally different 8 | 9 | square = lambda x:x*x 10 | print(square(2)) 11 | # You can also store lamda inside of a variable 12 | # In this case we are passing x as an parameter. Basically they are short and # anonymous functions 13 | # Lambdas don't have a name' 14 | ``` 15 | 16 | #### Map() function in Lambdas 17 | * It's a standard function that accepts at least two arguements a function and an iterable 18 | * Iterable can be lists tuples or dictionary 19 | * Runs lambda for each value and then returns 20 | ```python3 21 | nums = [1,2,3,4,5] 22 | x = map(lambda x:x*x,nums) 23 | print(list(x)) 24 | # This shows how map() function works. We are passing lamda function that will square each number in the list nums 25 | ``` 26 | 27 | #### filter() Function 28 | * It takes a list/tuple and filters based on the given condition 29 | * The lambda function needs to be a boolean it can be either true or false 30 | ```python3 31 | x = [1,2,3,4,5,6,7,8] 32 | names = ['alex','john','aneesa','aidan','amina','jill','jackson'] 33 | data = [ 34 | {'username' : 'alex_1'}, 35 | {'username' : 'axis_07'}, 36 | {'username' : 'aaa'}, 37 | {'username' : 'asthetic'}, 38 | {'username' : 'bob'}, 39 | {'username' : 'jason_07'}, 40 | {'username' : 'razer_07'}, 41 | {'username' : 'pythonista'} 42 | ] 43 | # A function that will print the usernames with more than 4 characters 44 | usernames = list(filter(lambda u:len(u['username']) > 4 , data)) 45 | for name in usernames: 46 | print(name['username']) 47 | 48 | # A new list with the multiples of two and less than 10 49 | print('\n') 50 | new_list = list(map(lambda num: num*2, filter(lambda num: num < 6 ,x))) 51 | print(new_list) 52 | print('\n') 53 | for nums in new_list: 54 | print(nums) 55 | 56 | # filter names starting with J and adding them to group 1 and names starting with a goes to group_2 57 | 58 | group_1 = filter(lambda n:n[0]=='j',names) 59 | print(list(group_1)) 60 | 61 | group_2 = filter(lambda n:n[0]=='a',names) 62 | print(list(group_2)) 63 | 64 | # We can also use the list comprehension but it's better to understand how the map() and filter() works 65 | ``` 66 | 67 | #### Any() and all() built in function 68 | * all() takes the iterables and return of they are true or not 69 | ```python 70 | list = [1,2,3,4] 71 | all(list) 72 | #This will return true since all the values are true 73 | # You can also check if all numbers are divisible by two in list 74 | ``` 75 | 76 | Lets say you want to check if every name started in the list with the character C 77 | 78 | ```python 79 | list = ['Casey','Charlie','Courtney','Cashmere'] 80 | x = [name[0] == 'C' for name in list] 81 | print(all(x)) 82 | #This will return True since every name starts with C 83 | ``` 84 | 85 | Generator Expressions 86 | - They are less memory consuming. 87 | - Readmore on [List vs Generators](https://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehension) 88 | - 89 | ```python 90 | #A small test \ 91 | import sys 92 | list_comp = sys.getsizeof([x for x in range(10)]) 93 | gen = sys.getsizeof((x for x in range(10))) 94 | print(f'The mem usage of a list {list_comp} and mem usage of gen {gen}') 95 | ``` 96 | 97 | ### Sorted 98 | - This is built in python function that can be used to sort elements in the list or tuple. 99 | 100 | ```python 101 | x = [7,4,5,2,12] 102 | y = sorted(x,reverse=True) 103 | ``` 104 | This will sort the list. 105 | 106 | Another Example let say we have a dictionary of users and want to sort them. 107 | 108 | ```python 109 | data = [ 110 | { 111 | # 112 | 'name':'John', 113 | 'class':7, 114 | }, 115 | { 116 | 'name':'Zayn', 117 | 'class':2, 118 | }, 119 | { 120 | 'name':'Aquaman', 121 | 'class':11, 122 | }, 123 | { 124 | 'name':'Tony', 125 | 'class':12, 126 | }, 127 | { 128 | 'name':'Harry', 129 | 'class':5 130 | } 131 | 132 | ] 133 | 134 | sorted_dict = sorted(data,key=lambda user:user['class']) 135 | 136 | print(sorted_dict) 137 | ``` 138 | 139 | ### Min and Max Function 140 | 141 | - This is simple function that returns min or max in the list or tuple. 142 | 143 | ```python 144 | a = min([1,2,3,4,5]) 145 | print(a) 146 | # This returns 1 147 | # if we do max 148 | b = max([1,2,3,4,5]) 149 | print(b) 150 | ``` 151 | 152 | ### Reverse 153 | - This function reverses list,string or a iterator 154 | 155 | ```python 156 | x = [1,2,3,4,5] 157 | x.reverse() 158 | # This will reverse a list 159 | 160 | for char in reversed("Hello"): 161 | print(char) 162 | # This will print out reversed hello 163 | ``` 164 | 165 | 166 | ### Extras 167 | - `abs()` this will return the absolute value. 168 | - `sum()` this will sum a iterable like a list or tuple. 169 | - `round()` This is going to round the number. 170 | 171 | ```python 172 | x = -10 173 | abs(x) # this is going to print 10 174 | d = [1,2,3,4,5] 175 | sum(d) # This will print the sum of the list. 176 | f = 10.5 177 | round(f) #This will print 11 178 | ``` 179 | 180 | ### Zip() 181 | 182 | - Make an iterator that aggregates elements from each of the iterables. 183 | - Returns an iterator of tuples, where the i-th tuple contains the i-th elements from each of the arguement sequences or iterables. 184 | - the iterator stops when the shortest input iterable is exhausted. 185 | 186 | ```python 187 | x = [1,2,3] 188 | y= [4,5,6] 189 | zip(x,y) 190 | # This will print(1,4),(2,5),(3,6) 191 | # We can also convert it to a dictionary 192 | dict(zip(x,y)) 193 | ``` 194 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # Python-for-beginners documentation build configuration file, created by 5 | # sphinx-quickstart on Fri Sep 21 12:36:38 2018. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | # 20 | # import os 21 | # import sys 22 | # sys.path.insert(0, os.path.abspath('.')) 23 | 24 | 25 | # -- General configuration ------------------------------------------------ 26 | 27 | # If your documentation needs a minimal Sphinx version, state it here. 28 | # 29 | # needs_sphinx = '1.0' 30 | 31 | # Add any Sphinx extension module names here, as strings. They can be 32 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 33 | # ones. 34 | extensions = [] 35 | 36 | # Add any paths that contain templates here, relative to this directory. 37 | templates_path = ['_templates'] 38 | 39 | # The suffix(es) of source filenames. 40 | # You can specify multiple suffix as a list of string: 41 | # 42 | # source_suffix = ['.rst', '.md'] 43 | source_suffix = '.rst' 44 | 45 | # The master toctree document. 46 | master_doc = 'index' 47 | 48 | # General information about the project. 49 | project = 'Python-for-beginners' 50 | copyright = '2018, Muhammad' 51 | author = 'Muhammad' 52 | 53 | # The version info for the project you're documenting, acts as replacement for 54 | # |version| and |release|, also used in various other places throughout the 55 | # built documents. 56 | # 57 | # The short X.Y version. 58 | version = '1.0' 59 | # The full version, including alpha/beta/rc tags. 60 | release = '1.0' 61 | 62 | # The language for content autogenerated by Sphinx. Refer to documentation 63 | # for a list of supported languages. 64 | # 65 | # This is also used if you do content translation via gettext catalogs. 66 | # Usually you set "language" from the command line for these cases. 67 | language = None 68 | 69 | # List of patterns, relative to source directory, that match files and 70 | # directories to ignore when looking for source files. 71 | # This patterns also effect to html_static_path and html_extra_path 72 | exclude_patterns = [] 73 | 74 | # The name of the Pygments (syntax highlighting) style to use. 75 | pygments_style = 'sphinx' 76 | 77 | # If true, `todo` and `todoList` produce output, else they produce nothing. 78 | todo_include_todos = False 79 | 80 | 81 | # -- Options for HTML output ---------------------------------------------- 82 | 83 | # The theme to use for HTML and HTML Help pages. See the documentation for 84 | # a list of builtin themes. 85 | # 86 | html_theme = 'alabaster' 87 | 88 | # Theme options are theme-specific and customize the look and feel of a theme 89 | # further. For a list of options available for each theme, see the 90 | # documentation. 91 | # 92 | # html_theme_options = {} 93 | 94 | # Add any paths that contain custom static files (such as style sheets) here, 95 | # relative to this directory. They are copied after the builtin static files, 96 | # so a file named "default.css" will overwrite the builtin "default.css". 97 | html_static_path = ['_static'] 98 | 99 | # Custom sidebar templates, must be a dictionary that maps document names 100 | # to template names. 101 | # 102 | # This is required for the alabaster theme 103 | # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars 104 | html_sidebars = { 105 | '**': [ 106 | 'relations.html', # needs 'show_related': True theme option to display 107 | 'searchbox.html', 108 | ] 109 | } 110 | 111 | 112 | # -- Options for HTMLHelp output ------------------------------------------ 113 | 114 | # Output file base name for HTML help builder. 115 | htmlhelp_basename = 'Python-for-beginnersdoc' 116 | 117 | 118 | # -- Options for LaTeX output --------------------------------------------- 119 | 120 | latex_elements = { 121 | # The paper size ('letterpaper' or 'a4paper'). 122 | # 123 | # 'papersize': 'letterpaper', 124 | 125 | # The font size ('10pt', '11pt' or '12pt'). 126 | # 127 | # 'pointsize': '10pt', 128 | 129 | # Additional stuff for the LaTeX preamble. 130 | # 131 | # 'preamble': '', 132 | 133 | # Latex figure (float) alignment 134 | # 135 | # 'figure_align': 'htbp', 136 | } 137 | 138 | # Grouping the document tree into LaTeX files. List of tuples 139 | # (source start file, target name, title, 140 | # author, documentclass [howto, manual, or own class]). 141 | latex_documents = [ 142 | (master_doc, 'Python-for-beginners.tex', 'Python-for-beginners Documentation', 143 | 'Muhammad', 'manual'), 144 | ] 145 | 146 | 147 | # -- Options for manual page output --------------------------------------- 148 | 149 | # One entry per manual page. List of tuples 150 | # (source start file, name, description, authors, manual section). 151 | man_pages = [ 152 | (master_doc, 'python-for-beginners', 'Python-for-beginners Documentation', 153 | [author], 1) 154 | ] 155 | 156 | 157 | # -- Options for Texinfo output ------------------------------------------- 158 | 159 | # Grouping the document tree into Texinfo files. List of tuples 160 | # (source start file, target name, title, author, 161 | # dir menu entry, description, category) 162 | texinfo_documents = [ 163 | (master_doc, 'Python-for-beginners', 'Python-for-beginners Documentation', 164 | author, 'Python-for-beginners', 'One line description of project.', 165 | 'Miscellaneous'), 166 | ] 167 | 168 | 169 | 170 | -------------------------------------------------------------------------------- /docs/functions.md: -------------------------------------------------------------------------------- 1 | # Functions in Python 2 | 3 | ### What is a Function 4 | * It's process of executing a task 5 | * It can accept an input and return an output 6 | 7 | ### Why Use Functions 8 | * Stay DontRepeatYourself **DRY** 9 | * Clean Code no duplication 10 | * for example print() function 11 | * They can help you refactor 12 | * They help us organize things better 13 | 14 | #### Syntax 15 | * snakecase 16 | ```Python 17 | def function(): 18 | #Here goes everything(block of code) 19 | def say_hi(): 20 | print('Hi') 21 | #This function will say hi 22 | say_hi() #invoke the function 23 | ``` 24 | 25 | #### Return values from functions 26 | * It exits the function 27 | * Outputs whatever is placed after a return 28 | * Everytime there is a function call there is an instruction added to the stack 29 | ```Python 30 | def square_of_two(): 31 | return 2**2 32 | 33 | ``` 34 | 35 | #### Parameters in the Functions 36 | 37 | ```Python 38 | def square(num): 39 | return num**2 40 | # These parameters only exists in the functions 41 | def add(a,b): 42 | return a+b 43 | #Parameters should be named in a better way that makes sense 44 | ``` 45 | 46 | #### Parameters VS Arguements 47 | * Parameter is in the declaration of the function 48 | * Arguement is what we pass into the function 49 | 50 | ```Python 51 | def multiply(a,b): 52 | return a * b 53 | print(multiply(1,5)) 54 | # a & b are parameters 55 | # 1 & 5 are arguements 56 | # Order matters 57 | ``` 58 | 59 | ### Common Mistakes Made while returning in a Function 60 | ```Python3 61 | def sum_odd_num(numbers): 62 | total = 0 63 | for x in numbers: 64 | if x%2 ==1: 65 | ` total +=x 66 | return total 67 | 68 | print(sum_odd_numbers([1,3,5])) 69 | ``` 70 | * This function will not return the desired output instead it will return 1 because the return keyword is not indented correctly. 71 | ```Python 72 | def sum_odd_num(numbers): 73 | total = 0 74 | for x in numbers: 75 | if x%2 ==1: 76 | total +=x 77 | return total 78 | 79 | print(sum_odd_numbers([1,3,5])) 80 | ``` 81 | 82 | * Now the function will return the sum of the odd numbers because we have idented the return keyword 83 | 84 | #### Default Parameters 85 | * We can also set the default values in the functions 86 | 87 | ```Python 88 | def square(num,power=2): 89 | return num **power 90 | #Even if we dont pass a value for the power it will retain its default value 2 91 | ``` 92 | 93 | * Default parameters can help you save from errors 94 | * It makes our code more flexible 95 | * Default Parameters can be any values we can also pass functions inside of a function 96 | 97 | ### Passing Functions inside of function 98 | ```Python 99 | def add(a,b): 100 | return a+b 101 | #The math function takes in add function as a parameter also 102 | def math(a,b,fn=add): 103 | return add(a,b) 104 | ``` 105 | 106 | #### Keyword Arguements 107 | * Using keyword arguements we can alter the order 108 | * The reason we use the keyword arguements is because it helps you cause less errors and makes it more explicit 109 | ```Python 110 | def exponent(num,pow): 111 | return num **pow; 112 | print(exponent(pow=2,num=3)) #This will return 9 113 | ``` 114 | 115 | #### Scopes 116 | * There are rules where are variables can be accessed 117 | * Whenever we define a variable inside of a function it will be part of the function 118 | 119 | ```Python 120 | x = 2 121 | def add_two(num): 122 | return x+num 123 | #In this example the x variable is available outside the function 124 | 125 | def add_three(num): 126 | y = 3 127 | return num+y 128 | #In this example the y is just the part of the function and it cannot be accessed from outside 129 | ``` 130 | 131 | * Global scope 132 | * A variable that is defined outside of the function it is global 133 | * If we want to manipulate a variable that is not defined inside of the local scope we use the keyword **global**. 134 | 135 | ```Python 136 | total = 0 137 | def increment(): 138 | global total 139 | total +=1 140 | return total 141 | print(increment()) 142 | ``` 143 | 144 | * **non local** keyword 145 | 146 | ## Documenting Functions Better 147 | ```Python 148 | """ 149 | This will allow us to document the function better 150 | # These are called the docstrings in python 151 | __doc__ they are used to document the functions and it helps us learn better. 152 | 153 | print.__doc__ 154 | # All built in functions have a docstring 155 | 156 | def add(x,y): 157 | """Add function will take two parameters x and y. Then adds them""" 158 | return x + y 159 | print(add.__doc__) 160 | """ 161 | ``` 162 | 163 | ## ** and * Operators in the Functions 164 | 165 | * * star operator allow us to pass in as much parameters we can and it gathers them as a tuple 166 | * The standard keyword is **args but you call it whatever you like. 167 | 168 | ```Python3 169 | # Lets say we want to add 5 numbers we will write a function and pass 5 parameters 170 | def add(num1,num2,num3,num4,num5): 171 | return num1+num2+num3+num4+num5 172 | print(add(1,2,3,4,5)) 173 | 174 | #But what if we want to add 3 number with the same function then we have pass default values and it gets messy and takes a long time so therefore we use *args for function. 175 | 176 | def addition(*args): 177 | total = 0 178 | for num in args: 179 | total+=num 180 | return total 181 | #This is better function now 182 | #args parameter will say the input in the tuple 183 | ``` 184 | 185 | ```Python3 186 | # **kwargs parameter this will save the arguements passed into a dictionary 187 | # **kwargs is standard keyword used in the community 188 | def color(**kwargs): 189 | for person,color in kwargs.item(): 190 | print(f"{person}'s favorite color is {color}") 191 | 192 | ``` 193 | 194 | 195 | ## Parameter Odering 196 | 197 | 1) Parameters 198 | 2) **args 199 | 3) Default Parameters 200 | 4) **kwargs 201 | 202 | ```Python 203 | def odering(a,b,**args,name='john',**kwargs): 204 | return [a,b,**args,name='john',**kwargs] 205 | ``` 206 | 207 | ## List Unpacking 208 | 209 | * Passing *values* to unpack the tuples and pass them as arguements in the function 210 | 211 | ```python3 212 | def addition(*args): 213 | total = 0 214 | for num in args: 215 | total+=num 216 | return total 217 | x = [1,2,3,4] 218 | # Now we will pass the list inside of the function 219 | 220 | print(addition(*x)) 221 | ``` 222 | -------------------------------------------------------------------------------- /markdown-version/functions.md: -------------------------------------------------------------------------------- 1 | # Functions in Python 2 | 3 | ### What is a Function 4 | * It's process of executing a task 5 | * It can accept an input and return an output 6 | 7 | ### Why Use Functions 8 | * Stay DontRepeatYourself **DRY** 9 | * Clean Code no duplication 10 | * for example print() function 11 | * They can help you refactor 12 | * They help us organize things better 13 | 14 | #### Syntax 15 | * snakecase 16 | ```Python 17 | def function(): 18 | #Here goes everything(block of code) 19 | def say_hi(): 20 | print('Hi') 21 | #This function will say hi 22 | say_hi() #invoke the function 23 | ``` 24 | 25 | #### Return values from functions 26 | * It exits the function 27 | * Outputs whatever is placed after a return 28 | * Everytime there is a function call there is an instruction added to the stack 29 | ```Python 30 | def square_of_two(): 31 | return 2**2 32 | 33 | ``` 34 | 35 | #### Parameters in the Functions 36 | 37 | ```Python 38 | def square(num): 39 | return num**2 40 | # These parameters only exists in the functions 41 | def add(a,b): 42 | return a+b 43 | #Parameters should be named in a better way that makes sense 44 | ``` 45 | 46 | #### Parameters VS Arguements 47 | * Parameter is in the declaration of the function 48 | * Arguement is what we pass into the function 49 | 50 | ```Python 51 | def multiply(a,b): 52 | return a * b 53 | print(multiply(1,5)) 54 | # a & b are parameters 55 | # 1 & 5 are arguements 56 | # Order matters 57 | ``` 58 | 59 | ### Common Mistakes Made while returning in a Function 60 | ```Python3 61 | def sum_odd_num(numbers): 62 | total = 0 63 | for x in numbers: 64 | if x%2 ==1: 65 | ` total +=x 66 | return total 67 | 68 | print(sum_odd_numbers([1,3,5])) 69 | ``` 70 | * This function will not return the desired output instead it will return 1 because the return keyword is not indented correctly. 71 | ```Python 72 | def sum_odd_num(numbers): 73 | total = 0 74 | for x in numbers: 75 | if x%2 ==1: 76 | total +=x 77 | return total 78 | 79 | print(sum_odd_numbers([1,3,5])) 80 | ``` 81 | 82 | * Now the function will return the sum of the odd numbers because we have idented the return keyword 83 | 84 | #### Default Parameters 85 | * We can also set the default values in the functions 86 | 87 | ```Python 88 | def square(num,power=2): 89 | return num **power 90 | #Even if we dont pass a value for the power it will retain its default value 2 91 | ``` 92 | 93 | * Default parameters can help you save from errors 94 | * It makes our code more flexible 95 | * Default Parameters can be any values we can also pass functions inside of a function 96 | 97 | ### Passing Functions inside of function 98 | ```Python 99 | def add(a,b): 100 | return a+b 101 | #The math function takes in add function as a parameter also 102 | def math(a,b,fn=add): 103 | return add(a,b) 104 | ``` 105 | 106 | #### Keyword Arguements 107 | * Using keyword arguements we can alter the order 108 | * The reason we use the keyword arguements is because it helps you cause less errors and makes it more explicit 109 | ```Python 110 | def exponent(num,pow): 111 | return num **pow; 112 | print(exponent(pow=2,num=3)) #This will return 9 113 | ``` 114 | 115 | #### Scopes 116 | * There are rules where are variables can be accessed 117 | * Whenever we define a variable inside of a function it will be part of the function 118 | 119 | ```Python 120 | x = 2 121 | def add_two(num): 122 | return x+num 123 | #In this example the x variable is available outside the function 124 | 125 | def add_three(num): 126 | y = 3 127 | return num+y 128 | #In this example the y is just the part of the function and it cannot be accessed from outside 129 | ``` 130 | 131 | * Global scope 132 | * A variable that is defined outside of the function it is global 133 | * If we want to manipulate a variable that is not defined inside of the local scope we use the keyword **global**. 134 | 135 | ```Python 136 | total = 0 137 | def increment(): 138 | global total 139 | total +=1 140 | return total 141 | print(increment()) 142 | ``` 143 | 144 | * **non local** keyword 145 | 146 | ## Documenting Functions Better 147 | ```Python 148 | """ 149 | This will allow us to document the function better 150 | # These are called the docstrings in python 151 | __doc__ they are used to document the functions and it helps us learn better. 152 | 153 | print.__doc__ 154 | # All built in functions have a docstring 155 | 156 | def add(x,y): 157 | """Add function will take two parameters x and y. Then adds them""" 158 | return x + y 159 | print(add.__doc__) 160 | """ 161 | ``` 162 | 163 | ## ** and * Operators in the Functions 164 | 165 | * * star operator allow us to pass in as much parameters we can and it gathers them as a tuple 166 | * The standard keyword is **args but you call it whatever you like. 167 | 168 | ```Python3 169 | # Lets say we want to add 5 numbers we will write a function and pass 5 parameters 170 | def add(num1,num2,num3,num4,num5): 171 | return num1+num2+num3+num4+num5 172 | print(add(1,2,3,4,5)) 173 | 174 | #But what if we want to add 3 number with the same function then we have pass default values and it gets messy and takes a long time so therefore we use *args for function. 175 | 176 | def addition(*args): 177 | total = 0 178 | for num in args: 179 | total+=num 180 | return total 181 | #This is better function now 182 | #args parameter will say the input in the tuple 183 | ``` 184 | 185 | ```Python3 186 | # **kwargs parameter this will save the arguements passed into a dictionary 187 | # **kwargs is standard keyword used in the community 188 | def color(**kwargs): 189 | for person,color in kwargs.item(): 190 | print(f"{person}'s favorite color is {color}") 191 | 192 | ``` 193 | 194 | 195 | ## Parameter Odering 196 | 197 | 1) Parameters 198 | 2) **args 199 | 3) Default Parameters 200 | 4) **kwargs 201 | 202 | ```Python 203 | def odering(a,b,**args,name='john',**kwargs): 204 | return [a,b,**args,name='john',**kwargs] 205 | ``` 206 | 207 | ## List Unpacking 208 | 209 | * Passing *values* to unpack the tuples and pass them as arguements in the function 210 | 211 | ```python3 212 | def addition(*args): 213 | total = 0 214 | for num in args: 215 | total+=num 216 | return total 217 | x = [1,2,3,4] 218 | # Now we will pass the list inside of the function 219 | 220 | print(addition(*x)) 221 | ``` 222 | --------------------------------------------------------------------------------