├── Book └── Emailing Eric Matthes - Python Crash Course-No Starch Press (2023).pdf ├── Dictionaries ├── Dict.py ├── dic.png ├── dict.md └── markdown.md ├── Error handing ├── cal1.py ├── cal2.py ├── doc_string.py ├── error.md ├── error.py └── file.txt ├── File Handling ├── file.bin ├── file.ipynb ├── file.md ├── file.py ├── file.txt ├── file2.txt ├── file3.txt ├── file4.txt └── file5.txt ├── Functions ├── function.md ├── function.py ├── image-1.png ├── image.png ├── prime.md └── prime.py ├── If_Statement ├── if elif statement flow.png ├── if else statement flow.png ├── if statement flow.png ├── if.ipynb ├── if.md ├── if.py ├── main.py ├── nested if statement flow.png ├── syantax of if elif statement.png ├── syantax of if else statement.png ├── syantax of if nested if statement.png ├── syantax of if statement.png └── syantax of short hand.png ├── List ├── List methods.md ├── list.ipynb ├── list.md └── list.py ├── Loops in Python ├── a.ipynb ├── ahbf.ipynb ├── for.ipynb ├── for.md ├── for_loops.py ├── lopp.ipynb ├── syantax of for loop.png ├── while sytax.png ├── while.ipynb ├── while.md ├── while.py └── while2.py ├── Numbers , Int , Float , Complex ├── Numbers.md ├── Numbers.py └── main.py ├── OOP ├── ABstraction │ ├── abstraction.md │ └── abstraction.py ├── Class_Obj_Construtor_Self_Destrcutor_Typenames │ ├── OOP.md │ ├── OOP.py │ ├── {38B0A826-F032-4495-998A-58F485BF09FE}.png │ ├── {5ACC869D-7E21-4268-9FC6-F4D21A2F62BE}.png │ └── {5DC5A6C1-7F09-4A80-A69E-2A7A073F1832}.png ├── Encapsulation │ ├── encapsulation.md │ └── py.py ├── Inheritance │ ├── Inheritance.py │ ├── image-1.png │ ├── image-2.png │ ├── image-3.png │ ├── image.png │ ├── inheritance.md │ ├── super.md │ ├── {77F097BC-1FE2-4FA4-A21D-96882897AB9A}.png │ └── {81C98B3B-0954-4A39-A99F-AB05BA07E41E}.png └── Polymorphism │ ├── Polymorphism.md │ ├── Polymorphism.py │ ├── Types.md │ └── week.py ├── Operators in python ├── Opeartors.md ├── Operators_in_python.py ├── f_string.py └── main.py ├── Print statement ├── print.md └── print.py ├── README.md ├── String ├── __pycache__ │ └── string.cpython-312.pyc ├── index.png ├── main.py ├── string.ipynb ├── string.md └── string1.py ├── Tuple ├── myhtml ├── tuple.md └── tuple.py ├── Variables in python ├── variables.md └── variables.py ├── __pycache__ └── string.cpython-312.pyc ├── practise └── hello_world.py └── revision ├── OOP_rev.py └── revision.py /Book/Emailing Eric Matthes - Python Crash Course-No Starch Press (2023).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/Book/Emailing Eric Matthes - Python Crash Course-No Starch Press (2023).pdf -------------------------------------------------------------------------------- /Dictionaries/Dict.py: -------------------------------------------------------------------------------- 1 | # # original = {'a': [1, 2, 3], 'b': 100} 2 | # # shallow_copy = original.copy() 3 | 4 | 5 | # # # Modifying the original 6 | # # original['a']="string" 7 | # # print(original) 8 | # # print(shallow_copy) 9 | 10 | # # seq = ('a', 'b', 'c') 11 | # # print(dict.fromkeys(seq,[1,2,3,4])) 12 | 13 | 14 | # # # list1 = [1,2,3,4,5] 15 | # # dic1 = {"a" : 1 , "b" : 2 , "c" : 3 , "d": 4 , "e" : 5 } 16 | # # print(dic1) 17 | 18 | 19 | # # Dict = {} 20 | # # print("Empty Dictionary: ") 21 | # # print(Dict) 22 | 23 | # # list1 = [1,2,3,4,5] 24 | 25 | # # Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} 26 | # # print("\nDictionary with the use of dict(): ") 27 | # # print(Dict) 28 | 29 | # # Dict = dict([(1, 'Geeks'), (2, 'For') ,(3, 'yes')]) 30 | # # print("\nDictionary with each item as a pair: ") 31 | # # print(Dict) 32 | 33 | 34 | # # list1 = [1,2,3,["A","B",[1,2,3],"C"],4,5] 35 | # # # first = list1[3] 36 | # # # sec = first[2] 37 | # # # print(sec[1]) 38 | 39 | # # print(list1[3][2][1]) 40 | 41 | 42 | # # # Dict = {1: 'Geeks', 'name': 'For', 3: {"a" : 1 , "b" : 2}, 4 : {"c" : 1 , "d" : 2 , "e" : 5}} 43 | # # Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks' , 4 : (1,2,3)} 44 | # # print(Dict.get) 45 | 46 | 47 | 48 | # # DELL() 49 | # # Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} 50 | # # print("Dictionary =") 51 | # # print(Dict) 52 | # # del(Dict["name"]) 53 | # # print("Data after deletion Dictionary=") 54 | # # print(Dict) 55 | # # del(Dict["name"]) 56 | # # print(Dict) 57 | 58 | 59 | # # clear() 60 | # # Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} 61 | # # Dict2 = Dict.copy() 62 | # # print(Dict) 63 | # # print(Dict2) 64 | 65 | # # fromkey() 66 | 67 | # # seq = ('a', 'b', 'c') 68 | # # Dict : dict = dict.fromkeys(()) 69 | # # print(Dict) 70 | # # Dict["age"] = int(input("write any value : ")) 71 | # # Dict["gender"] = [input("write any value : ")] 72 | # # Dict["name"] = (input("write any value : "),) 73 | # # print(Dict) 74 | 75 | # # pop() 76 | # # Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} 77 | # # Dict.pop(3) 78 | # # print(Dict) 79 | # # 80 | # # popitem() 81 | # # Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} 82 | # # Dict.popitem() 83 | # # print(Dict) 84 | # # 85 | # # update() 86 | 87 | # # Dictionary with three items 88 | # # Dictionary1 = {'A': 'Geeks', 'B': 'For', } 89 | # # Dictionary2 = {'B': 'Geeks' , "C" : "uzair"} 90 | 91 | # # print("Original Dictionary:") 92 | # # print(Dictionary1) 93 | # # Dictionary1.update(Dictionary2) 94 | # # print("Dictionary after updation:") 95 | # # print(Dictionary1) 96 | 97 | 98 | # # setdefault() 99 | # my_dict = {'name': 'Alice', 'age': 25 ,'salary': 200 , "gender" : ""} 100 | # print(my_dict) 101 | 102 | # # age = my_dict.setdefault('age', 10) 103 | # # print(f"Age: {age}") 104 | 105 | # salary = my_dict.setdefault('salary', 50000) 106 | # gender = my_dict.setdefault("gender","male") 107 | # print(f"Salary: {salary}") 108 | # print(my_dict) # Output: {'name': 'Alice', 'age': 25, 'salary': 50000} 109 | 110 | 111 | # d = {'coding': 'good', 'thinking': 'better'} 112 | # print(d['cod']) 113 | 114 | # Python3 code to demonstrate 115 | # to initialize dictionary with list 116 | # using from keys() 117 | 118 | # # using from keys() to construct 119 | # new_dict = dict.fromkeys(range(4),) 120 | 121 | # # printing result 122 | # print ("New dictionary with empty lists as keys : " + str(new_dict)) 123 | # seq = ('a', 'b', 'c') 124 | # print(dict.fromkeys(seq, None)) 125 | # seq = ('title', 'author', 'status') 126 | # values = {} 127 | 128 | # for key in seq: 129 | # user_input = input(f"Enter value for {key}: ") 130 | # values[key] = user_input 131 | 132 | # print(values) 133 | # value = {} 134 | # value["a"] = "uzair" 135 | # print(value) 136 | 137 | # li = [1,2,3,4,5,6,7,8,["a","b","c" , [12,13,14]]] 138 | 139 | # print(li[9]) 140 | # for x ,y in enumerate(li): 141 | # print(x,y) 142 | # # print(li[8]) 143 | # li2= li[8] 144 | # for x ,y in enumerate(li2): 145 | # print(x,y) 146 | # # print(li2[1]) 147 | 148 | # print(li[8][3][2]) 149 | 150 | 151 | # dic = {1 : [1,2,3] , 2 : (1,2,3) , 3 : {4 : [5,6,7]} } 152 | # # print(dic["b"][1]) 153 | 154 | # print(dic[3][4][2]) 155 | 156 | 157 | # dic = {} 158 | # print(dic) 159 | # dic["a"] = int(input("write any num")) 160 | # dic["b"] = 2 161 | # dic["c"] = 3 162 | # dic["d"] = 4 163 | 164 | 165 | # print(dic) 166 | 167 | dic = dict([(1,"a"),(2,"b"),(3,"c")]) 168 | # print(dic) 169 | 170 | # del dic[1] 171 | 172 | # dic.clear() 173 | # print(dic) 174 | 175 | # seq = ('a', 'b', 'c') 176 | # print(dict.fromkeys(seq, None)) 177 | 178 | # tu = (1,2,3,4,5) 179 | # print(dict.fromkeys(tu,"Uzair")) 180 | 181 | # dic = dict([(1,"a"),(2,"b"),(3,"c")]) 182 | # print(dic) 183 | 184 | # print(dic.get(4)) 185 | 186 | # d = {1: '001', 2: '010', 3: '011'} 187 | # li = [1,2,3,4,5] 188 | 189 | # d.pop(1) # dic pop if you dont give any value it will cause error 190 | # # # if you give any value it will remove that element 191 | 192 | # d.popitem() # dic popitem() if you dont give any value it will remove last element 193 | # # # # if you give any value it will cause error 194 | 195 | 196 | # li.pop(0) # list pop if you dont give any value it will remove last element 197 | # # if you give any value it will remove that element 198 | 199 | # print(d) 200 | # print(li) 201 | 202 | # # print(d.get(4,"Not Found")) 203 | 204 | # d.popitem() 205 | # print(d) 206 | 207 | 208 | # d2 = {1: 'a', 2: "b" , 3 : "c" , 4 : "d"} 209 | 210 | # # print(d) 211 | # # d.update(d2) 212 | # # print(d) 213 | 214 | 215 | # print(d2.setdefault(5)) 216 | 217 | # print(d2) 218 | 219 | 220 | # def add(**a): 221 | # # print(a) 222 | 223 | 224 | # # add(a = 1 , b = 2 , c = 3 ) 225 | 226 | # def add(*a): 227 | # print(a) 228 | 229 | 230 | # add(1 , 2 ,3 ) 231 | 232 | d2 = {1: 'a', 2: "b" , 3 : "c" , 4 : "d"} 233 | 234 | # # print(d2.keys()) 235 | # # print(d2.values()) 236 | 237 | # # print(d2.items()) 238 | # # dic = dict([(1,"a"),(2,"b"),(3,"c")]) 239 | 240 | # for x , y in d2.items(): 241 | # print(x,y) 242 | # dic = {} 243 | # li = ["a" , "b" , "c" , "d"] 244 | 245 | 246 | # for x , y in enumerate(li): 247 | # dic[x] = y 248 | 249 | # print(dic) 250 | 251 | 252 | # dic3 = {} 253 | 254 | # dic3[1] = "a" 255 | 256 | print(dic3) -------------------------------------------------------------------------------- /Dictionaries/dic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/Dictionaries/dic.png -------------------------------------------------------------------------------- /Dictionaries/dict.md: -------------------------------------------------------------------------------- 1 | # Dictionaries In python 2 | 3 | ## A Python dictionary is a data structure that stores the value in key: value pairs. 4 | 5 | 6 | ## How to Create a Dictionary 7 | 8 | ### In Python, a dictionary can be created by placing a sequence of elements within curly {} braces, separated by a ‘comma’. The dictionary holds pairs of values, one being the Key and the other corresponding pair element being its Key:value. Values in a dictionary can be of any data type and can be duplicated, whereas keys can’t be repeated and must be immutable. 9 | 10 | 11 | 12 | 13 | ```python 14 | Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} 15 | print(Dict) 16 | ``` 17 | 18 | ## demonstrates creating dictionaries with different types of keys. 19 | 20 | ```python 21 | Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} 22 | print("\nDictionary with the use of Integer Keys: ") 23 | print(Dict) 24 | 25 | Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} 26 | print("\nDictionary with the use of Mixed Keys: ") 27 | print(Dict) 28 | ``` 29 | 30 | ## Different Ways to Create a Python Dictionary 31 | 32 | ```python 33 | Dict = {} 34 | print("Empty Dictionary: ") 35 | print(Dict) 36 | 37 | Dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'}) 38 | print("\nDictionary with the use of dict(): ") 39 | print(Dict) 40 | 41 | Dict = dict([(1, 'Geeks'), (2, 'For')]) 42 | print("\nDictionary with each item as a pair: ") 43 | print(Dict) 44 | ``` 45 | ## Accessing Elements of a Dictionary 46 | ### To access the items of a dictionary refer to its key name. Key can be used inside square brackets. 47 | ```python 48 | Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} 49 | print("Accessing a element using key:") 50 | print(Dict['name']) 51 | print("Accessing a element using key:") 52 | print(Dict[1]) 53 | ``` 54 | ## Nested Dictionaries 55 | 56 | 57 | 58 | ```python 59 | Dict = {1: 'Geeks', 2: 'For', 60 | 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}} 61 | 62 | print(Dict) 63 | ``` 64 | 65 | ## Accessing an Element of a Nested Dictionary 66 | 67 | ```python 68 | Dict = {'Dict1': {1: 'Geeks'}, 69 | 'Dict2': {'Name': 'For'}} 70 | 71 | print(Dict['Dict1']) 72 | print(Dict['Dict1'][1]) 73 | print(Dict['Dict2']['Name']) 74 | ``` 75 | 76 | ## Deleting Elements using ‘del’ Keyword 77 | 78 | 79 | ```python 80 | Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} 81 | 82 | print("Dictionary =") 83 | print(Dict) 84 | del(Dict[1]) 85 | print("Data after deletion Dictionary=") 86 | print(Dict) 87 | ``` 88 | 89 | # Dic Methods 90 | 91 | ## Python Dictionary clear() 92 | 93 | ```python 94 | # Python program to demonstrate working of 95 | # dictionary clear() 96 | text = {1: "geeks", 2: "for"} 97 | 98 | text.clear() 99 | print('text =', text) 100 | ``` 101 | 102 | ## Python Dictionary copy() 103 | ### Python Dictionary copy() method returns a shallow copy of the dictionary. 104 | 105 | ```python 106 | original = {1: 'geeks', 2: 'for'} 107 | 108 | # copying using copy() function 109 | new = original.copy() 110 | 111 | # removing all elements from the list 112 | # Only new list becomes empty as copy() 113 | # does shallow copy. 114 | new.clear() 115 | 116 | print('new: ', new) 117 | print('original: ', original) 118 | ``` 119 | ## Python Dictionary fromkeys() Method 120 | 121 | ### Python dictionary fromkeys() function returns the dictionary with key mapped and specific value. It creates a new dictionary from the given sequence with the specific value 122 | 123 | ```python 124 | seq = ('a', 'b', 'c') 125 | print(dict.fromkeys(seq, None)) 126 | ``` 127 | ```python 128 | # Python3 code to demonstrate 129 | # to initialize dictionary with list 130 | # using from keys() 131 | 132 | # using from keys() to construct 133 | new_dict = dict.fromkeys(range(4), []) 134 | 135 | # printing result 136 | print ("New dictionary with empty lists as keys : " + str(new_dict)) 137 | ``` 138 | 139 | ## Python Dictionary get() Method 140 | 141 | ### Python Dictionary get() Method returns the value for the given key if present in the dictionary. If not, then it will return None (if get() is used with only one argument). 142 | 143 | ```python 144 | d = {'coding': 'good', 'thinking': 'better'} 145 | print(d.get('coding')) 146 | ``` 147 | ```python 148 | d = {1: '001', 2: '010', 3: '011'} 149 | 150 | print(d.get(4, "Not found")) 151 | ``` 152 | ```python 153 | test_dict = {'Gfg' : {'is' : 'best'}} 154 | 155 | # printing original dictionary 156 | print("The original dictionary is : " + str(test_dict)) 157 | 158 | # using nested get() 159 | # Safe access nested dictionary key 160 | res = test_dict.get('Gfg', {}).get('is') 161 | 162 | # printing result 163 | print("The nested safely accessed value is : " + str(res)) 164 | ``` 165 | ## Python Dictionary pop() Method 166 | ### Python dictionary pop() method removes and returns the specified element from the dictionary. 167 | 168 | ```python 169 | # inializing dictionary student 170 | student = {"rahul":7, "Aditya":1, "Shubham":4} 171 | 172 | # priting original dictionary 173 | print(student) 174 | 175 | # using dictionary pop 176 | suspended = student.pop("rahul") 177 | 178 | # checking key of the element 179 | print("suspended student roll no. = "+ str(suspended)) 180 | 181 | # printing list after performing pop() 182 | print("remaining student" + str(student)) 183 | ``` 184 | ## Python Dictionary popitem() method 185 | ### Python dictionary popitem() method removes the last inserted key-value pair from the dictionary and returns it as a tuple. 186 | ```python 187 | d = {1: '001', 2: '010', 3: '011'} 188 | print(d.popitem()) 189 | ``` 190 | ## Python Dictionary update() method 191 | ### Python Dictionary update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs. 192 | 193 | ```python 194 | # Python program to show working 195 | # of update() method in Dictionary 196 | 197 | # Dictionary with three items 198 | Dictionary1 = {'A': 'Geeks', 'B': 'For', } 199 | Dictionary2 = {'B': 'Geeks'} 200 | 201 | # Dictionary before Updation 202 | print("Original Dictionary:") 203 | print(Dictionary1) 204 | 205 | # update the value of key 'B' 206 | Dictionary1.update(Dictionary2) 207 | print("Dictionary after updation:") 208 | print(Dictionary1) 209 | ``` 210 | 211 | ## Python Dictionary setdefault() Method 212 | ### Python Dictionary setdefault() returns the value of a key (if the key is in dictionary). Else, it inserts a key with the default value to the dictionary. 213 | 214 | 215 | ```python 216 | my_dict = {'name': 'Alice', 'age': 25} 217 | 218 | # Using setdefault to retrieve a value 219 | age = my_dict.setdefault('age', 0) 220 | print(f"Age: {age}") # Output: Age: 25 221 | 222 | # Using setdefault to add a new key with a default value 223 | salary = my_dict.setdefault('salary', 50000) 224 | print(f"Salary: {salary}") # Output: Salary: 50000 225 | 226 | print(my_dict) # Output: {'name': 'Alice', 'age': 25, 'salary': 50000} 227 | ``` 228 | ### The setdefault() method in Python dictionaries is a handy function that simplifies your code when you want to retrieve a value for a given key and also ensure that the key exists in the dictionary. If the key is already present, setdefault() returns its value. If the key is not present, it inserts the key with a specified default value and then returns that value. 229 | -------------------------------------------------------------------------------- /Dictionaries/markdown.md: -------------------------------------------------------------------------------- 1 | 1. uzair 2 | 2. uzair 3 | - yaasin 4 | - rafay 5 | 3. uzair 6 | 7 | ![img](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS2J91RNQHF_b_Ac4ZNeiMR_1FwPsVG2cTdwA&s) -------------------------------------------------------------------------------- /Error handing/cal1.py: -------------------------------------------------------------------------------- 1 | 2 | def add(x, y): 3 | """This function adds two numbers.""" 4 | return x + y 5 | 6 | def subtract(x, y): 7 | """This function subtracts two numbers.""" 8 | return x - y 9 | 10 | def multiply(x, y): 11 | """This function multiplies two numbers.""" 12 | return x * y 13 | 14 | def divide(x, y): 15 | """This function divides two numbers and handles division by zero.""" 16 | return x / y 17 | 18 | def mod(x, y): 19 | """This function calculates the modulus of two numbers.""" 20 | return x % y 21 | 22 | def exponent(x, y): 23 | """This function raises x to the power of y.""" 24 | return x ** y 25 | 26 | 27 | first_value = int(input( "write your first number : ")) 28 | second_value = int(input( "write your second number : ")) 29 | choice = input("choice what do you want to do : ( '+ , - , * , / , % , **' ) : ") 30 | if choice == "+": 31 | print(add(first_value,second_value)) 32 | elif choice == "*": 33 | print(multiply(first_value , second_value)) 34 | elif choice == "-": 35 | print(subtract(first_value, second_value)) 36 | elif choice == "/": 37 | print(divide(first_value, second_value)) 38 | elif choice == "%": 39 | print(mod(first_value, second_value)) 40 | elif choice == "**": 41 | print(exponent(first_value, second_value)) 42 | else : 43 | print("invalid choice") 44 | 45 | print("uzair") 46 | 47 | -------------------------------------------------------------------------------- /Error handing/cal2.py: -------------------------------------------------------------------------------- 1 | def add(x, y): 2 | """This function adds two numbers but does not allow negative numbers.""" 3 | try: 4 | if x < 0 or y < 0: 5 | raise ValueError("Error: Negative numbers are not allowed in addition.") 6 | return x + y 7 | except ValueError as e: 8 | return e 9 | 10 | 11 | return x + y 12 | 13 | def subtract(x, y): 14 | """This function subtracts two numbers.""" 15 | return x - y 16 | 17 | def multiply(x, y): 18 | """This function multiplies two numbers.""" 19 | return x * y 20 | 21 | def divide(x, y): 22 | """This function divides two numbers and handles division by zero.""" 23 | try: 24 | return x / y 25 | except ZeroDivisionError: 26 | return "Error: Division by zero is not allowed." 27 | 28 | def mod(x, y): 29 | """This function calculates the modulus of two numbers.""" 30 | try: 31 | return x % y 32 | except ZeroDivisionError: 33 | return "Error: Modulus by zero is not allowed." 34 | 35 | def exponent(x, y): 36 | """This function raises x to the power of y.""" 37 | return x ** y 38 | 39 | try: 40 | first_value = int(input("Write your first number: ")) 41 | second_value = int(input("Write your second number: ")) 42 | choice = input("Choose what you want to do ( '+ , - , * , / , % , **' ): ") 43 | 44 | if choice == "+": 45 | print(add(first_value, second_value)) 46 | elif choice == "*": 47 | print(multiply(first_value, second_value)) 48 | elif choice == "-": 49 | print(subtract(first_value, second_value)) 50 | elif choice == "/": 51 | print(divide(first_value, second_value)) 52 | elif choice == "%": 53 | print(mod(first_value, second_value)) 54 | elif choice == "**": 55 | print(exponent(first_value, second_value)) 56 | else: 57 | print("Invalid choice.") 58 | except ValueError: 59 | print("Error: Please enter valid numbers.") 60 | 61 | 62 | print("uzair") 63 | -------------------------------------------------------------------------------- /Error handing/doc_string.py: -------------------------------------------------------------------------------- 1 | # def add(): 2 | # """This function adds two numbers but does not allow negative numbers.""" 3 | 4 | # print(add.__doc__) 5 | 6 | # print(list.__doc__) -------------------------------------------------------------------------------- /Error handing/error.md: -------------------------------------------------------------------------------- 1 | 2 | # Errors and Exceptions in Python 3 | 4 | Errors in Python can be of two types: **Syntax Errors** and **Exceptions**. Errors are issues in a program that cause the program to stop execution. On the other hand, exceptions are raised when some internal events occur that change the normal flow of the program. 5 | 6 | ## Types of Exceptions in Python 7 | 8 | In Python, there are several built-in exceptions that can be raised when an error occurs during program execution. Some of the most common types are: 9 | 10 | - **SyntaxError**: Raised when the interpreter encounters a syntax error, such as a missing colon or unbalanced parenthesis. 11 | - **TypeError**: Raised when an operation or function is applied to an object of the wrong type, such as adding a string to an integer. 12 | - **NameError**: Raised when a variable or function name is not found in the current scope. 13 | - **IndexError**: Raised when an index is out of range for a list, tuple, or sequence. 14 | - **KeyError**: Raised when a key is not found in a dictionary. 15 | - **ValueError**: Raised when a function receives an invalid argument, such as converting an invalid string to an integer. 16 | - **AttributeError**: Raised when an attribute or method is not found on an object. 17 | - **IOError**: Raised when an I/O operation fails, such as reading or writing to a file. 18 | - **ZeroDivisionError**: Raised when trying to divide a number by zero. 19 | - **ImportError**: Raised when an import statement fails to find or load a module. 20 | 21 | ## Difference between Syntax Errors and Exceptions 22 | 23 | ### Syntax Error 24 | A syntax error occurs due to incorrect syntax in the code, causing the program to terminate. 25 | 26 | Example: 27 | 28 | ```python 29 | amount = 10000 30 | if(amount > 2999) 31 | print("You are eligible to purchase DSA Self Paced") 32 | ``` 33 | 34 | ### Exceptions 35 | Exceptions occur when the code is syntactically correct but results in an error during execution. This doesn't stop the program, but it changes its normal flow. 36 | 37 | Example: 38 | 39 | ```python 40 | marks = 10000 41 | a = marks / 0 42 | print(a) 43 | ``` 44 | 45 | This will raise a `ZeroDivisionError` because dividing by zero is not allowed. 46 | 47 | ## Handling Exceptions 48 | 49 | ### TypeError Example 50 | A `TypeError` is raised when incompatible types are used in an operation. 51 | 52 | ```python 53 | x = 5 54 | y = "hello" 55 | try: 56 | z = x + y 57 | except TypeError: 58 | print("Error: cannot add an int and a str") 59 | ``` 60 | 61 | ### Try and Except Statement 62 | 63 | `try` and `except` blocks are used to catch and handle exceptions in Python. 64 | 65 | Example: 66 | 67 | ```python 68 | a = [1, 2, 3] 69 | try: 70 | print("Second element = %d" % (a[1])) 71 | print("Fourth element = %d" % (a[3])) 72 | except: 73 | print("An error occurred") 74 | ``` 75 | 76 | ### Catching Specific Exceptions 77 | 78 | You can catch specific exceptions like `IndexError` or `ValueError`. 79 | 80 | ```python 81 | try: 82 | # statements 83 | except IndexError: 84 | # handle IndexError 85 | except ValueError: 86 | # handle ValueError 87 | ``` 88 | 89 | ### Example of Specific Exception Handling 90 | 91 | ```python 92 | def fun(a): 93 | if a < 4: 94 | b = a / (a - 3) 95 | print("Value of b = ", b) 96 | 97 | try: 98 | fun(3) 99 | fun(5) 100 | except ZeroDivisionError: 101 | print("ZeroDivisionError Occurred and Handled") 102 | ``` 103 | 104 | ## Try with Else Clause 105 | 106 | The `else` clause executes only if the `try` block doesn't raise an exception. 107 | 108 | Example: 109 | 110 | ```python 111 | def AbyB(a, b): 112 | try: 113 | c = (a + b) / (a - b) 114 | except ZeroDivisionError: 115 | print("a/b result in 0") 116 | else: 117 | print(c) 118 | 119 | AbyB(2.0, 3.0) 120 | AbyB(3.0, 3.0) 121 | ``` 122 | 123 | To handle a syntax error using error handling in Python, you can use a `try-except` block. However, keep in mind that a `SyntaxError` occurs at compile time, meaning the Python interpreter will not even run the code if it detects a syntax error. Therefore, you cannot catch a `SyntaxError` using `try-except` within the code that has the error itself. 124 | 125 | However, you can catch `SyntaxError` when dynamically executing code using `eval()` or `exec()`. Here's an example of handling a `SyntaxError` in such cases: 126 | 127 | ```python 128 | code = "print('Hello World'" # SyntaxError: missing closing parenthesis 129 | 130 | try: 131 | exec(code) # Using exec to run the code 132 | except SyntaxError as e: 133 | print(f"Syntax error occurred: {e}") 134 | ``` 135 | 136 | 137 | ## Finally Keyword in Python 138 | 139 | The `finally` block is always executed, regardless of whether an exception occurs. 140 | 141 | ```python 142 | try: 143 | k = 5 // 0 144 | print(k) 145 | except ZeroDivisionError: 146 | print("Can't divide by zero") 147 | finally: 148 | print("This is always executed") 149 | ``` 150 | # finally 151 | 152 | ### there may be some situation in which the current method ends up while handling some exceptions. But the method may require some additional steps before its termination, like closing a file or a network and so on. So, in order to handle these situations, Python provides a keyword finally, which is always executed after try and except blocks. The finally block always executes after normal termination of try block or after try block terminates due to some exception. 153 | 154 | 155 | ### Important Points – 156 | 157 | - finally block is always executed after leaving the try statement. In case if some exception was not handled by except block, it is re-raised after execution of finally block. 158 | - finally block is used to deallocate the system resources. 159 | One can use finally just after try without using except block, but no exception is handled in that case. 160 | 161 | ```python 162 | try: 163 | file = open("sample.txt", "r") 164 | content = file.read() 165 | print(content) 166 | except FileNotFoundError: 167 | print("Error: The file was not found.") 168 | except IOError: 169 | print("Error: An error occurred while reading the file.") 170 | finally: 171 | print("Closing the file.") 172 | if file: 173 | file.close() 174 | ``` -------------------------------------------------------------------------------- /Error handing/error.py: -------------------------------------------------------------------------------- 1 | # x = 5 2 | # y = "z" 3 | # try: 4 | # z = x + y 5 | # print(z) 6 | # except Exception as a: 7 | # print(a) 8 | # print("uzair") 9 | 10 | # a = [1, 2, 3] 11 | # try: 12 | # print("Second element = %d" % (a[1])) 13 | # print("Fourth element = %d" % (a[3])) 14 | # except IndexError as a: 15 | # print("An error occurred") 16 | 17 | 18 | # try: 19 | # print('Hello 20 | # except SyntaxError as e: 21 | # print(f"Caught a syntax error: {e}") 22 | 23 | # def fun(a): 24 | # if a < 4: 25 | # b = a / (a - 3) 26 | # print("Value of b = ", b) 27 | 28 | # try: 29 | # # fun(3) 30 | # fun(5) 31 | # except ZeroDivisionError: 32 | # print("ZeroDivisionError Occurred and Handled") 33 | # except NameError as f : 34 | # print(f) 35 | 36 | 37 | # def AbyB(a, b): 38 | # try: 39 | # c = (a + b) / (a - b) 40 | # except ZeroDivisionError as d: 41 | # print(d) 42 | # else: 43 | # print(c) 44 | 45 | # AbyB(2.0, 3.0) 46 | 47 | # AbyB(3.0, 3.0) 48 | 49 | # print(") 50 | # print("uzair") 51 | 52 | # x = 53 | # b = 0 54 | 55 | # try: 56 | # print(") 57 | # raise "error" 58 | # except SyntaxError as a: 59 | # print(a) 60 | 61 | 62 | # print("uzair") 63 | 64 | 65 | # a = [1, 2, 3] 66 | # try: 67 | # print("Fourth element = %d" % (a[3])) 68 | # except IndexError as a: 69 | # print(a) 70 | 71 | 72 | # print("uzair") 73 | 74 | # print("Fourth element = %d" % (a[3])) 75 | 76 | 77 | # def fun(a): 78 | # if a < 4: 79 | # b = a / (a - 3) 80 | # print(b) 81 | 82 | # try: 83 | # # fun(5) 84 | # fun(3) 85 | # except ZeroDivisionError as a: 86 | # print("fun (3) : " ,a) 87 | # # except UnboundLocalError as b : 88 | # # print("fun (5)",b) 89 | 90 | # # fun(3) 91 | # fun(5) 92 | 93 | 94 | # def AbyB(a, b): 95 | # try: 96 | # c = (a + b) / (a - b) 97 | # except ZeroDivisionError : 98 | # print("a/b result in 0 : ") 99 | # else: 100 | # print(c) 101 | 102 | # # AbyB(2.0, 3.0) 103 | # AbyB(3.0, 3.0) 104 | 105 | # try: 106 | # k = 5 // 4 107 | # print(k) 108 | # except ZeroDivisionError: 109 | # print("error") 110 | # finally: 111 | # print("finally") 112 | 113 | # code = "print('Hello World'" 114 | 115 | # try: 116 | # exec(code) # Using exec to run the code 117 | # except SyntaxError as e: 118 | # print(f"Syntax error occurred: {e}") 119 | # file = None # Initialize file to None 120 | # try: 121 | # file = open("file.txt", "r") 122 | # content = file.read() 123 | # print(content) 124 | # except FileNotFoundError: 125 | # print("Error: The file was not found.") 126 | # except IOError: 127 | # print("Error: An error occurred while reading the file.") 128 | # finally: 129 | # print("Closing the file.") 130 | # file.close() 131 | 132 | # a = [1, 2, 3] 133 | # x = 5 134 | # # y = "j" 135 | # # try: 136 | # # z = x + y 137 | # # # print("Fourth element = %d" % (a[3])) 138 | # # except Exception as a : 139 | # # print(a) 140 | 141 | # # print("uzair") 142 | 143 | # a = [1, 2, 3] 144 | # try: 145 | # # print("Second element = %d" % (a[1])) 146 | # print("Fourth element = %d" % (a[3])) 147 | # except IndexError as a: 148 | # print(a) 149 | # else: 150 | # print("No exception occurred") 151 | # finally: 152 | # # print("This will always run") 153 | 154 | # try: 155 | # exec("x === 5") # This has a syntax error (invalid '===' instead of '==') 156 | # except SyntaxError as e: 157 | # print("Caught a SyntaxError:", e) 158 | 159 | # print("uzair") 160 | 161 | # def fun(a): 162 | # if a < 4: 163 | # b = a / (a - 3) 164 | # # print("Value of b = ", b) 165 | 166 | # # # try: 167 | # # # # fun(3) 168 | # # # fun(5) 169 | # # # except ZeroDivisionError: 170 | # # # print("ZeroDivisionError Occurred and Handled") 171 | 172 | 173 | 174 | # # x = 5 175 | # # y = "uzair" 176 | # # try : 177 | # # print(x+y) 178 | # # # except TypeError as d: 179 | # # # print(d) 180 | 181 | # # # print("uzair") 182 | 183 | # x = 5 184 | # y = 0 185 | # z= "uzair" 186 | # try : 187 | # print(x+z) 188 | # # print(x/y) 189 | # except Exception as e: 190 | # print(e) 191 | # else: 192 | # print("No exception occurred") 193 | # finally: 194 | # print("This will always run") 195 | 196 | # # print("uzair") 197 | 198 | # try: 199 | # exec(var = "uzar) 200 | # except SyntaxError as e: 201 | # print(e) 202 | 203 | 204 | # print("uzair") 205 | 206 | user = input("Enter your age") 207 | if type(user) == str : 208 | raise ("this is not a valid input") 209 | -------------------------------------------------------------------------------- /Error handing/file.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/Error handing/file.txt -------------------------------------------------------------------------------- /File Handling/file.bin: -------------------------------------------------------------------------------- 1 | uzair -------------------------------------------------------------------------------- /File Handling/file.ipynb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/File Handling/file.ipynb -------------------------------------------------------------------------------- /File Handling/file.py: -------------------------------------------------------------------------------- 1 | # # # f = open("file.txt" , "r+") 2 | 3 | # # # # Read the content of the file 4 | 5 | # # # content = f.read() 6 | # # # print(content) 7 | # # # # Close the file 8 | 9 | # # # f.close() 10 | 11 | # # # w=open("file2.txt" , "w") 12 | # # # w.write("Hello , how are you ? ") 13 | # # # w.write("\nHello , how are you 2? ") 14 | # # # # Close the file 15 | 16 | # # # w.close() 17 | 18 | # # # r=open("file2.txt" , "r") 19 | 20 | # # # # Read the content of the file 21 | 22 | # # # content = r.read() 23 | # # # print(content) 24 | 25 | # # # # Close the file 26 | # # # # r.close() 27 | # # # w = open("file.txt" , "w") 28 | 29 | # # # # Write some content to the file 30 | 31 | # # # w.write("Hello , how are you ? ") 32 | # # # w.write("\nHello , how are you 2? ") 33 | 34 | # # # # Close the file 35 | 36 | # # # w.close() 37 | 38 | # # # r = open("file.txt" , "r") 39 | 40 | # # # # Read the content of the file 41 | 42 | # # # content = r.read() 43 | # # # print(content) 44 | 45 | # # # # Close the file 46 | 47 | # # # r.close() 48 | # # # a = open("file.txt" , "a") 49 | 50 | # # # # Write some content to the file 51 | 52 | # # # a.write("\nHello , how are you 3? ") 53 | 54 | # # # # Close the file 55 | 56 | # # # a.close() 57 | 58 | # # # r = open("file.txt" , "r") 59 | 60 | # # # # Read the content of the file 61 | 62 | # # # content = r.read() 63 | # # # content.split() 64 | 65 | # # # # Close the file 66 | 67 | # # # r.close() 68 | 69 | # # # print(content) 70 | 71 | # # # r = open("file2.txt" , "r") 72 | 73 | # # # # # Read the content of the file 74 | # # # con = r.read() 75 | # # # words = con.split() 76 | # # # # print(words) 77 | 78 | # # wb= open("binary.bin" , "wb") 79 | 80 | # # # # Write some binary data to the file 81 | # # wb.write(b'1,2') 82 | # # wb.close() 83 | # # # read 84 | # # rb = open("binary.bin" , "rb") 85 | # # # Read the content of the file 86 | 87 | # # content = rb.read() 88 | 89 | # # print(content) 90 | 91 | # # # Close the file 92 | 93 | # # rb.close() 94 | # # # Writing to a binary file 95 | # # # with open("example.bin", "wb") as file: 96 | # # # file.write(b'Binary data to write') # Write binary data 97 | 98 | # # # # Reading from the same binary file 99 | # # # with open("example.bin", "rb") as file: 100 | # # # data = file.read() # Read the content 101 | # # # print(data) 102 | 103 | 104 | # # file1 = open('myfile.txt', 'w') 105 | # # L = ["This is Delhi \n", "This is Paris \n", "This is London \n"] 106 | # # s = "Hello\n" 107 | 108 | # # # Writing a string to file 109 | # # file1.write(s) 110 | 111 | # # # Writing multiple strings at a time 112 | # # file1.writelines(L) 113 | 114 | # # # Closing file 115 | # # file1.close() 116 | 117 | # # # Checking if the data is written to file or not 118 | # # file1 = open('myfile.txt', 'r') 119 | # # print(file1.read()) 120 | # # file1.close() 121 | 122 | # # file1 = open("myfile.txt", "w") 123 | # # L = ["This is Delhi \n", "This is Paris \n", "This is London"] 124 | # # file1.writelines(L) 125 | # # file1.close() 126 | 127 | # # # Append-adds at last 128 | # # file1 = open("myfile.txt", "a") # append mode 129 | # # file1.write("Today \n") 130 | # # file1.close() 131 | 132 | # # file1 = open("myfile.txt", "r") 133 | # # print("Output of Readlines after appending") 134 | # # print(file1.read()) 135 | # # print() 136 | # # file1.close() 137 | 138 | # # # Write overwrites 139 | # # file1 = open("myfile.txt", "w") # write mode 140 | # # file1.write("Tomorrow \n") 141 | # # file1.close() 142 | 143 | # # file1 = open("myfile.txt", "r") 144 | # # print("Output of Readlines after writing") 145 | # # print(file1.read()) 146 | # # print()# list1 = [1,2,3,4,5,2,9] 147 | # # # file1.close()44 148 | # # list1 = [1,2,3,4,5,2,9] 149 | # # # Program to show various ways to read data from a file. 150 | 151 | # # # Creating a file 152 | # # file1 = open("myfile.txt", "w") 153 | # # L = ["This is Delhi \n", "This is Paris \n", "This is London \n"] 154 | 155 | # # # Writing data to a file 156 | # # file1.write("Hello \n") 157 | # # file1.writelines(L) 158 | # # file1.close() # to change file access modes 159 | 160 | # # file1 = open("myfile.txt", "r+") 161 | 162 | # # print("Output of Read function is ") 163 | # # print(file1.read()) 164 | # # print() 165 | 166 | # # # seek(n) takes the file handle to the nth byte from the beginning. 167 | # # file1.seek(0) 168 | 169 | # # print("Output of Readline function is ") 170 | # # print(file1.readline()) 171 | # # print() 172 | 173 | 174 | # # # readlines function 175 | # # print("Output of Readlines function is ") 176 | # # print(file1.readlines()) 177 | # # print() 178 | # # file1.close() 179 | 180 | 181 | 182 | # # r = open("file.txt") 183 | # # # Read the content of the file 184 | # # content = r.read() 185 | # # # Close the file 186 | # # r.close() 187 | # # print(r.read()) 188 | # # print(content) 189 | 190 | 191 | # # # a = open("file.txt", "a") 192 | 193 | 194 | # # w = open("file.txt" , "w") 195 | 196 | # # # Write some content to the file 197 | # # w.write("Hello, this is a test file.\n") 198 | 199 | # # # Close the file 200 | 201 | # # w.close() 202 | 203 | 204 | # # r = open("file.txt","r") 205 | 206 | # # # Read the content of the file 207 | 208 | # # content = r.read() 209 | 210 | # # # Close the file 211 | 212 | # # r.close() 213 | # # print(content) 214 | 215 | # # w = open("file4.xls","w") 216 | 217 | # # # Write some content to the file 218 | 219 | # # w.write("This is new file 1.\n") 220 | # # w.write("This is new file 2.\n") 221 | # # w.write("This is new file 3.\n") 222 | # # w.write("This is new file 4.\n") 223 | # # w.write("This is new file 5.\n") 224 | # # w.write("This is new file 6.\n") 225 | # # L = ["uzar\t","ri"] 226 | # # # w.write(L) 227 | 228 | 229 | # # #Close the file 230 | # # w.close() 231 | 232 | # # r = open("file4.xls" , "r") 233 | 234 | # # # Read the content of the file 235 | # # content = r.read() 236 | # # r.seek(0) 237 | 238 | # # content1 = r.readlines() 239 | # # # content = r.readline() 240 | 241 | # # # Close the fil 242 | 243 | # # r.close() 244 | # # # ls = content1 245 | # # # first = ls[0] 246 | # # # print(first) 247 | # # print(content) 248 | # # print(content1) 249 | 250 | 251 | 252 | 253 | # # print(content) 254 | 255 | 256 | # # r = open("file.txt" ,"r") 257 | # # # Read the content of the file 258 | # # content = r.read() 259 | # # r.close() 260 | # # print(content) 261 | 262 | # # w = open("file.txt" , "w") 263 | # # # Write some content to the file 264 | # # w.write("This is new file 1.\n") 265 | # # w.write("This is new file 1.\n") 266 | # # w.close 267 | 268 | # # r = open("file.txt" ,"r") 269 | # # # Read the content of the file 270 | # # # r.seek(0) 271 | # # print(r.read()) 272 | # # r.close() 273 | # # # print(content) 274 | 275 | # # w= open("file2.txt" , "w") 276 | # # # Write some content to the file 277 | # # w.write("This is new file 2.\n") 278 | # # w.write("This is new file 3.\n") 279 | 280 | # # w.close() 281 | 282 | # # r = open("file2.txt" , "r") 283 | # # # Read the content of the file 284 | # # # r.seek(1) 285 | # # content = r.readline(10) 286 | # # r.close() 287 | # # print(content) # prints: Hello, World! 288 | 289 | 290 | # # a = open("file.txt" , "a+") 291 | # # # Write some content to the file 292 | # # # a.seek(0) 293 | # # # a.write("uzair") 294 | # # a.seek(0) 295 | # # con = a.read() 296 | # # a.close() 297 | # # print(con) 298 | # # r = open("file.txt" , "r") 299 | # # # Read the content of the file 300 | # # content = r.read() 301 | # # r.close() 302 | # # print(content) 303 | 304 | # # r= open("file.txt" , "") 305 | # # with open("file4.txt" , "r") as w: 306 | # # w.write("This is new file 2.\n") 307 | # # w.write("This is new file 3.\n") 308 | # # w.seek(0) 309 | # # content = w.read() 310 | # # print(content) 311 | 312 | # # with open("file.bin" ,"wb+") as rb: 313 | # # rb.write(b"uzair") 314 | # # rb.seek(0) 315 | # # content = rb.read() 316 | # # bn = int(content , 2 ) 317 | # # print(content) 318 | # # print(bn) 319 | 320 | # # with open("file.bin", "wb+") as rb: 321 | # # rb.write(b"uzair") # Write byte string "uzair" to the file 322 | # # rb.seek(0) # Move the pointer back to the start of the file 323 | # # content = rb.read() # Read the content from the file 324 | 325 | # # # Convert each byte to binary 326 | # # binary_representation = ''.join(format(byte, '08b') for byte in content) 327 | 328 | # # # print("Content as text:", content.decode()) # Decoding to show the text representation 329 | # # # print("Content in binary:", binary_representation) 330 | 331 | # # # binary_string = "0111010101111010011000010110100101110010" 332 | 333 | # # # # Split the binary string into chunks of 8 bits 334 | # # # binary_values = [binary_string[i:i+8] for i in range(0, len(binary_string), 8)] 335 | 336 | # # # # Convert each binary value to its corresponding ASCII character 337 | # # # ascii_string = ''.join([chr(int(bv, 2)) for bv in binary_values]) 338 | 339 | # # # print(ascii_string) 340 | 341 | 342 | # # # # f = open("file.txt", "w") 343 | 344 | # # # # f.write("Hello, World!\n") 345 | # # # # f.write("This is a new line.\n") 346 | # # # # f.close() 347 | 348 | # # # f = open("file.txt", "a") 349 | 350 | # # # f.write("This is another new line.\n") 351 | 352 | # # # f.close() 353 | 354 | # # # f = open("file.txt", "r") 355 | 356 | # # # content = f.read() 357 | 358 | 359 | 360 | # # # print(content) 361 | 362 | # w = open("file.txt", "w") 363 | 364 | # w.write("This is new data") 365 | 366 | # w.close() 367 | 368 | # r = open("file.txt", "r") 369 | # content = r.read() 370 | # r.close() 371 | # print(content) 372 | 373 | # w = open("file5.txt", "w") 374 | # w.write("new file created ") 375 | # # w.close 376 | 377 | # # # a = open("file.txt", "a") 378 | # # # a.write("\nThis is second data") 379 | 380 | # # # a.close() 381 | 382 | # # r= open("file3.txt", "r+") 383 | # # r.write("This written using r+") 384 | # # r.seek(2) 385 | # # content = r.read() 386 | # # # print(content) 387 | # # print(content) 388 | # # r.close() 389 | 390 | 391 | 392 | # # print(content) 393 | 394 | # # r = open("file.txt" ,"r" ) 395 | 396 | # # # Read the content of the file 397 | # # content = r.read() 398 | 399 | # # r.close() 400 | # with open("file4.txt", "w+") as r: 401 | # r.write("\nuzair") 402 | # r.seek(0) 403 | # content = r.read() 404 | # print(content) 405 | 406 | 407 | # # r = open("file.txt" ,"w" ) 408 | 409 | # # # Read the content of the file 410 | 411 | # # r.write("\nuzaiir") 412 | 413 | # # r.close() 414 | 415 | # # g = open("file.txt", "r") 416 | 417 | # # # Read the content of the file 418 | 419 | # # content = g.read() 420 | 421 | # # g.close() 422 | 423 | # # print(content) -------------------------------------------------------------------------------- /File Handling/file.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/File Handling/file.txt -------------------------------------------------------------------------------- /File Handling/file2.txt: -------------------------------------------------------------------------------- 1 | This is new file 2. 2 | This is new file 3. 3 | -------------------------------------------------------------------------------- /File Handling/file3.txt: -------------------------------------------------------------------------------- 1 | This written using r+ -------------------------------------------------------------------------------- /File Handling/file4.txt: -------------------------------------------------------------------------------- 1 | 2 | uzair -------------------------------------------------------------------------------- /File Handling/file5.txt: -------------------------------------------------------------------------------- 1 | new file created -------------------------------------------------------------------------------- /Functions/function.py: -------------------------------------------------------------------------------- 1 | # # def even_odd(x): 2 | # # if x % 2 == 0: 3 | # # return "even" 4 | # # else: 5 | # # return "odd" 6 | 7 | # # print(even_odd(4)) 8 | # # # # for x in range(1,5): 9 | # # # # user_input = int(input(f"wrrite your {x} number")) 10 | # # # print(even_odd(10)) 11 | 12 | # # # # def print (): 13 | # # # # pass 14 | 15 | # # # print("hello") 16 | 17 | 18 | 19 | # # # # even_odd(int(input("write number "))) 20 | # # # # even_odd(int(input("write number "))) 21 | # # # # even_odd(int(input("write number "))) 22 | 23 | 24 | # # # # print("") 25 | 26 | # # # def fun(): 27 | # # # print("Welcome to GFG") 28 | # # # print("Welcome to GFG") 29 | # # # print("Welcome to GFG") 30 | # # # print("Welcome to GFG") 31 | 32 | 33 | 34 | 35 | # # # fun() 36 | # # # fun() 37 | 38 | 39 | 40 | # # # Here a,b are the parameters 41 | # # # def sum(a : int, b : int ) -> int: 42 | # # # return a + b 43 | # # # print(a+b) 44 | 45 | 46 | 47 | 48 | # # # print(sum(8,9)) 49 | 50 | 51 | # # # def is_prime(n): 52 | # # # if n <= 1: 53 | # # # return False 54 | # # # for i in range(2, int((n ** 0.5))): 55 | # # # if n % i == 0: 56 | # # # return False 57 | # # # return True 58 | 59 | 60 | # # # # print(is_prime(9)) 61 | 62 | # # # def myFun(**kwargs): 63 | # # # for key, value in kwargs.items(): 64 | # # # print(f"{key} = {value}") 65 | 66 | 67 | # # # # Driver code 68 | # # # myFun(first='Geeks', mid='for', last='Geeks') 69 | 70 | # # # def add(fir,a): 71 | # # # """Add two numbers""" 72 | # # # return f" {a + b}" 73 | 74 | # # # # Driver code 75 | # # # print(add(1,2)) 76 | 77 | # # def person_name(first_name , Second_name, age ): 78 | # # print(f"this is your first name {first_name} This is your second name {Second_name} and my age is {age}") 79 | 80 | # # person_name( age = 20 ,Second_name="yasin" ,first_name= "uzair" ) 81 | 82 | # # # def sum(x,y): 83 | # # # return x + y 84 | 85 | # # # print(sum(2,7)) 86 | 87 | # # # def add(*argv): 88 | # # # y = 0 89 | # # # for x in argv: 90 | # # # return y + = x 91 | 92 | 93 | # # # # print(add(2,3,5)) 94 | 95 | # # def myFun(*argv): 96 | # # for items in argv: 97 | # # print(items) 98 | 99 | 100 | # # myFun("uzair","yasin" ,20) 101 | 102 | 103 | # def myFun(**kargv): 104 | # # print(kargv) 105 | # """This function is about key word arguments""" 106 | # for key, value in kargv.items(): 107 | # print(f"{key} = {value}") 108 | 109 | 110 | 111 | # myFun( first = "uzair", sec = "yasin" ,age = 20 ) 112 | # print(myFun.__doc__) 113 | 114 | # # # class Car: 115 | # # # def __init__(self ,color,model,company,size): 116 | # # # self.color = color 117 | # # # self.model = model 118 | # # # self.company = company 119 | # # # self.size = size 120 | # # # def info(self): 121 | # # # print(f"this car is {self.color} color and its model is {self.model} it is a {self.size} size car and it is made by {self.company} company ") 122 | 123 | # # # def drive(self): 124 | # # # print("the car is driving") 125 | # # # def dance(self): 126 | # # # print("the car is dancing") 127 | # # # def song(self): 128 | # # # print("the car is singing a song") 129 | 130 | 131 | # # # c1 = Car("red" ,2024,"Supra","4x4") 132 | # # # print(c1.color) 133 | # # # c1.dance() 134 | # # # c1.drive() 135 | # # # c1.info() 136 | 137 | 138 | # # # def add(x,y): 139 | # # # return x + y 140 | 141 | # # count = 0 142 | # # while count == 0: 143 | # # print("while") 144 | # # count = count + 1 145 | 146 | 147 | # # # x = 10 148 | # # # y = 20 149 | # # # summ = lambda x,y,z : x+y+z 150 | # # # print(summ(10,18,16)) 151 | 152 | # # def div(x,y): 153 | # # return x/y 154 | 155 | # # def even_odd(n): 156 | # # if n % 2 == 0 : 157 | # # return "even" 158 | # # else: 159 | # # return "odd" 160 | 161 | 162 | # # ans = div(10 , 2) 163 | # # print(ans) 164 | # # print(even_odd(ans)) 165 | 166 | # # list1 = [] 167 | 168 | # # for x in range(3): 169 | # # ans = even_odd(int(input("number :"))) 170 | # # print(ans) 171 | 172 | # # if ans == "even" : 173 | # # list1.append(ans) 174 | # # else: 175 | # # print(ans) 176 | # # print(list1) 177 | 178 | # def add(x,y): 179 | # return x + y 180 | 181 | # add = lambda x,y : x+y 182 | # print(add(2,3)) 183 | 184 | # name = "uzair" 185 | # li = list(name) 186 | # li[2] = "h" 187 | # str2 = "" .join(li) 188 | # print(li) 189 | # print(str2) 190 | # name[2] = "h" 191 | # print(name 192 | 193 | 194 | # def even_odd(user_input): 195 | # """This function is used to check whether a user input is even odd""" 196 | # if user_input % 2 == 0: 197 | # print("it even") 198 | # else: 199 | # print("it is odd") 200 | 201 | 202 | 203 | 204 | 205 | # user_input = int(input("write any number")) 206 | # even_odd(user_input) 207 | # print(even_odd.__doc__) 208 | 209 | 210 | # # A simple Python function 211 | # def fun(): 212 | # print("Welcome to GFG") 213 | 214 | # name = "uzair" 215 | 216 | # def add( x , y ,z , a = 3 , b = 2 ,h = 1): 217 | # z = x + y 218 | # return z 219 | 220 | # # num1 = int(input("number 1 :")) 221 | # # num2 = int(input("number 2 :")) 222 | 223 | 224 | # print(add(1)) 225 | 226 | # def intro(name,age,qualification ,city ,grade,degree): 227 | # print(f"My name is {name} and age is {age} and qualifier is {qualification} and my city is {city} and my grade is {grade} and my degree is {degree}") 228 | 229 | # intro(city = "Lahore", grade="A",name = "Uzair",age=20,qualification="Bs" ,degree = "bscs") 230 | 231 | # def add(**a): 232 | # for x , y in a.items(): 233 | # print(f"{x} = {y}") 234 | # add(a = 1, b = 2, c = 4) 235 | 236 | 237 | 238 | 239 | # add = lambda x : x**2 240 | # print(add(9)) 241 | 242 | 243 | 244 | # # print(print.__doc__) 245 | 246 | # def add1(x): 247 | # return x**2 248 | 249 | # add2 = lambda x : x**2 250 | 251 | # print(add1(9)) 252 | # print(add2(9)) 253 | -------------------------------------------------------------------------------- /Functions/image-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/Functions/image-1.png -------------------------------------------------------------------------------- /Functions/image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/Functions/image.png -------------------------------------------------------------------------------- /Functions/prime.md: -------------------------------------------------------------------------------- 1 | Let's use `17` as an example to illustrate how checking up to the square root works: 2 | 3 | ### Steps to Determine if 17 is Prime 4 | 5 | 1. **Calculate the Square Root:** 6 | - The square root of 17 is approximately \( \sqrt{17} \approx 4.12 \). 7 | - Therefore, we need to check for factors up to \( \text{int}(4.12) + 1 = 5 \). 8 | 9 | 2. **Check Divisibility:** 10 | - We’ll check if 17 is divisible by any integer from 2 up to 4 (the integer part of the square root). 11 | 12 | **Checking each divisor:** 13 | - **2:** \( 17 \div 2 = 8.5 \) (17 is not divisible by 2, as it does not result in an integer) 14 | - **3:** \( 17 \div 3 \approx 5.67 \) (17 is not divisible by 3) 15 | - **4:** \( 17 \div 4 = 4.25 \) (17 is not divisible by 4) 16 | 17 | 3. **Conclusion:** 18 | - Since 17 is not divisible by any number up to its square root (which is 4), it has no divisors other than 1 and itself. 19 | 20 | ### Summary: 21 | - For `n = 17`, the square root is approximately 4.12. 22 | - We check for divisors up to 4. 23 | - 17 is not divisible by 2, 3, or 4. 24 | - Therefore, 17 is a prime number. 25 | 26 | **Why This Works:** 27 | - If 17 had any divisors, one of them would have to be less than or equal to the square root of 17. 28 | - Since there are no such divisors (less than or equal to 4) that divide 17 evenly, 17 must be prime. 29 | 30 | Let's use `78` to determine if it's a prime number by checking up to its square root. 31 | 32 | ### Steps to Determine if 78 is Prime 33 | 34 | 1. **Calculate the Square Root:** 35 | - The square root of 78 is approximately \( \sqrt{78} \approx 8.83 \). 36 | - Therefore, we need to check for factors up to \( \text{int}(8.83) + 1 = 9 \). 37 | 38 | 2. **Check Divisibility:** 39 | - We’ll check if 78 is divisible by any integer from 2 up to 8 (the integer part of the square root). 40 | 41 | **Checking each divisor:** 42 | - **2:** \( 78 \div 2 = 39 \) (78 is divisible by 2, and the result is an integer, 39) 43 | - Since 78 is divisible by 2, it is not a prime number. 44 | 45 | However, for completeness, let’s check the remaining potential divisors: 46 | 47 | - **3:** \( 78 \div 3 = 26 \) (78 is divisible by 3) 48 | - **4:** \( 78 \div 4 = 19.5 \) (78 is not divisible by 4) 49 | - **5:** \( 78 \div 5 = 15.6 \) (78 is not divisible by 5) 50 | - **6:** \( 78 \div 6 = 13 \) (78 is divisible by 6) 51 | - **7:** \( 78 \div 7 \approx 11.14 \) (78 is not divisible by 7) 52 | - **8:** \( 78 \div 8 = 9.75 \) (78 is not divisible by 8) 53 | 54 | 3. **Conclusion:** 55 | - Since 78 is divisible by 2 (and other numbers like 3 and 6), it is not a prime number. 56 | 57 | ### Summary: 58 | - For `n = 78`, the square root is approximately 8.83. 59 | - We check divisibility up to 8. 60 | - 78 is divisible by 2, 3, and 6, among others. 61 | - Therefore, 78 is not a prime number. 62 | 63 | **Explanation of Why This Works:** 64 | - If a number `n` has any divisors, one of them must be less than or equal to the square root of `n`. 65 | - Since we found that 78 is divisible by 2 (and 3, and 6), we confirmed that 78 is not a prime number. -------------------------------------------------------------------------------- /Functions/prime.py: -------------------------------------------------------------------------------- 1 | 2 | n = 58080 3 | 4 | 5 | if n <= 1: 6 | print("its not a prime ") 7 | for x in range (2, n): 8 | if n % x == 0: 9 | print("its not a prime number") 10 | else: 11 | print("its a prime number") 12 | -------------------------------------------------------------------------------- /If_Statement/if elif statement flow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/If_Statement/if elif statement flow.png -------------------------------------------------------------------------------- /If_Statement/if else statement flow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/If_Statement/if else statement flow.png -------------------------------------------------------------------------------- /If_Statement/if statement flow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/If_Statement/if statement flow.png -------------------------------------------------------------------------------- /If_Statement/if.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 4, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "i is 20\n" 13 | ] 14 | } 15 | ], 16 | "source": [ 17 | "\n", 18 | "i = 25\n", 19 | "if (i == 10):\n", 20 | " print(\"i is 10\")\n", 21 | "elif (i == 21):\n", 22 | " print(\"i is 15\")\n", 23 | "elif (i == 22):\n", 24 | " print(\"i is 20\")\n", 25 | "elif (i == 0):\n", 26 | " print(\"i is 20\")\n", 27 | "elif (i == 19):\n", 28 | " print(\"i is 20\")\n", 29 | "elif (i == 25):\n", 30 | " print(\"i is 20\")\n", 31 | "elif (i == 18):\n", 32 | " print(\"i is 20\")\n", 33 | "elif (i == 30):\n", 34 | " print(\"i is 20\")\n", 35 | "elif (i == 90):\n", 36 | " print(\"i is 20\") \n", 37 | "else:\n", 38 | " print(\"i is not present\")" 39 | ] 40 | } 41 | ], 42 | "metadata": { 43 | "kernelspec": { 44 | "display_name": "Python 3", 45 | "language": "python", 46 | "name": "python3" 47 | }, 48 | "language_info": { 49 | "codemirror_mode": { 50 | "name": "ipython", 51 | "version": 3 52 | }, 53 | "file_extension": ".py", 54 | "mimetype": "text/x-python", 55 | "name": "python", 56 | "nbconvert_exporter": "python", 57 | "pygments_lexer": "ipython3", 58 | "version": "3.12.5" 59 | } 60 | }, 61 | "nbformat": 4, 62 | "nbformat_minor": 2 63 | } 64 | -------------------------------------------------------------------------------- /If_Statement/if.md: -------------------------------------------------------------------------------- 1 | # Python If Else Statements – Conditional Statements 2 | 3 | ### In both real life and programming, decision-making is crucial. We often face situations where we need to make choices, and based on those choices, we determine our next actions. Similarly, in programming, we encounter scenarios where we must make decisions to control the flow of our code. 4 | ### As the name suggests, If-Else statements offer two paths, allowing for different outcomes depending on the condition evaluated. 5 | 6 | 7 | ## Types of Control Flow in Python 8 | 9 |
    10 |
  1. Python If Statement
  2. 11 |
  3. Python If Else Statement
  4. 12 |
  5. Python Elif
  6. 13 |
  7. Python Nested If Statement
  8. 14 |
  9. Ternary Statement | Short Hand If Else Statement
  10. 15 |
16 | 17 | ## Python If Statement 18 | ### The if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not. 19 | 20 | 21 | ## Syntax 22 | 23 | 24 | 25 | # Example of Python if Statement 26 | 27 | ```Python 28 | i = 10 29 | 30 | if (i > 15): 31 | print("10 is less than 15") 32 | print("I am Not in if") 33 | ``` 34 | 35 | # Python If Else Statement 36 | ### The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But if we want to do something else if the condition is false, we can use the else statement with the if statement Python to execute a block of code when the Python if condition is false. 37 | 38 | ## Flowchart of If Else Statement 39 | 40 | 41 | 42 | ## Syntax of If Else in Python 43 | 44 | 45 | 46 | ## Example of Python If Else Statement 47 | 48 | ```Python 49 | i = 20 50 | if (i < 15): 51 | print("i is smaller than 15") 52 | print("i'm in if Block") 53 | else: 54 | print("i is greater than 15") 55 | print("i'm in else Block") 56 | print("i'm not in if and not in else Block") 57 | 58 | ``` 59 | ## Python Elif 60 | 61 | ### Here, a user can decide among multiple options. The if statements are executed from the top down. 62 | 63 | ### As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final “else” statement will be executed. 64 | 65 | ## Flowchart of Elif Statement in Python 66 | 67 | 68 | ## Syntax of If Elif in Python 69 | 70 | 71 | ## Example of Python If Elif Statement 72 | 73 | ```Python 74 | 75 | i = 25 76 | if (i == 10): 77 | print("i is 10") 78 | elif (i == 15): 79 | print("i is 15") 80 | elif (i == 20): 81 | print("i is 20") 82 | else: 83 | print("i is not present") 84 | ``` 85 | ## Python Nested If Statement 86 | ### Nested if statements mean an if statement inside another if statement. 87 | 88 | ## Flowchart of Nested If Statement in Python 89 | 90 | 91 | ## Syntax of Nested If in Python 92 | 93 | 94 | ## Example of Python Nested If Statement 95 | 96 | ```Python 97 | i = 10 98 | if (i == 10): 99 | 100 | # First if statement 101 | if (i < 15): 102 | print("i is smaller than 15") 103 | 104 | # Nested - if statement 105 | # Will only be executed if statement above 106 | # it is true 107 | if (i < 12): 108 | print("i is smaller than 12 too") 109 | else: 110 | print("i is greater than 15") 111 | ``` 112 | 113 | ## Ternary Statement | Short Hand If Else Statement 114 | ### Whenever there is only a single statement to be executed inside the if block then shorthand if can be used. The statement can be put on the same line as the if statement. 115 | 116 | ## Syntax of Ternary or Short hand If Else in Python 117 | 118 | 119 | ## Example of Python Shorthand If Statement 120 | ```Python 121 | i = 10 122 | if i < 15: print("i is less than 15") 123 | ``` 124 | ## Example of Python Shorthand If Else Statement 125 | ```Python 126 | i = 10 127 | print(True) if i < 15 else print(False) 128 | ``` 129 | -------------------------------------------------------------------------------- /If_Statement/if.py: -------------------------------------------------------------------------------- 1 | # # i = 10 2 | # # if (i > 15): 3 | # # t in the list") print("10 is less than 15") 4 | # # print("I am Not in if") 5 | 6 | # i = 20 7 | # if (i > 15): 8 | # print("i is smaller than 15") 9 | # print("i'm in if Block") 10 | # else: 11 | # print("i is greater than 15") 12 | # print("i'm in else Block") 13 | # print("i'm not in if and not in else Block") 14 | 15 | # i = 25 16 | # if (i == 10): 17 | # print("i is 10") 18 | # elif (i == 21): 19 | # print("i is 15") 20 | # elif (i == 22): 21 | # print("i is 20") 22 | # elif (i == 0): 23 | # print("i is 20") 24 | # elif (i == 19): 25 | # print("i is 20") 26 | # elif (i == 25): 27 | # print("i is 20") 28 | # elif (i == 18): 29 | # print("i is 20") 30 | # elif (i == 30): 31 | # print("i is 20") 32 | # elif (i == 90): 33 | # print("i is 20") 34 | # else: 35 | # print("i is not present") 36 | 37 | # num = [1,2,3,4,5] 38 | # for x in num: 39 | # if (x == 4): 40 | # print("the num is present") 41 | # else: 42 | # print("the num is not present") 43 | 44 | 45 | # num = [1,2,3,4,5] 46 | # if 4 in num: 47 | # print("the num is present") 48 | # else: 49 | # print("the num is not present") 50 | 51 | # Nested If 52 | # i = 10 53 | # if (i == 1): 54 | # print("condition true move forward to next if") 55 | # if (i < 12): 56 | # print("second condition is true") 57 | # if (i< 50): 58 | # print("third condition is true") 59 | # else: 60 | # print("third condition is false") 61 | # else: 62 | # print("second condition is false") 63 | # else : 64 | # print("first condition is false ") 65 | 66 | 67 | # i = 10 68 | # if (i < 15) : print("i is less than 15") 69 | 70 | # i = 10 71 | # print(True) if (i < 15) else print(False) 72 | 73 | 74 | # num = int(input("what is your age : ")) 75 | # num2 = int(input("what is your age : ")) 76 | 77 | # minus = num - num2 78 | # print(minus) 79 | 80 | # i = 10 81 | 82 | # if (i == 9): 83 | # print("10 is greater than 9") 84 | # print("uzair") 85 | # print("uzair") 86 | # print("uzair") 87 | 88 | # print("I am Not in if") 89 | 90 | 91 | # i = 20 92 | # if (i > 15): 93 | 94 | # print("i is smaller than 15") 95 | # print("i'm in if Block") 96 | # else: 97 | # print("i is greater than 15") 98 | # print("i'm in else Block") 99 | # print("i'm not in if and not in else Block") 100 | 101 | # i = 10 102 | 103 | # if (i < 10): 104 | # print("10 is less than 15") 105 | # elif (i != 10): 106 | # print("10 is equal to 10") 107 | # elif (i > 10): 108 | # print("10 is equal to 10") 109 | # elif (i != 10): 110 | # print("10 is equal to 10") 111 | # else: 112 | # print("else") 113 | 114 | # # print("I am Not in if") 115 | # i = int(input("write your marks")) 116 | 117 | # if (i > 50): 118 | # print("A") 119 | # elif (i > 70): 120 | # print("B") 121 | # elif (i > 90): 122 | # print("c") 123 | # elif (i > 70): 124 | # print("B") 125 | # elif (i > 40): 126 | # print("c") 127 | # elif (i > 30): 128 | # print("B") 129 | # elif (i > 10): 130 | # print("c") 131 | # else: 132 | # print("you are fail") 133 | 134 | # i = 10 135 | # if (i == 10): 136 | # print("parentt if") 137 | # if (i > 9 ): 138 | # print("child if") 139 | # if (i == 11): 140 | # print("second child") 141 | # else: 142 | # print("second else") 143 | # else: 144 | # print("child else") 145 | # else: 146 | # print("parent else") 147 | 148 | # i = 10 149 | # if (i == 10): 150 | 151 | # # First if statement 152 | # if (i < 15): 153 | # print("i is smaller than 15") 154 | 155 | # # Nested - if statement 156 | # # Will only be executed if statement above 157 | # # it is true 158 | # if (i < 12): 159 | # print("i is smaller than 12 too") 160 | # else: 161 | # print("i is greater than 15") 162 | 163 | 164 | 165 | # i = 10 166 | # if i < 15: print("i is less than 15") else print("uzair") 167 | 168 | i = 10 169 | print(True) if i > 15 else print(False) -------------------------------------------------------------------------------- /If_Statement/main.py: -------------------------------------------------------------------------------- 1 | # Output 2 | # print("Hello World") 3 | 4 | # Data types 5 | 6 | # Primitive and Non primitive 7 | 8 | 9 | # primitive : u can store single value 10 | 11 | # str : string : anything which comes inside inverted commas is called string 12 | # int : integer : 123546846465468 13 | # float : decimal number : 123.456 14 | # bool : boolean : true/false 15 | 16 | # type() 17 | 18 | # print( type("5765") ) 19 | 20 | # "" 21 | # '' 22 | # ''''' 23 | 24 | 25 | # print(''' 'Quaid' Said : Work "Work" and Work ''') 26 | # print ('''uzair 27 | # yasin ''') 28 | 29 | # Escape Sequence 30 | # \n : new line 31 | # \t : tab space 32 | # \\ : back slash 33 | # print(" 'Quaid' Said : Work \"Work\" and Work ") 34 | # print("uzair \nyasin") 35 | 36 | 37 | # Variables 38 | 39 | # name = 5.5 40 | # print(name) 41 | # Rules of Variable 42 | 43 | # no space 44 | # dont start with integer 45 | # dont use special character 46 | # dont use keyword 47 | 48 | 49 | # meaningful name 50 | # a = 0 51 | # print = "uzair" 52 | # print(print) 53 | 54 | # stages 55 | 56 | # 1. declaration 57 | # 2. initialization 58 | 59 | # name = "uzair" 60 | 61 | 62 | # String 63 | # indexing 64 | # slicing 65 | # steping 66 | # [start : end : step] 67 | # for reversing string we can give step in minus 68 | # name = "My name is Muhammad Uzair and I am a Piaic Student" 69 | # print(name[::]) 70 | 71 | # immutable : anything which is unchangeable 72 | # mutable : anything which is changeable 73 | 74 | 75 | # String function 76 | # 1. lower() 77 | # 2. upper() 78 | # 3. title() 79 | # 4. capitalize() 80 | 81 | 82 | # name = "uzaira" 83 | # Second_str = "" .join("uzair") 84 | # # print(name) 85 | # print(Second_str) 86 | 87 | # print("uzair","yasin" , sep="-") 88 | # print("Yasin ") 89 | 90 | # print("Hello", "World") 91 | # num = False 92 | # print(type(num)) 93 | 94 | 95 | 96 | 97 | # If statement 98 | 99 | # i = 10 100 | 101 | # if (i < 15): 102 | # print("true") 103 | # if (i != 10): 104 | # print("nested") 105 | # else: 106 | # print("c false") 107 | # else: 108 | # print("P false") 109 | 110 | # print("I am Not in if")4 111 | 112 | 113 | # i = 10 114 | # if (i != 10): 115 | # print("i is") 116 | # else: 117 | # print("i is not") 118 | 119 | 120 | 121 | # print("outside if") 122 | 123 | 124 | 125 | # i = 25 126 | # if (i == 10): 127 | # print("i is 10") 128 | # elif (i == 25): 129 | # print("i is 15") 130 | # elif (i == 25): 131 | # print("i is 20") 132 | # else: 133 | # print("i is not present") 134 | # i = 10 135 | # if (i != 10): 136 | # print("parent if ") 137 | # # if (i > 5): 138 | # # print("child if") 139 | # # else: 140 | # # print("child else") 141 | # # else: 142 | # # print("parent else") 143 | 144 | 145 | # i = 10 146 | # if(i == 10): 147 | # print("parent if ") 148 | # if(i < 5): 149 | # print("child if ") 150 | # else: 151 | # print("child else") 152 | # if(i >5): 153 | # print("childesh if") 154 | # else: 155 | # print("parent else") 156 | 157 | 158 | # grading 159 | 160 | # mark > 90 so A grade 161 | # mark > 80 so B grade 162 | # mark > 70 so B+ grade 163 | # mark > 60 so B- grade 164 | # mark > 50 so C grade 165 | # fail 166 | 167 | 168 | # marks = int(input("Enter your marks : ")) 169 | # if marks > 90: 170 | # print("Grade A") 171 | # elif marks > 80: 172 | # print("Grade B") 173 | # elif marks > 70: 174 | # print("Grade C") 175 | # elif marks > 60: 176 | # print("Grade D") 177 | # elif marks > 50: 178 | # print("Grade E") 179 | # else: 180 | -------------------------------------------------------------------------------- /If_Statement/nested if statement flow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/If_Statement/nested if statement flow.png -------------------------------------------------------------------------------- /If_Statement/syantax of if elif statement.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/If_Statement/syantax of if elif statement.png -------------------------------------------------------------------------------- /If_Statement/syantax of if else statement.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/If_Statement/syantax of if else statement.png -------------------------------------------------------------------------------- /If_Statement/syantax of if nested if statement.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/If_Statement/syantax of if nested if statement.png -------------------------------------------------------------------------------- /If_Statement/syantax of if statement.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/If_Statement/syantax of if statement.png -------------------------------------------------------------------------------- /If_Statement/syantax of short hand.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/If_Statement/syantax of short hand.png -------------------------------------------------------------------------------- /List/List methods.md: -------------------------------------------------------------------------------- 1 | ## Python list functions 2 | ## 1 . `Append()` 3 | ### • Description 4 | 5 | Python list append function is a pre-defined function that takes a value as a parameter and adds it at the end of the list. append() function can take any type of data as input, including a number, a string, a decimal number, a list, or another object. 6 | ### • Syntax 7 | It is very easy to use function you just need to call function with list object and passing value as parameter. 8 | 9 | ``` 10 | fruits : list = ["apple", "cherry", "banana"] 11 | fruits.append("grapes") 12 | print(fruits) 13 | 14 | ``` 15 | ### • Return Type None 16 | (This method only adds an element at the end of the list) 17 | 18 | 19 | ## 2 . `Extend()` 20 | 21 | ### • Description 22 | List extend() function is an in-built function of python that extends a list by adding values of an iterable (list,tuple,string) at the end of that list 23 | ### • Syntax 24 | ``` 25 | cars : list = ["Audi","BMW","Jaguar"] 26 | other_cars = ["Maruti", "Tata"] 27 | cars.extend(other_cars) 28 | print(cars) 29 | ``` 30 | ### • Return Type None 31 | (This method extends the list by appending elements from an iterable.) 32 | 33 | ## 3 . `Insert()` 34 | 35 | ### • Description 36 | List insert() method in Python is very useful to insert an element in a list. What makes it different from append() is that the list insert() function can add the value at any position in a list, whereas the append function is limited to adding values at the end. 37 | ### • Syntax 38 | ``` 39 | fruit : list = ["banana","cherry","grape"] 40 | fruit.insert(1,"apple") 41 | print(fruit) 42 | ``` 43 | ### • Return Type None 44 | (This method inserts an element at a specified position.) 45 | 46 | ## 4 .`Remove()` 47 | 48 | ### • Description 49 | List remove() function in Python removes the first occurrence of a given item from the list. It make changes to the current list. It only takes one argument that is the element you want to remove and if that element is not present in the list, it gives ValueError. 50 | ### • Syntax 51 | ``` 52 | lis : list = ['a', 'b', 'c'] 53 | lis.remove("b") 54 | print(lis) 55 | ``` 56 | ### • Return Type None 57 | (This method removes the first occurrence of a specified value.) 58 | 59 | ## 5 .`Pop()` 60 | 61 | ### • Description 62 | List pop() function removes and returns the value at a specific index from a list. It is an inbuilt function of Python. 63 | It can be used with and without parameters; without a parameter list pop() returns and removes the last value from the list by default, but when given an index value as a parameter, it only returns and removes the element at that index. 64 | ### • Syntax 65 | Without parameter it will remove the last element 66 | ``` 67 | fruits : list = ["apple", "mango", "cherry"] 68 | fruits.pop() 69 | print(fruits) 70 | ``` 71 | With parameter it will remove the desired element 72 | ``` 73 | my_list : list = [1, 2, 3, 4, 5, 6] 74 | poped_item = my_list.pop(-2) 75 | print("New list", my_list) 76 | ``` 77 | ### • Return Type 78 | Returns the element that was removed from the list. If no index is specified, It removes and returns the last item. 79 | 80 | ## 6 . `Clear()` 81 | 82 | ### • Description 83 | Python List clear() method removes all items from the List making it an empty/null list. 84 | ### • Syntax 85 | ``` 86 | my_list : list = [1, 2, 3, 4, 5, 6] 87 | lis.clear() 88 | print( my_list) 89 | ``` 90 | ### • Return Type 91 | None ( This method removes all elements from the list.) 92 | 93 | ## 7 . `Index()` 94 | 95 | ### • Description 96 | Python list index() method is used to find position of element in list. 97 | It returns the position of the first occurrence of that element in the list. If the item is not found in the list, index() function raises a “ValueError” error 98 | ### • Syntax 99 | ``` 100 | Animals : list= ["cat", "dog", "tiger"] 101 | print(Animals.index("dog")) 102 | 103 | ``` 104 | ### • Return Type 105 | Returns an integer. This method returns the index of the first occurrence of a specified value. 106 | 107 | ## 8 . `Count()` 108 | 109 | ### • Description 110 | Python list count() function lets you count the occurrence of an element in a list. It returns the count of how many times an element is present in a list. 111 | ### • Syntax 112 | ``` 113 | fruits : list = ["Apple", "Mango", "Banana", "Cherry" , "Papaya"] 114 | print(fruits.count("Apple")) 115 | ``` 116 | ### • Return Type 117 | Returns an integer. This method returns the number of times a specified value appears in the list. 118 | 119 | 120 | ## 9 . `Pop()` 121 | 122 | ### • Description 123 | Python list sort() method sorts the elements of a list. It sorts in ascending order by default but can also sort values in descending order or in a custom manner using its parameters. 124 | ###• Syntax 125 | Without parameter it will sort in ascending order 126 | ``` 127 | random_numbers : list = [2,5,6,1,8,3] 128 | random_numbers.sort () 129 | print(random_numbers) 130 | ``` 131 | With parameter it will sort in ascending order 132 | ``` 133 | numbers : list = [1, 3, 4, 2] 134 | numbers.sort(reverse=True) 135 | print(numbers) 136 | ``` 137 | ### • Return Type 138 | Returns None. This method sorts the list in ascending order and in ascending order 139 | 140 | ## 10. `Reverse()` 141 | 142 | ### • Description 143 | It reverses objects of the List in place i.e. it doesn’t use any extra space but it just modifies the original list 144 | ### • Syntax 145 | ``` 146 | list1 : list = [1, 2, 3, 4, 1, 2, 6] 147 | list1.reverse() 148 | print(list1) 149 | ``` 150 | ### • Return Type 151 | Returns None. This method reverses the elements of the list in place. 152 | 153 | ## 11. `Copy()` 154 | 155 | ### • Description 156 | The list Copy() method makes a new shallow copy of a list. 157 | 158 | • Syntax 159 | ``` 160 | fruits : list = ["mango","apple","strawberry"] 161 | shakes = fruits.copy() 162 | print(shakes) 163 | ``` 164 | ## • Return Type 165 | Returns a new list. This method returns a shallow copy of the list. 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | -------------------------------------------------------------------------------- /List/list.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 7, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "[1, 2, 3, 4, 'uzair', 'yasin', 5.5, True, 'ali']\n" 13 | ] 14 | } 15 | ], 16 | "source": [ 17 | "list1 = [1,2,3,4,\"uzair\", \"yasin\" ,5.5,True]\n", 18 | "list1.append(\"ali\")\n", 19 | "print((list1))" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": 8, 25 | "metadata": {}, 26 | "outputs": [ 27 | { 28 | "name": "stdout", 29 | "output_type": "stream", 30 | "text": [ 31 | "[1, 2, 3, 4, 'uzair', 'yasin', 5.5, True, 'ali']\n" 32 | ] 33 | } 34 | ], 35 | "source": [ 36 | "list1 = [1,2,3,4,\"uzair\", \"yasin\" ,5.5,True]\n", 37 | "list1.append(\"ali\")\n", 38 | "print((list1))" 39 | ] 40 | }, 41 | { 42 | "cell_type": "code", 43 | "execution_count": null, 44 | "metadata": {}, 45 | "outputs": [], 46 | "source": [] 47 | } 48 | ], 49 | "metadata": { 50 | "kernelspec": { 51 | "display_name": "Python 3", 52 | "language": "python", 53 | "name": "python3" 54 | }, 55 | "language_info": { 56 | "codemirror_mode": { 57 | "name": "ipython", 58 | "version": 3 59 | }, 60 | "file_extension": ".py", 61 | "mimetype": "text/x-python", 62 | "name": "python", 63 | "nbconvert_exporter": "python", 64 | "pygments_lexer": "ipython3", 65 | "version": "3.12.5" 66 | } 67 | }, 68 | "nbformat": 4, 69 | "nbformat_minor": 2 70 | } 71 | -------------------------------------------------------------------------------- /List/list.py: -------------------------------------------------------------------------------- 1 | # string = input("Enter elements (Space-Separated): ") 2 | 3 | # # split the strings and store it to a list 4 | # lst = string.split() 5 | # print('The list is:', lst) # printing the list 6 | 7 | 8 | # ls = [1,2,3,4,5] 9 | # ls2 = reversed(ls) 10 | # print(ls) 11 | # print(list(ls2)) 12 | 13 | 14 | # list1 = [1,2,3,4,"uzair", "yasin" ,5.5,True] 15 | 16 | # for x in list1 : 17 | # print(x) 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | # print(list1[]) 26 | 27 | 28 | 29 | # print(list1[-1]) 30 | 31 | # length = len(list1) 32 | # print(length) 33 | # print(type(list1)) 34 | # print(list1) 35 | 36 | 37 | # # string = "uzair yasin ahmed" 38 | # # str2 = string.split() 39 | # # print(str2) 40 | # string = input("Enter elements (Space-Separated): ") 41 | # lst = string.split() 42 | # print('The list is:', lst) 43 | 44 | 45 | # list1 = [1,2,3,4,"uzair", "yasin" ,5.5,True] 46 | # list2= [10,11,12,13] 47 | # list3 = zip(list1 ,list2) 48 | # print(list(list3)) 49 | # print((list1)) 50 | 51 | # list1 = [1,2,3,4,5,2,9] 52 | # list1.reverse() 53 | # print(list1) 54 | 55 | 56 | # list1 = [1,2,3,4,5,2,9] 57 | # list2 = reversed(list1) 58 | # print(list(list2)) 59 | # print(list1) 60 | 61 | # def li(n): 62 | # pass 63 | 64 | # list1 = [1,2,3,4,5,10,] 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | # [2,4,6,8,10,20] 75 | # min_=min(list1) 76 | # max_=max(list1) 77 | # sum_=sum(list1) 78 | # print(min_) 79 | # print(max_) 80 | # print(sum_) 81 | 82 | # list2= sorted(list1 , reverse=True) 83 | # print(list1) 84 | # print(list2) 85 | # value = list1.pop() 86 | # print(value) 87 | # print(list1) 88 | 89 | 90 | # li = [1,2,3,"ali","rafay",5.5,True] 91 | # # # length = len(li) 92 | # print(li[-1]) 93 | 94 | # # print(length) 95 | 96 | # li2=li[1:5] 97 | # print(li) 98 | # li2.pop() 99 | # print(li2) 100 | 101 | li = [1,2,6,3,1] 102 | # li2 =["a","b","c"] 103 | 104 | # max = max(li) 105 | # min = min(li) 106 | # sum = sum(li) 107 | # print(max) 108 | # print(min) 109 | # print(sum) 110 | 111 | 112 | # index= li.index(6) 113 | # print(index) 114 | 115 | # # reverse 116 | # li.reverse() 117 | # print(li) 118 | 119 | # sort 120 | 121 | # li.sort(reverse=True) 122 | # print(li) 123 | 124 | 125 | # # copy 126 | # li2 = li.copy() 127 | # print(li2) 128 | 129 | 130 | # count 131 | # count = li.count(2) 132 | # print(count) 133 | # remove 134 | # ele = li.remove(1) 135 | # print(li) 136 | # print(ele) 137 | 138 | # pop() 139 | # remove_ele = li.pop(2) 140 | # print(remove_ele) 141 | # print(li) 142 | 143 | # clear() 144 | # li.clear() 145 | # print(li) 146 | # delete() 147 | # del li[4] 148 | # print(li) 149 | 150 | 151 | 152 | # # insert 153 | # # li.insert(1,"ahmed") 154 | # # print(li) 155 | # # # append 156 | # # li.append(10) 157 | # # print(li) 158 | # # # extend 159 | # li.extend(li2) 160 | # print(li) 161 | 162 | li = [] 163 | 164 | for x in range(1,4): 165 | user_input = int(input(f"enter {x} number :")) 166 | li.append(user_input) 167 | print(tuple(li)) 168 | 169 | 170 | 171 | 172 | # tu = (1,2,3,4,4,"uzair" , 5.6) 173 | 174 | # count = tu.count(4) 175 | # print(count) 176 | 177 | 178 | 179 | 180 | # tu = (1,) 181 | 182 | # print(type(tu)) 183 | -------------------------------------------------------------------------------- /Loops in Python/a.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 3, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "1\n", 13 | "2\n", 14 | "3\n", 15 | "4\n" 16 | ] 17 | } 18 | ], 19 | "source": [ 20 | "for x in [1,2,3,4,5,6,7,8,9]:\n", 21 | " if x == 5:\n", 22 | " break\n", 23 | " print(x)" 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "execution_count": null, 29 | "metadata": {}, 30 | "outputs": [], 31 | "source": [] 32 | } 33 | ], 34 | "metadata": { 35 | "kernelspec": { 36 | "display_name": "Python 3", 37 | "language": "python", 38 | "name": "python3" 39 | }, 40 | "language_info": { 41 | "codemirror_mode": { 42 | "name": "ipython", 43 | "version": 3 44 | }, 45 | "file_extension": ".py", 46 | "mimetype": "text/x-python", 47 | "name": "python", 48 | "nbconvert_exporter": "python", 49 | "pygments_lexer": "ipython3", 50 | "version": "3.12.5" 51 | } 52 | }, 53 | "nbformat": 4, 54 | "nbformat_minor": 2 55 | } 56 | -------------------------------------------------------------------------------- /Loops in Python/ahbf.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "1 1\n", 13 | "1 2\n", 14 | "1 3\n", 15 | "2 1\n", 16 | "2 2\n", 17 | "2 3\n", 18 | "3 1\n", 19 | "3 2\n", 20 | "3 3\n" 21 | ] 22 | } 23 | ], 24 | "source": [ 25 | "for x in range(1,4):\n", 26 | " for y in range(1,4):\n", 27 | " print(x,y)\n", 28 | " " 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": null, 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [ 37 | "for x in range(1,4):\n", 38 | " for y in range(1,4):\n", 39 | " print(x,y)\n", 40 | " " 41 | ] 42 | } 43 | ], 44 | "metadata": { 45 | "kernelspec": { 46 | "display_name": "Python 3", 47 | "language": "python", 48 | "name": "python3" 49 | }, 50 | "language_info": { 51 | "codemirror_mode": { 52 | "name": "ipython", 53 | "version": 3 54 | }, 55 | "file_extension": ".py", 56 | "mimetype": "text/x-python", 57 | "name": "python", 58 | "nbconvert_exporter": "python", 59 | "pygments_lexer": "ipython3", 60 | "version": "3.12.5" 61 | } 62 | }, 63 | "nbformat": 4, 64 | "nbformat_minor": 2 65 | } 66 | -------------------------------------------------------------------------------- /Loops in Python/for.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 2, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "1 1\n", 13 | "1 2\n", 14 | "1 3\n", 15 | "2 1\n", 16 | "2 2\n", 17 | "2 3\n", 18 | "3 1\n", 19 | "3 2\n", 20 | "3 3\n" 21 | ] 22 | } 23 | ], 24 | "source": [ 25 | "for x in range(1,4):\n", 26 | " for y in range(1,4):\n", 27 | " print(x,y)" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": null, 33 | "metadata": {}, 34 | "outputs": [ 35 | { 36 | "name": "stdout", 37 | "output_type": "stream", 38 | "text": [ 39 | "1\n", 40 | "2\n", 41 | "3\n" 42 | ] 43 | } 44 | ], 45 | "source": [ 46 | "name = \"uzair\"\n", 47 | "for character in name:\n", 48 | " print(character)" 49 | ] 50 | }, 51 | { 52 | "cell_type": "code", 53 | "execution_count": null, 54 | "metadata": {}, 55 | "outputs": [ 56 | { 57 | "name": "stdout", 58 | "output_type": "stream", 59 | "text": [ 60 | "u\n", 61 | "z\n", 62 | "a\n", 63 | "i\n", 64 | "r\n" 65 | ] 66 | } 67 | ], 68 | "source": [] 69 | } 70 | ], 71 | "metadata": { 72 | "kernelspec": { 73 | "display_name": "Python 3", 74 | "language": "python", 75 | "name": "python3" 76 | }, 77 | "language_info": { 78 | "codemirror_mode": { 79 | "name": "ipython", 80 | "version": 3 81 | }, 82 | "file_extension": ".py", 83 | "mimetype": "text/x-python", 84 | "name": "python", 85 | "nbconvert_exporter": "python", 86 | "pygments_lexer": "ipython3", 87 | "version": "3.12.5" 88 | } 89 | }, 90 | "nbformat": 4, 91 | "nbformat_minor": 2 92 | } 93 | -------------------------------------------------------------------------------- /Loops in Python/for.md: -------------------------------------------------------------------------------- 1 | # For Loops in Python 2 | 3 | ### Python For loop is used for iterating over an iterable like a String, Tuple, List, Set, or Dictionary. 4 | 5 | ## Table of Content 6 | 7 | 1. How to use the for loop in Python 8 | 1. Python For Loop Syntax 9 | 1. Python For Loop with String 10 | 1. Python for loop with Range 11 | 1. Python for loop Enumerate 12 | 1. Nested For Loops in Python 13 | 1. Python For Loop Over List 14 | 1. Control Statements that can be used with For Loop in Python 15 | 16 | 17 | ## How to use the for loop in Python 18 | ### In Python, the for loop is used to iterate over a sequence (such as a list, tuple, string, or dictionary) or any iterable object. The basic syntax of the for loop is: 19 | ## Python For Loop Syntax 20 | 21 | 22 | ## Python For Loop with String 23 | ```python 24 | # Iterating over a String 25 | print("String Iteration") 26 | 27 | s = "Geeks" 28 | for i in s: 29 | print(i) 30 | ``` 31 | 32 | ## Python for loop with Range 33 | ```python 34 | for i in range(0, 10, 2): 35 | print(i) 36 | ``` 37 | ## Python for loop Enumerate 38 | ### In Python, the enumerate() function is used with the for loop to iterate over an iterable while also keeping track of the index of each item. 39 | ```python 40 | l1 = ["eat", "sleep", "repeat"] 41 | 42 | for count, ele in enumerate(l1): 43 | print (count, ele) 44 | ``` 45 | ## Nested For Loops in Python 46 | ```python 47 | for i in range(1, 4): 48 | for j in range(1, 4): 49 | print(i, j) 50 | ``` 51 | ## Python For Loop Over List 52 | ``` python 53 | # Python program to illustrate 54 | # Iterating over a list 55 | l = ["geeks", "for", "geeks"] 56 | 57 | for i in l: 58 | print(i) 59 | ``` 60 | ## Continue in Python For Loop 61 | ### Python Continue Statement skips the execution of the program block after the continue statement and forces the control to start the next iteration. 62 | ``` python 63 | 64 | for var in "Geeksforgeeks": 65 | if var == "e": 66 | continue 67 | print(var) 68 | ``` 69 | 70 | ## Printing range with Python Continue Statement 71 | ``` python 72 | # loop from 1 to 10 73 | for i in range(1, 11): 74 | 75 | # If i is equals to 6, 76 | # continue to next iteration 77 | # without printing 78 | if i == 6: 79 | continue 80 | else: 81 | # otherwise print the value 82 | # of i 83 | print(i, end=" ") 84 | ``` 85 | 86 | ## Break in Python For Loop 87 | ### Python break is used to terminate the execution of the loop. 88 | ```python 89 | for i in range(10): 90 | print(i) 91 | if i == 2: 92 | break 93 | ``` 94 | ## Example 2: 95 | 96 | ```python 97 | # Python program to 98 | # demonstrate break statement 99 | 100 | s = 'geeksforgeeks' 101 | # Using for loop 102 | for letter in s: 103 | 104 | print(letter) 105 | # break the loop as soon it sees 'e' 106 | # or 's' 107 | if letter == 'e' or letter == 's': 108 | break 109 | 110 | print("Out of for loop" ) 111 | print() 112 | 113 | i = 0 114 | 115 | ``` 116 | 117 | ## For Loop in Python with Pass Statement 118 | ### When the user does not know what code to write, So user simply places a pass at that line. Sometimes, the pass is used when the user doesn’t want any code to execute. So users can simply place a pass where empty code is not allowed, like in loops, function definitions, class definitions, or in if statements. So using a pass statement user avoids this error 119 | 120 | ```python 121 | n = 26 122 | 123 | if n > 26: 124 | # write code your here 125 | 126 | print('Geeks') 127 | ``` 128 | ## Example 2 129 | ```python 130 | li =['a', 'b', 'c', 'd'] 131 | 132 | for i in li: 133 | if(i =='a'): 134 | pass 135 | else: 136 | print(i) 137 | ``` 138 | ## For Loops in Python with Else Statement 139 | ### The else block in a for loop is used to execute a block of code when the loop finishes 140 | ### The else block is executed only when the loop doesn’t encounter a break statement 141 | 142 | ```python 143 | # Python program to demonstrate 144 | # for-else loop 145 | 146 | for i in range(1, 4): 147 | print(i) 148 | else: # Executed because no break in for 149 | print("No Break\n") 150 | ``` 151 | 152 | 153 | -------------------------------------------------------------------------------- /Loops in Python/for_loops.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # # # # loop from 1 to 10 4 | # # # for i in range(1, 11): 5 | # # # if i == 6: 6 | # # # continue 7 | # # # print(i, end=" ") 8 | # # for i in range(1, 4): 9 | # # for j in range(1, 4): 10 | # # print(j) 11 | 12 | # # li =['a', 'b', 'c', 'd'] 13 | 14 | # # for i in li: 15 | # # if(i =='a'): 16 | # # pass 17 | # # else: 18 | # # print(i) 19 | 20 | # # for x in range(1,11,2): 21 | # # print(x) 22 | 23 | 24 | 25 | # # li =['a', 'b', 'c', 'd'] 26 | # # for x in li: 27 | # # print(x) # this will throw an error because list is not defined 28 | # # s = "Geeks Yasin" 29 | # # for i in s: 30 | # # print(i) 31 | # # l1 = "Uzair Yasin" 32 | # # for c,e in enumerate(l1): 33 | # # print (c,e) 34 | 35 | # # for i in range(1, 4): 36 | # # for j in range(5,8): 37 | # # print(j) 38 | 39 | # # for i in range(1, 11): 40 | # # if i == 6: 41 | # # pass 42 | # # print(i) 43 | 44 | # # string = "muhammad uzair" 45 | # # for x in string: 46 | # # print(x) 47 | 48 | # # for i in range(1, 6): 49 | # # print(i) 50 | # # for j in range(1, 6): 51 | # # print(i,j) 52 | 53 | # # l = ["geeks", "for", "geeks"] 54 | 55 | # # for i in l: 56 | # # print(i) 57 | 58 | # # for x in range(1,5): 59 | # # for x in range(1,5): 60 | # # print(f"*" , end = "") 61 | # # print() 62 | 63 | # # print(1) 64 | # # print(2) 65 | # # print(3) 66 | 67 | 68 | # # for x in [1,2,3]: 69 | # # print(x) 70 | # score = 0 71 | # con = True 72 | # while con: 73 | # print("Hello, World!") 74 | # score += 1 75 | # print(score) 76 | # user_input = input("do you want to stop yes or no :") 77 | # # if user_input == "yes": 78 | # # con = False 79 | 80 | # for x in range(1,4): 81 | # for y in range(1,4): 82 | # print(x,y) 83 | 84 | # name = "test" 85 | # for character in name: 86 | # print(character) 87 | 88 | 89 | # for x in range(1,10,2): 90 | # print(x) 91 | 92 | # print("uzair") 93 | 94 | # for x in range(1,5): 95 | # print("uzair") 96 | 97 | 98 | # for x in range(1,101 ,2): 99 | # print(x) 100 | 101 | # for i in range(0, 10, 2): 102 | # print(i) 103 | 104 | 105 | 106 | 107 | # name = "uzair yasin ali rafay ahmed aqib" 108 | 109 | # # for char in name: 110 | # # print(char) 111 | 112 | # for index,char in enumerate(name): 113 | # print(index , char) 114 | 115 | 116 | # for x in range(1,4): 117 | # for y in range(1,4): 118 | # print(x,y) 119 | 120 | 121 | # for x in range(1,10,2): 122 | # print(x) 123 | 124 | 125 | # for x i 126 | 127 | # i = 0 128 | # while (i < 3): 129 | # print(i) 130 | # i += 1 131 | # print("outside") 132 | 133 | 134 | # for x in range(1,10): 135 | # if x == 4: 136 | # break 137 | # else: 138 | # print(x) 139 | 140 | 141 | w -------------------------------------------------------------------------------- /Loops in Python/lopp.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 11, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "ename": "TypeError", 10 | "evalue": "'int' object is not callable", 11 | "output_type": "error", 12 | "traceback": [ 13 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 14 | "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", 15 | "Cell \u001b[1;32mIn[11], line 2\u001b[0m\n\u001b[0;32m 1\u001b[0m x \u001b[38;5;241m=\u001b[39m [\u001b[38;5;241m1\u001b[39m,\u001b[38;5;241m2\u001b[39m,\u001b[38;5;241m3\u001b[39m,\u001b[38;5;241m4\u001b[39m,\u001b[38;5;241m5\u001b[39m,\u001b[38;5;241m6\u001b[39m]\n\u001b[1;32m----> 2\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;28;43msum\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43mx\u001b[49m\u001b[43m)\u001b[49m)\n\u001b[0;32m 4\u001b[0m \u001b[38;5;66;03m# if x == 5:\u001b[39;00m\n\u001b[0;32m 5\u001b[0m \u001b[38;5;66;03m# continue\u001b[39;00m\n\u001b[0;32m 6\u001b[0m \u001b[38;5;66;03m# print(x)for x in [1,2,3,4,5,6]:\u001b[39;00m\n\u001b[0;32m 7\u001b[0m \u001b[38;5;66;03m# if x == 5:\u001b[39;00m\n\u001b[0;32m 8\u001b[0m \u001b[38;5;66;03m# continue\u001b[39;00m\n\u001b[0;32m 9\u001b[0m \u001b[38;5;66;03m# print(x)\u001b[39;00m\n", 16 | "\u001b[1;31mTypeError\u001b[0m: 'int' object is not callable" 17 | ] 18 | } 19 | ], 20 | "source": [ 21 | "\n", 22 | " \n", 23 | " # if x == 5:\n", 24 | " # continue\n", 25 | " # print(x)for x in [1,2,3,4,5,6]:\n", 26 | " # if x == 5:\n", 27 | " # continue\n", 28 | " # print(x)" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": null, 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [] 37 | } 38 | ], 39 | "metadata": { 40 | "kernelspec": { 41 | "display_name": "Python 3", 42 | "language": "python", 43 | "name": "python3" 44 | }, 45 | "language_info": { 46 | "codemirror_mode": { 47 | "name": "ipython", 48 | "version": 3 49 | }, 50 | "file_extension": ".py", 51 | "mimetype": "text/x-python", 52 | "name": "python", 53 | "nbconvert_exporter": "python", 54 | "pygments_lexer": "ipython3", 55 | "version": "3.12.5" 56 | } 57 | }, 58 | "nbformat": 4, 59 | "nbformat_minor": 2 60 | } 61 | -------------------------------------------------------------------------------- /Loops in Python/syantax of for loop.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/Loops in Python/syantax of for loop.png -------------------------------------------------------------------------------- /Loops in Python/while sytax.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/Loops in Python/while sytax.png -------------------------------------------------------------------------------- /Loops in Python/while.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 10, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "0\n", 13 | "1\n", 14 | "2\n", 15 | "3\n" 16 | ] 17 | }, 18 | { 19 | "ename": "KeyboardInterrupt", 20 | "evalue": "", 21 | "output_type": "error", 22 | "traceback": [ 23 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 24 | "\u001b[1;31mKeyboardInterrupt\u001b[0m Traceback (most recent call last)", 25 | "Cell \u001b[1;32mIn[10], line 6\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[38;5;28;01mwhile\u001b[39;00m count \u001b[38;5;241m<\u001b[39m \u001b[38;5;28mlen\u001b[39m(li):\n\u001b[0;32m 5\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m li[count] \u001b[38;5;241m==\u001b[39m \u001b[38;5;241m5\u001b[39m:\n\u001b[1;32m----> 6\u001b[0m \u001b[38;5;28;01mcontinue\u001b[39;00m\n\u001b[0;32m 7\u001b[0m \u001b[38;5;28mprint\u001b[39m(count)\n\u001b[0;32m 8\u001b[0m count \u001b[38;5;241m=\u001b[39m count\u001b[38;5;241m+\u001b[39m\u001b[38;5;241m1\u001b[39m \n", 26 | "\u001b[1;31mKeyboardInterrupt\u001b[0m: " 27 | ] 28 | } 29 | ], 30 | "source": [ 31 | "# Prints all letters except 'e' and 's'\n", 32 | "li = [1,2,3,4,5,6]\n", 33 | "count = 0\n", 34 | "while count < len(li):\n", 35 | " if li[count] == 4:\n", 36 | " continue\n", 37 | " print(count)\n", 38 | " count = count+1 " 39 | ] 40 | }, 41 | { 42 | "cell_type": "code", 43 | "execution_count": null, 44 | "metadata": {}, 45 | "outputs": [], 46 | "source": [] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "execution_count": null, 51 | "metadata": {}, 52 | "outputs": [], 53 | "source": [] 54 | } 55 | ], 56 | "metadata": { 57 | "kernelspec": { 58 | "display_name": "Python 3", 59 | "language": "python", 60 | "name": "python3" 61 | }, 62 | "language_info": { 63 | "codemirror_mode": { 64 | "name": "ipython", 65 | "version": 3 66 | }, 67 | "file_extension": ".py", 68 | "mimetype": "text/x-python", 69 | "name": "python", 70 | "nbconvert_exporter": "python", 71 | "pygments_lexer": "ipython3", 72 | "version": "3.12.5" 73 | } 74 | }, 75 | "nbformat": 4, 76 | "nbformat_minor": 2 77 | } 78 | -------------------------------------------------------------------------------- /Loops in Python/while.md: -------------------------------------------------------------------------------- 1 | # Python While Loop 2 | ### Python While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed. 3 | 4 | 5 | 6 | ```python 7 | # Python program to illustrate 8 | # while loop 9 | count = 0 10 | while (count < 3): 11 | count = count + 1 12 | print("Hello Geek") 13 | ``` 14 | 15 | ## Infinite while Loop in Python 16 | 17 | ```python 18 | age = 28 19 | 20 | # the test condition is always True 21 | while age > 19: 22 | print('Infinite Loop') 23 | ``` 24 | 25 | ## Control Statements in Python with Examples 26 | 27 | ```python 28 | # Prints all letters except 'e' and 's' 29 | i = 0 30 | a = 'geeksforgeeks' 31 | 32 | while i < len(a): 33 | if a[i] == 'e' or a[i] == 's': 34 | i += 1 35 | continue 36 | 37 | print('Current Letter :', a[i]) 38 | i += 1 39 | ``` 40 | 41 | ## Python while loop with a break statement 42 | ```python 43 | # break the loop as soon it sees 'e' 44 | # or 's' 45 | i = 0 46 | a = 'geeksforgeeks' 47 | 48 | while i < len(a): 49 | if a[i] == 'e' or a[i] == 's': 50 | i += 1 51 | break 52 | 53 | print('Current Letter :', a[i]) 54 | i += 1 55 | ``` 56 | 57 | ## Python while loop with a pass statement 58 | 59 | ```python 60 | # An empty loop 61 | a = 'geeksforgeeks' 62 | i = 0 63 | 64 | while i < len(a): 65 | i += 1 66 | pass 67 | 68 | print('Value of i :', i) 69 | ``` 70 | -------------------------------------------------------------------------------- /Loops in Python/while.py: -------------------------------------------------------------------------------- 1 | # Python program to illustrate 2 | # while loop 3 | # Prints all letters except 'e' and 's' 4 | 5 | # Prints all letters except 'e' and 's' 6 | # i = 0 7 | # a = 'geeksforgeeks' 8 | 9 | # while i < len(a): 10 | # if a[i] == 'k': 11 | # i += 1 12 | # break 13 | 14 | # print('Current Letter :', a[i]) 15 | # # i += 1 16 | 17 | # condition = True 18 | # while condition: 19 | # user_input = input("write your name : ") 20 | # if user_input == "exit": 21 | # condition = False 22 | # print("type exit to close : ") 23 | 24 | 25 | 26 | # count = 0 27 | # while (count < 5): 28 | # print("Hello Geek") 29 | # count = count + 1 30 | # if count == 3: 31 | # print("continue") 32 | 33 | 34 | 35 | # for x in range(1,10): 36 | # if x == 6: 37 | # break 38 | # else: 39 | # print(x) 40 | 41 | 42 | # for x in range(1 , 6): 43 | # print('*****') 44 | 45 | # user_input = int(input("Enter the number which table u want : ")) 46 | # for i in range(1,11): 47 | # print(f" {user_input} x {i} = {(user_input) * (i)}") 48 | 49 | 50 | # for x in range(1,101): 51 | 52 | # if x % 3 == 0 and x % 5 == 0: 53 | # print("FizzBuzz") 54 | # elif x % 3 == 0: 55 | # print("Fizz") 56 | # elif x % 5 == 0: 57 | # print("Buzz") 58 | # else: 59 | # print(x) -------------------------------------------------------------------------------- /Loops in Python/while2.py: -------------------------------------------------------------------------------- 1 | # While Loop in Python 2 | # In Python, a while loop is used to execute a block of statements repeatedly until a given condition is satisfied. 3 | # 4 | # count = 0 5 | # while (count < 3): 6 | # count = count + 1 7 | # print("Hello World") 8 | 9 | # Using else statement with While Loop in Python 10 | # The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won’t be executed. 11 | 12 | # count = 0 13 | # while (count < 3): 14 | # count = count + 1 15 | # print("Hello World") 16 | # else: 17 | # print("In Else Block") 18 | 19 | 20 | # Infinite While Loop in Python 21 | # If we want a block of code to execute infinite number of time, we can use the while loop in Python to do so. 22 | # count = 0 23 | # while (count == 0): 24 | # print("Hello World") -------------------------------------------------------------------------------- /Numbers , Int , Float , Complex/Numbers.md: -------------------------------------------------------------------------------- 1 | # Python Integer 2 | ## Python int is the whole number, including negative numbers but not fractions. In Python, there is no limit to how long an integer value can be. 3 | 4 | ## Example 1: Creating int and checking type 5 | 6 | 7 | ```python 8 | num = -8 9 | 10 | # print the data type 11 | print(type(num)) 12 | ``` 13 | 14 | # Python Float 15 | ## Some examples of numbers that are represented as floats are 0.5 and -7.823457. 16 | ### Example 1: Creating float and checking type 17 | 18 | 19 | ```python 20 | num = 3/4 21 | 22 | # print the data type 23 | print(type(num)) 24 | ``` 25 | # Python Complex 26 | ## A complex number is a number that consists of real and imaginary parts. For example, 2 + 3j is a complex number where 2 is the real component, and 3 multiplied by j is an imaginary part. 27 | ### Example 1: Creating Complex and checking type 28 | 29 | 30 | ```python 31 | num = 6 + 9j 32 | 33 | print(type(num)) 34 | ``` 35 | -------------------------------------------------------------------------------- /Numbers , Int , Float , Complex/Numbers.py: -------------------------------------------------------------------------------- 1 | # num = 684684684684684646468644 2 | # print(type(num)) 3 | num = 6 + 9j 4 | 5 | print(type(num)) -------------------------------------------------------------------------------- /Numbers , Int , Float , Complex/main.py: -------------------------------------------------------------------------------- 1 | # Output 2 | # print("Hello World") 3 | 4 | # Data types 5 | 6 | # Primitive and Non primitive 7 | 8 | 9 | # primitive : u can store single value 10 | 11 | # str : string : anything which comes inside inverted commas is called string 12 | # int : integer : 123546846465468 13 | # float : decimal number : 123.456 14 | # bool : boolean : true/false 15 | 16 | # type() 17 | 18 | # print( type("5765") ) 19 | 20 | # "" 21 | # '' 22 | # ''''' 23 | 24 | 25 | # print(''' 'Quaid' Said : Work "Work" and Work ''') 26 | # print ('''uzair 27 | # yasin ''') 28 | 29 | # Escape Sequence 30 | # \n : new line 31 | # \t : tab space 32 | # \\ : back slash 33 | # print(" 'Quaid' Said : Work \"Work\" and Work ") 34 | # print("uzair \nyasin") 35 | 36 | 37 | # Variables 38 | 39 | # name = 5.5 40 | # print(name) 41 | # Rules of Variable 42 | 43 | # no space 44 | # dont start with integer 45 | # dont use special character 46 | # dont use keyword 47 | 48 | 49 | # meaningful name 50 | # a = 0 51 | # print = "uzair" 52 | # print(print) 53 | 54 | # stages 55 | 56 | # 1. declaration 57 | # 2. initialization 58 | 59 | # name = "uzair" 60 | 61 | 62 | # String 63 | # indexing 64 | # slicing 65 | # steping 66 | # [start : end : step] 67 | # for reversing string we can give step in minus 68 | # name = "My name is Muhammad Uzair and I am a Piaic Student" 69 | # print(name[::]) 70 | 71 | # immutable : anything which is unchangeable 72 | # mutable : anything which is changeable 73 | 74 | 75 | # String function 76 | # 1. lower() 77 | # 2. upper() 78 | # 3. title() 79 | # 4. capitalize() 80 | 81 | 82 | # name = "uzaira" 83 | # Second_str = "" .join("uzair") 84 | # # print(name) 85 | # print(Second_str) 86 | 87 | # print("uzair","yasin" , sep="-") 88 | # print("Yasin ") 89 | 90 | # print("Hello", "World") 91 | # num = False 92 | # print(type(num)) 93 | 94 | 95 | 96 | # number = 5 + 2j 97 | # print(type(number)) 98 | 99 | 100 | number = True 101 | string = str(number) 102 | print(type(string)) -------------------------------------------------------------------------------- /OOP/ABstraction/abstraction.md: -------------------------------------------------------------------------------- 1 | 2 | # Data Abstraction in Python 3 | 4 | **Last Updated**: 04 Jul, 2024 5 | 6 | Data abstraction is one of the most essential concepts of Python OOPs which is used to hide irrelevant details from the user and show the details that are relevant to the users. For example, the readers of geeksforgeeks only know that a writer can write an article on geeksforgeeks, and when it gets published readers can read the articles but the reader is not aware of the background process of publishing the article. 7 | 8 | A simple example of this can be a car. A car has an accelerator, clutch, and brake and we all know that pressing an accelerator will increase the speed of the car and applying the brake can stop the car but we don’t know the internal mechanism of the car and how these functionalities can work. This detail hiding is known as data abstraction. 9 | 10 | To understand data abstraction we should be aware of the below basic concepts: 11 | 12 | - OOP concepts in Python 13 | - Classes in Python 14 | - Abstract classes in Python 15 | 16 | ## Importance of Data Abstraction 17 | 18 | It enables programmers to hide complex implementation details while just showing users the most crucial data and functions. This abstraction makes it easier to design modular and well-organized code, makes it simpler to understand and maintain, promotes code reuse, and improves developer collaboration. 19 | 20 | ## Data Abstraction in Python 21 | 22 | Data abstraction in Python is a programming concept that hides complex implementation details while exposing only essential information and functionalities to users. In Python, we can achieve data abstraction by using abstract classes, and abstract classes can be created using the `abc` (abstract base class) module and `abstractmethod` of `abc` module. 23 | 24 | ### Abstraction Classes in Python 25 | 26 | An abstract class is a class in which one or more abstract methods are defined. When a method is declared inside the class without its implementation, it is known as an abstract method. 27 | 28 | - **Abstract Method**: In Python, the abstract method feature is not a default feature. To create an abstract method and abstract classes, we have to import the `ABC` and `abstractmethod` classes from the `abc` (Abstract Base Class) library. The abstract method of the base class forces its child class to implement all abstract methods defined in the base class. If we do not implement the abstract methods of the base class in the child class, our code will give an error. In the code below, `method_1` is an abstract method created using the `@abstractmethod` decorator. 29 | 30 | ```python 31 | from abc import ABC, abstractmethod 32 | class BaseClass(ABC): 33 | @abstractmethod 34 | def method_1(self): 35 | # empty body 36 | pass 37 | ``` 38 | 39 | - **Concrete Method**: Concrete methods are the methods defined in an abstract base class with their complete implementation. Concrete methods are required to avoid replication of code in subclasses. For example, in an abstract base class, there may be a method whose implementation is the same in all its subclasses, so we write the implementation of that method in the abstract base class. Afterward, we do not need to write the implementation of the concrete method again in every subclass. In the code below, `startEngine` is a concrete method. 40 | 41 | ```python 42 | class Car(ABC): 43 | def __init__(self, brand, model, year): 44 | self.brand = brand 45 | self.model = model 46 | self.year = year 47 | self.engine_started = True 48 | 49 | def startEngine(self): 50 | if not self.engine_started: 51 | print(f"Starting the {self.model}'s engine.") 52 | self.engine_started = True 53 | else: 54 | print("Engine is already running.") 55 | ``` 56 | 57 | ### Steps to Create Abstract Base Class and Abstract Method: 58 | 59 | 1. Import `ABC` and `abstractmethod` class from the `abc` (Abstract Base Class) library. 60 | 2. Create a `BaseClass` that inherits from the `ABC` class. In Python, when a class inherits from `ABC`, it indicates that the class is intended to be an abstract base class. 61 | 3. Inside `BaseClass`, declare an abstract method named `method_1` by using the `abstractmethod` decorator. Any subclass derived from `BaseClass` must implement this `method_1` method. We write `pass` in this method, which indicates that there is no code or logic in this method. 62 | 63 | ```python 64 | from abc import ABC, abstractmethod 65 | class BaseClass(ABC): 66 | @abstractmethod 67 | def method_1(self): 68 | # empty body 69 | pass 70 | ``` 71 | 72 | ### Implementation of Data Abstraction in Python 73 | 74 | In the code below, we have implemented data abstraction using an abstract class and method. Firstly, we import the required modules or classes from the `abc` library, then we create a base class `Car` that inherits from the `ABC` class that we have imported. Inside the base class, we create an `__init__` function, abstract function, and non-abstract functions. To declare the abstract function `printDetails`, we use the `@abstractmethod` decorator. After that, we create child classes `Hatchback` and `Suv`. Since these child classes inherit from the abstract class, we need to implement all abstract functions declared in the base class. We write the implementation of the abstract method in both child classes. We create an instance of a child class and call the `printDetails` method. In this way, we can achieve data abstraction. 75 | 76 | ```python 77 | # Import required modules 78 | from abc import ABC, abstractmethod 79 | 80 | # Create Abstract base class 81 | class Car(ABC): 82 | def __init__(self, brand, model, year): 83 | self.brand = brand 84 | self.model = model 85 | self.year = year 86 | 87 | # Create abstract method 88 | @abstractmethod 89 | def printDetails(self): 90 | pass 91 | 92 | # Create concrete method 93 | def accelerate(self): 94 | print("Speed up ...") 95 | 96 | def break_applied(self): 97 | print("Car stopped") 98 | 99 | # Create a child class 100 | class Hatchback(Car): 101 | def printDetails(self): 102 | print("Brand:", self.brand) 103 | print("Model:", self.model) 104 | print("Year:", self.year) 105 | 106 | def sunroof(self): 107 | print("Not having this feature") 108 | 109 | # Create a child class 110 | class Suv(Car): 111 | def printDetails(self): 112 | print("Brand:", self.brand) 113 | print("Model:", self.model) 114 | print("Year:", self.year) 115 | 116 | def sunroof(self): 117 | print("Available") 118 | 119 | # Create an instance of the Hatchback class 120 | car1 = Hatchback("Maruti", "Alto", "2022") 121 | 122 | # Call methods 123 | car1.printDetails() 124 | car1.accelerate() 125 | car1.sunroof() 126 | ``` 127 | 128 | **Output**: 129 | ``` 130 | Brand: Maruti 131 | Model: Alto 132 | Year: 2022 133 | Speed up ... 134 | ``` 135 | ```python 136 | from abc import ABC, abstractmethod 137 | 138 | # Abstract class representing an ATM 139 | class ATM(ABC): 140 | @abstractmethod 141 | def insert_card(self): 142 | pass 143 | 144 | @abstractmethod 145 | def enter_pin(self): 146 | pass 147 | 148 | @abstractmethod 149 | def perform_transaction(self): 150 | pass 151 | 152 | # Concrete class implementing ATM functionalities 153 | class BankATM(ATM): 154 | def insert_card(self): 155 | print("Card inserted.") 156 | 157 | def enter_pin(self): 158 | print("PIN entered.") 159 | 160 | def perform_transaction(self): 161 | print("Transaction successful! Here is your cash.") 162 | 163 | # Usage 164 | atm = BankATM() 165 | atm.insert_card() 166 | atm.enter_pin() 167 | atm.perform_transaction() 168 | ``` 169 | -------------------------------------------------------------------------------- /OOP/ABstraction/abstraction.py: -------------------------------------------------------------------------------- 1 | # from abc import ABC,abstractmethod 2 | 3 | # class Person(ABC): 4 | 5 | # @abstractmethod # This decorator marks the eating method as abstract method in Person abstract class. 6 | # def eating(self): 7 | # pass 8 | # class Child(Person): 9 | # def eating(self): 10 | # print("he is eating") 11 | # def running(self): 12 | # print("this is child class") 13 | 14 | 15 | 16 | # c1 = Child() 17 | # c1.running() 18 | 19 | # c1.eating() # This will give an error because eating method in Child class is not implemented. 20 | 21 | # Import required modules 22 | from abc import ABC, abstractmethod 23 | 24 | # Create Abstract base class 25 | class Car(ABC): 26 | def __init__(self, brand, model, year): 27 | self.brand = brand 28 | self.model = model 29 | self.year = year 30 | 31 | # Create abstract method 32 | @abstractmethod 33 | def printDetails(self): 34 | pass 35 | 36 | # Create concrete method 37 | def accelerate(self): 38 | print("Speed up ...") 39 | 40 | def break_applied(self): 41 | print("Car stopped") 42 | 43 | # Create a child class 44 | class Hatchback(Car): 45 | def printDetails(self): 46 | print("Brand:", self.brand) 47 | print("Model:", self.model) 48 | print("Year:", self.year) 49 | 50 | def sunroof(self): 51 | print("Not having this feature") 52 | 53 | # Create a child class 54 | class Suv(Car): 55 | def printDetails(self): 56 | print("Brand:", self.brand) 57 | print("Model:", self.model) 58 | print("Year:", self.year) 59 | 60 | def sunroof(self): 61 | print("Available") 62 | 63 | # Create an instance of the Hatchback class 64 | car1 = Hatchback("Maruti", "Alto", "2022") 65 | 66 | # # Call methods 67 | # car1.printDetails() 68 | car1.accelerate() 69 | car1.sunroof() 70 | car1.printDetails() 71 | 72 | # s1 = Suv("honda",2022,2000) 73 | 74 | # s1.sunroof() -------------------------------------------------------------------------------- /OOP/Class_Obj_Construtor_Self_Destrcutor_Typenames/OOP.py: -------------------------------------------------------------------------------- 1 | # # # class Car: 2 | # # # def __init__(a ,color,model) : 3 | # # # a.color = color 4 | # # # a.model = model 5 | 6 | # # # def drive(self): 7 | # # # print("The car is driving") 8 | # # # def loading(self): 9 | # # # # print("The car is loading") 10 | # # class Dog: 11 | # # def __init__(self, breed, age,color): 12 | # # self.breed = breed 13 | # # self.age = age 14 | # # self.color = color 15 | # # def bark(self): 16 | # # print("The dog is barking") 17 | # # def sleep(self): 18 | # # print("The dog is sleeping") 19 | # # def eat(self,food): 20 | # # print("eating" ,food) 21 | 22 | 23 | # # dog1 = Dog("Russian" ,5,"black") 24 | # # dog2 = Dog("Jerman" ,2,"pinky") 25 | # # dog3 = Dog("bulldog" ,7,"white") 26 | 27 | # # print(dog1.age) 28 | # # print(dog1.color) 29 | # # dog1.eat("fish") 30 | # # dog1.sleep() 31 | 32 | # # print() 33 | # # print(dog2.age) 34 | # # print(dog2.color) 35 | # # print(dog2.breed) 36 | # # dog2.eat("mutton") 37 | 38 | # # # li =[1,2,3] 39 | # # # li.append() 40 | # # # car1 = Car("red" , 2024) 41 | # # # print(car1.color) 42 | # # # print(car1.model) 43 | # # # print() 44 | # # # car2 = Car("white" , 2022) 45 | # # # print(car2.color) 46 | # # # print(car2.model) 47 | # # # print() 48 | # # # car3 = Car("black" , 2023) 49 | # # # print(car3.color) 50 | # # # print(car3.model) 51 | 52 | 53 | 54 | # # # car1 = Car() 55 | 56 | 57 | 58 | # # # car1.drive() 59 | # # # print(car1.color) 60 | # # # print(car1.model) 61 | # # # print(car1.C_Name) 62 | # # # car1.loading() 63 | 64 | # # # car2 = Car() 65 | # # # print(car2.color) 66 | # # # print(car2.model) 67 | # # print("""Welcome to Treasure Island. 68 | # # Your mission is to find the treasure 69 | # # You're at a cross road. Where do yopu want to go? """ ) 70 | # # first_step=str(input('Type \"left\" or \"right\" \n')) 71 | # # if first_step.lower()=="left": 72 | # # print("You've come top lake.There is island in the middle of the lake.") 73 | # # second_step=str(input("Type \"wait\" to wait for a boat. Type \"swim\" to swim across. \n")) 74 | # # if second_step.lower()=="wait": 75 | # # print("You arrive at the island unharmed. There is a house with 3 doors.") 76 | # # third_step=str(input("One \"red\", One \"yellow\" and one \"blue\". Which color do you choose? \n")) 77 | # # if third_step.lower()=="red": 78 | # # print("Its a room full of fire. Game Over.") 79 | # # if third_step.lower()=="yellow": 80 | # # print("You find the treasure! You Win!") 81 | # # if third_step.lower()=="blue": 82 | # # print("Game Over") 83 | # # if second_step.lower()=="swim": 84 | # # # print("You get attacked by an angry trout. Game Over") 85 | # # # if first_step.lower()=="right": 86 | # # # print("You fell into a hole. Game Over.") 87 | 88 | 89 | 90 | # # class Car: 91 | # # # class variable or static variable 92 | # # tier = 4 93 | # # def __init__(self,color,model,company_n): 94 | # # # class instance or dynamic variable 95 | # # self.color = color 96 | # # self.model = model 97 | # # self.company_n = company_n 98 | # # def driving(self): 99 | # # print("The car is driving") 100 | # # def loading(self,material): 101 | # # print(f"The car is loading {material}") 102 | 103 | 104 | 105 | 106 | 107 | # # Car1 = Car("red" , 2023,"honda") 108 | # # Car1.color = "yellow" 109 | # # Car1.model = 2022 110 | # # print(Car1.color) 111 | # # print(Car1.model) 112 | # # Car1.driving() 113 | # # Car1.loading("food") 114 | # # print() 115 | # # Car2 = Car("white" , 2022,"Tesla") 116 | # # print(Car2.color) 117 | # # Car2.driving() 118 | # # Car2.loading("mirrors") 119 | 120 | # # # print(Car1.tier) 121 | # # # print(Car2.tier) 122 | 123 | 124 | # # li = [1,2,3,4] 125 | # # li.append("1") 126 | 127 | # # class Car: 128 | # # color = "red" 129 | # # model = 2024 130 | # # company_n = "Honda" 131 | 132 | 133 | # # car1 = Car() 134 | # # print(car1.color) 135 | # # print(car1.model) 136 | # # print(car1.company_n) 137 | # # # car2 = Car() 138 | # # # print(car2.color) 139 | # # # print(car2.model) 140 | # # # print(car2.company_n) 141 | 142 | 143 | # # class Dog: 144 | # # breed = "German" 145 | # # color = "black" 146 | # # age = 3 147 | 148 | # # def bar(self): 149 | # # print("The dog barks") 150 | # # def run(self): 151 | # # print("The dog runs") 152 | # # def sleep(self): 153 | # # print("The dog sleeps") 154 | 155 | 156 | 157 | 158 | # # D1 = Dog() 159 | 160 | # # print(D1.breed) 161 | # # print(D1.color) 162 | # # print(D1.age) 163 | 164 | # # D1.bar() 165 | # # D1.run() 166 | # # D1.sleep() 167 | 168 | 169 | 170 | class Human: 171 | name = "John" 172 | age = 25 173 | gender = "male" 174 | def eat(self): 175 | print("The human eats") 176 | def sleep(self): 177 | print("The human sleeps") 178 | def talk(self): 179 | print("The human talks") 180 | 181 | 182 | 183 | h1 = Human() 184 | 185 | print(h1.name) 186 | print(h1.age) 187 | print(h1.gender) 188 | 189 | # h1.eat() 190 | 191 | # h1.sleep() 192 | 193 | # h1.talk() 194 | 195 | 196 | # li = list([1,2,3,4]) 197 | # print(li) 198 | 199 | # li.clear() 200 | # li.count() 201 | # li. 202 | class Dog: 203 | def __init__(self , breed , color ,age): 204 | self.breed = breed 205 | self.color = color 206 | self.age = age 207 | 208 | def bark(self): 209 | print("Woof") 210 | def run(self): 211 | print("The dog is running") 212 | def eat(self , meal): 213 | print("The dog is eating" , meal) 214 | 215 | d1 = Dog("German" , "black" ,10) 216 | d2 = Dog("Russain" , "gray" ,12) 217 | d3 = Dog("husky" , "white" ,8) 218 | 219 | 220 | print(d1.age) 221 | 222 | print(d1.breed) 223 | print(d1.color) 224 | 225 | d1.bark() 226 | d1.run() 227 | d1.eat("meat") 228 | 229 | 230 | print() 231 | 232 | print(d2.age) 233 | print(d2.breed) 234 | print(d2.color) 235 | 236 | d2.bark() 237 | d2.run() 238 | d2.eat("Fish") -------------------------------------------------------------------------------- /OOP/Class_Obj_Construtor_Self_Destrcutor_Typenames/{38B0A826-F032-4495-998A-58F485BF09FE}.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/OOP/Class_Obj_Construtor_Self_Destrcutor_Typenames/{38B0A826-F032-4495-998A-58F485BF09FE}.png -------------------------------------------------------------------------------- /OOP/Class_Obj_Construtor_Self_Destrcutor_Typenames/{5ACC869D-7E21-4268-9FC6-F4D21A2F62BE}.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/OOP/Class_Obj_Construtor_Self_Destrcutor_Typenames/{5ACC869D-7E21-4268-9FC6-F4D21A2F62BE}.png -------------------------------------------------------------------------------- /OOP/Class_Obj_Construtor_Self_Destrcutor_Typenames/{5DC5A6C1-7F09-4A80-A69E-2A7A073F1832}.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/OOP/Class_Obj_Construtor_Self_Destrcutor_Typenames/{5DC5A6C1-7F09-4A80-A69E-2A7A073F1832}.png -------------------------------------------------------------------------------- /OOP/Encapsulation/py.py: -------------------------------------------------------------------------------- 1 | # # # class Person: 2 | # # # def __init__(self, name, age): 3 | # # # self.__name = name 4 | # # # self.__age = age 5 | 6 | 7 | 8 | # # # p1 = Person("uzair" , 20) 9 | # # # print(p1._Person__name 10 | # # def decorator(func): 11 | # # def wrapper(*args, **kwargs): 12 | # # result = func(*args, **kwargs) 13 | # # return result + 1 # Incrementing the result by 1 14 | # # return wrapper 15 | 16 | # # @decorator 17 | # # def add(x, y): 18 | # # return x + y 19 | 20 | # # # Test the function 21 | # # print(add(2, 4)) # Output will be 7, since 2+4 = 6, and decorator adds 1 22 | 23 | 24 | # class Mother: 25 | # def __init__(self, name, age): 26 | # self.name = name 27 | # self.age = age 28 | # def running(self): 29 | # print("Mother is running") 30 | # class Father: 31 | # def __init__(self, name, age): 32 | # self.name = name 33 | # self.age = age 34 | # def running(self): 35 | # print("running") 36 | # class Child(Mother, Father): 37 | # def __init__(self, name, age, mother_name, father_name): 38 | # super().__init__(name, age) 39 | # super().__init__(mother_name, father_name) 40 | # Father.running(self) 41 | 42 | 43 | 44 | # c = Child("uzair", 20, "sadia", "shahid") 45 | # c.running() 46 | 47 | 48 | class Person: 49 | def __init__(self, name): 50 | self.__name = name 51 | def __running(self): 52 | print("running") 53 | 54 | # def setter(self): 55 | # self.__name = "uzair" 56 | # def Admin(self): 57 | # return self.__name 58 | 59 | 60 | 61 | # p1 = Person("uzair") 62 | # print(p1._Person__name) 63 | # p1._Person__running() 64 | 65 | 66 | # # print(p1.Admin()) 67 | # p1.__name = "ali" 68 | # print(p1.__name) 69 | # # # print(p1.Admin()) #uzair 70 | # # # print(p1.age) #20 71 | 72 | 73 | 74 | # i = True 75 | # num = 0 76 | # while(i): 77 | # print("uzair") 78 | # num += 1 79 | # if num == 4: 80 | # break 81 | 82 | class Person: 83 | def __init__(self, name, age): 84 | self.__name = name 85 | self.__age = age 86 | def __eat(self): 87 | print("eating") 88 | # def admin(self): 89 | # return self._name, self._age 90 | def admin(self): 91 | return self.__name, self.__age 92 | 93 | 94 | 95 | 96 | 97 | person = Person("uzair" , 20) 98 | # print(person.admin()) 99 | print(person.__name) 100 | # print(person.__age) 101 | 102 | # person.__eat() 103 | 104 | # print(person.name) 105 | # print(person.age) 106 | # print(person.admin()) 107 | -------------------------------------------------------------------------------- /OOP/Inheritance/Inheritance.py: -------------------------------------------------------------------------------- 1 | # class GrandFather: 2 | 3 | # def Display_Gf(self): 4 | # print("this is father class") 5 | # def Wisdom(self): 6 | # print("this is guide method of Grand_father class") 7 | 8 | 9 | # class Father(GrandFather): 10 | 11 | # def display_f(self): 12 | # print("this is father class") 13 | # def protect(self): 14 | # print("this is protect method of father class") 15 | 16 | # class Son(Father): 17 | 18 | # def Print(self): 19 | # print("this is child class") 20 | # def Play(self): 21 | # print("this is play method of child class") 22 | 23 | 24 | # class Son2(Father,GrandFather): 25 | # def Print(self): 26 | # print("this is child2 class") 27 | # def Play(self): 28 | # print("this is play method of child2 class") 29 | 30 | 31 | 32 | 33 | 34 | # f1 = Father() 35 | # print("father functions") 36 | # f1.display_f() 37 | # f1.protect() 38 | 39 | # print() 40 | # print("grandfather functions") 41 | # f1.Display_Gf() 42 | # f1.Wisdom() 43 | 44 | 45 | # son1 = Son() 46 | # son1.Play() 47 | 48 | # print() 49 | # print("father class functions") 50 | # son1.display_f() 51 | 52 | # print() 53 | # print("grandfather class functions") 54 | # son1.Display_Gf() 55 | 56 | 57 | 58 | # # # # e1= Son() 59 | # # # # e1.Print() 60 | 61 | # # # # print() 62 | # # # # print("father functions") 63 | # # # # e1.Display_f() 64 | # # # # e1.Guide() 65 | 66 | # # # # print() 67 | # # # # print("mother functions") 68 | 69 | # # # # e1.display_m() 70 | # # # # e1.protect() 71 | 72 | 73 | # # # class Animal: 74 | # # # def __init__(self, name): 75 | # # # self.name = name 76 | 77 | # # # class Dog(Animal): 78 | # # # def __init__(self, name, breed): 79 | # # # super().__init__(name) 80 | # # # # Call the parent class's __init__ 81 | # # # self.breed = breed 82 | 83 | 84 | # # # dog1 =Dog("name" ,"any") 85 | # # # print(dog1.name) # Output: None 86 | # # # print(dog1.breed) # Output: None 87 | 88 | # # class A: 89 | # # def process(self): 90 | # # print("Processing in A") 91 | 92 | # # class B(A): 93 | # # def process(self): 94 | # # print("Processing in B") 95 | # # super().process() # Call A's process method 96 | 97 | # # class C(A): 98 | # # def process(self): 99 | # # print("Processing in C") 100 | # # super().process() # Call A's process method 101 | 102 | # # class D(B, C): 103 | # # def process(self): 104 | # # print("Processing in D") 105 | # # # super().process() # This ensures B, C, and A are all called 106 | 107 | # # # obj1=D() 108 | # # # obj1.process() # Output: Processing in D, Processing in B, Processing in C, 109 | 110 | 111 | 112 | 113 | 114 | 115 | # # class Animal: 116 | # # def __init__(self, name): 117 | # # self.name = name 118 | 119 | # # def make_sound(self): 120 | # # print(f"{self.name} makes a generic animal sound.") 121 | 122 | 123 | # # class Dog(Animal): 124 | # # def __init__(self, name, breed): 125 | # # super().__init__(name) # Calls the parent class constructor 126 | # # self.breed = breed 127 | 128 | # # def make_sound(self): 129 | # # print(f"{self.name} barks.") 130 | # # super().make_sound() # Calls the parent class method 131 | 132 | 133 | # # dog = Dog("Buddy", "Golden Retriever") 134 | # # dog.make_sound() 135 | 136 | 137 | # class Father2: 138 | # def __init__(self, f_name, f_age): 139 | # self.f_name = f_name 140 | # self.f_age = f_age 141 | 142 | # def running(self): 143 | # print(f"This is running") 144 | 145 | # class Child(Father2): 146 | # def __init__(self, f_name, f_age, my_name,my_grade): 147 | # super().__init__(f_name, f_age) 148 | # self.my_grade = my_grade 149 | # self.my_name = my_name 150 | # def running(self): 151 | # super().running() 152 | 153 | 154 | 155 | # c1 = Child("yasin",55,"uzair","A") 156 | # print(c1.f_name) 157 | # print(c1.f_age) 158 | # print(c1.my_name) 159 | # print(c1.my_grade) 160 | # c1.running() 161 | 162 | # class Father: 163 | # def guide(self): 164 | # print("this is guide method of Father class") 165 | # def work(self): 166 | # print("this is work method of Father class") 167 | 168 | # class Mother: 169 | # def protect(self): 170 | # print("this is protect method of Mother class") 171 | # def cook(self): 172 | # print("this is cook method of Mother class") 173 | 174 | 175 | 176 | 177 | 178 | # class Children(Mother,Father): 179 | # def play(self): 180 | # print("this is play method of Children class") 181 | # def eat(self): 182 | # print("this is eat method of Children class") 183 | # def sleep(self): 184 | # print("this is sleep method of Children class") 185 | 186 | 187 | 188 | # c1 = Children() 189 | # print("\t\t\tthese are children class methods") 190 | # c1.eat() 191 | # c1.sleep() 192 | # c1.play() 193 | 194 | # print("\t\t\tthese are mother class methods") 195 | 196 | # c1.protect() 197 | # c1.cook() 198 | 199 | # print("\t\t\tthese are father class methods") 200 | # c1.work() 201 | # c1.guide() 202 | 203 | class Father: 204 | def guide(self): 205 | print("this is guide method of Father class") 206 | def work(self): 207 | print("this is work method of Father class") 208 | 209 | class Mother(Father): 210 | def protect(self): 211 | print("this is protect method of Mother class") 212 | def cook(self): 213 | print("this is cook method of Mother class") 214 | 215 | class Children1(Mother): 216 | def play(self): 217 | print("this is play method of Children class") 218 | def eat(self): 219 | print("this is eat method of Children class") 220 | def sleep(self): 221 | print("this is sleep method of Children class") 222 | 223 | class Children2(Mother,Father): 224 | def play2(self): 225 | print("this is play method of Children class") 226 | def eat2(self): 227 | print("this is eat method of Children class") 228 | def sleep2(self): 229 | print("this is sleep method of Children class") 230 | 231 | 232 | c1 = Children1() 233 | 234 | c2 = Children2() 235 | 236 | # c1 = Children() 237 | # print("\t\t\tthese are children class methods") 238 | # c1.eat() 239 | # c1.sleep() 240 | # c1.play() 241 | 242 | # print("\t\t\tthese are mother class methods") 243 | 244 | # c1.protect() 245 | # c1.cook() 246 | 247 | # print("\t\t\tthese are father class methods") 248 | # c1.work() 249 | # c1.guide() 250 | 251 | # m1 = Mother() 252 | 253 | # print("\t\t\tthese are mother class methods") 254 | 255 | # m1.protect() 256 | 257 | # m1.cook() 258 | 259 | # m1.guide() 260 | 261 | -------------------------------------------------------------------------------- /OOP/Inheritance/image-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/OOP/Inheritance/image-1.png -------------------------------------------------------------------------------- /OOP/Inheritance/image-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/OOP/Inheritance/image-2.png -------------------------------------------------------------------------------- /OOP/Inheritance/image-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/OOP/Inheritance/image-3.png -------------------------------------------------------------------------------- /OOP/Inheritance/image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/OOP/Inheritance/image.png -------------------------------------------------------------------------------- /OOP/Inheritance/inheritance.md: -------------------------------------------------------------------------------- 1 | # Inheritance in Python 2 | 3 | Inheritance is the capability of one class to derive or inherit the properties from another class 4 | Inheritance allows us to create a new class from an existing class. 5 | 6 | ## Key Concepts 7 | 8 | - **Subclass**: The new class that is created (child or derived class). 9 | - **Superclass**: The existing class from which the child class is derived (parent or base class). 10 | ![alt text]({81C98B3B-0954-4A39-A99F-AB05BA07E41E}.png) 11 | 12 | ## Benefits of Inheritance 13 | 14 | The benefits of inheritance in Python are as follows: 15 | 16 | - Inheritance allows you to inherit the properties of a class, i.e., base class to another, i.e., derived class. 17 | - It represents real-world relationships well. 18 | - It provides the reusability of code; we don’t have to write the same code again and again. 19 | - It allows us to add more features to a class without modifying it. 20 | - It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A. 21 | - Inheritance offers a simple, understandable model structure. 22 | - Less development and maintenance expenses result from inheritance. 23 | 24 | ```python 25 | # A Python program to demonstrate inheritance 26 | class Person(object): 27 | 28 | # Constructor 29 | def __init__(self, name, id): 30 | self.name = name 31 | self.id = id 32 | 33 | # To check if this person is an employee 34 | def Display(self): 35 | print(self.name, self.id) 36 | 37 | 38 | 39 | 40 | class Emp(Person): 41 | 42 | def Print(self): 43 | print("Emp class called") 44 | 45 | # Driver code 46 | emp = Person("Satyam", 102) # An Object of Person 47 | emp.Display() 48 | 49 | Emp_details = Emp("Mayank", 103) 50 | 51 | # calling parent class function 52 | Emp_details.Display() 53 | 54 | # Calling child class function 55 | Emp_details.Print() 56 | ``` 57 | 58 | # Types of Inheritance 59 | 60 | Types of inheritance depend upon the number of child and parent classes involved. There are five types of inheritance in Python: 61 | 62 | 1. **Single Inheritance** 63 | 2. **Multiple Inheritance** 64 | 3. **Multilevel Inheritance** 65 | 4. **Hierarchical Inheritance** 66 | 5. **Hybrid Inheritance** 67 | 68 | 69 | ## Single Inheritance 70 | 71 | Single inheritance enables a derived class to inherit properties from a single parent class, thus enabling code reusability and the addition of new features to existing code. 72 | 73 | 74 | ![alt text](image.png) 75 | 76 | ```python 77 | # Python program to demonstrate 78 | # single inheritance 79 | 80 | # Base class 81 | class Parent: 82 | def func1(self): 83 | print("This function is in parent class.") 84 | 85 | # Derived class 86 | 87 | 88 | class Child(Parent): 89 | def func2(self): 90 | print("This function is in child class.") 91 | 92 | 93 | # Driver's code 94 | object = Child() 95 | object.func1() 96 | object.func2() 97 | ``` 98 | ## Multiple Inheritance 99 | 100 | When a class can be derived from more than one base class, this type of inheritance is called multiple inheritance. In multiple inheritance, all the features of the base classes are inherited into the derived class. 101 | 102 | 103 | ![alt text](image-1.png) 104 | 105 | 106 | ```python 107 | # Python program to demonstrate 108 | # multiple inheritance 109 | 110 | # Base class1 111 | class Mother: 112 | mothername = "" 113 | 114 | def mother(self): 115 | print(self.mothername) 116 | 117 | # Base class2 118 | 119 | 120 | class Father: 121 | fathername = "" 122 | 123 | def father(self): 124 | print(self.fathername) 125 | 126 | # Derived class 127 | 128 | 129 | class Son(Mother, Father): 130 | def parents(self): 131 | print("Father :", self.fathername) 132 | print("Mother :", self.mothername) 133 | 134 | 135 | # Driver's code 136 | s1 = Son() 137 | s1.fathername = "RAM" 138 | s1.mothername = "SITA" 139 | s1.parents() 140 | ``` 141 | ## Multilevel Inheritance 142 | 143 | In multilevel inheritance, features of the base class and the derived class are further inherited into the new derived class. This is similar to a relationship representing a child and a grandfather. 144 | 145 | 146 | ![alt text](image-2.png) 147 | 148 | ```python 149 | # Python program to demonstrate 150 | # multilevel inheritance 151 | 152 | # Base class 153 | 154 | 155 | class Grandfather: 156 | 157 | def __init__(self, grandfathername): 158 | self.grandfathername = grandfathername 159 | 160 | # Intermediate class 161 | 162 | 163 | class Father(Grandfather): 164 | def __init__(self, fathername, grandfathername): 165 | self.fathername = fathername 166 | 167 | # invoking constructor of Grandfather class 168 | Grandfather.__init__(self, grandfathername) 169 | 170 | # Derived class 171 | 172 | 173 | class Son(Father): 174 | def __init__(self, sonname, fathername, grandfathername): 175 | self.sonname = sonname 176 | 177 | # invoking constructor of Father class 178 | Father.__init__(self, fathername, grandfathername) 179 | 180 | def print_name(self): 181 | print('Grandfather name :', self.grandfathername) 182 | print("Father name :", self.fathername) 183 | print("Son name :", self.sonname) 184 | 185 | 186 | # Driver code 187 | s1 = Son('Prince', 'Rampal', 'Lal mani') 188 | print(s1.grandfathername) 189 | s1.print_name() 190 | ``` 191 | ## Hierarchical Inheritance 192 | 193 | When more than one derived class is created from a single base, this type of inheritance is called hierarchical inheritance. In this program, we have a parent (base) class and three child (derived) classes. 194 | 195 | ![alt text](image-3.png) 196 | 197 | ```python 198 | # Python program to demonstrate 199 | # Hierarchical inheritance 200 | 201 | 202 | # Base class 203 | class Parent: 204 | def func1(self): 205 | print("This function is in parent class.") 206 | 207 | # Derived class1 208 | 209 | 210 | class Child1(Parent): 211 | def func2(self): 212 | print("This function is in child 1.") 213 | 214 | # Derivied class2 215 | 216 | 217 | class Child2(Parent): 218 | def func3(self): 219 | print("This function is in child 2.") 220 | 221 | 222 | # Driver's code 223 | object1 = Child1() 224 | object2 = Child2() 225 | object1.func1() 226 | object1.func2() 227 | object2.func1() 228 | object2.func3() 229 | ``` 230 | ## Hybrid Inheritance 231 | 232 | Inheritance consisting of multiple types of inheritance is called hybrid inheritance. 233 | 234 | ![alt text]({77F097BC-1FE2-4FA4-A21D-96882897AB9A}.png) 235 | 236 | -------------------------------------------------------------------------------- /OOP/Inheritance/super.md: -------------------------------------------------------------------------------- 1 | Sure! Let’s break down the use of `super()` in simple terms. 2 | 3 | ### What is `super()`? 4 | 5 | `super()` is a built-in function in Python that helps you call methods from a parent class. When you have a class that is based on another class (called inheritance), you can use `super()` to access the parent class's methods and properties. 6 | 7 | ### Why Do We Use `super()`? 8 | 9 | 1. **Calling Parent Methods**: If you want to use a method from the parent class in the child class, you can use `super()`. It allows you to call that method without having to mention the parent class's name. 10 | 11 | 2. **Making Code Cleaner**: If you change the name of the parent class later, using `super()` means you don’t have to go through all the child classes to change the name. It keeps your code tidy. 12 | 13 | 3. **Handling Multiple Inheritance**: Sometimes, a class can inherit from more than one class. `super()` helps Python figure out which method to call next, so you don’t have to worry about the order. 14 | 15 | 4. **Reusing Code**: By using `super()`, you can call methods from the parent class and then add more features in the child class. This saves you from rewriting the same code. 16 | 17 | 5. **Easier Initialization**: When creating an object (like a new dog or a new employee), `super()` helps make sure that the parent class’s properties are set up correctly. 18 | ```python 19 | # INHERITANCE 20 | 21 | # A Python program to demonstrate inheritance 22 | class Person(object): 23 | 24 | # Constructor 25 | def __init__(self, name, id): 26 | self.name = name 27 | self.id = id 28 | 29 | # To check if this person is an employee 30 | def Display(self): 31 | print(self.name, self.id) 32 | 33 | 34 | 35 | 36 | class Emp(Person): 37 | def __init__(self, name, id ,salary): 38 | super().__init__(name, id) 39 | self.salary = salary 40 | 41 | def display_info(self): 42 | super().Display() 43 | print(self.salary) 44 | 45 | # Driver code 46 | # emp = Person("Satyam", 102) # An Object of Person 47 | # emp.Display() 48 | 49 | Emp_details = Emp("Mayank", 103,5000) 50 | 51 | # calling parent class function 52 | Emp_details.display_info() 53 | 54 | # Calling child class function 55 | # Emp_details.Print() 56 | ``` 57 | -------------------------------------------------------------------------------- /OOP/Inheritance/{77F097BC-1FE2-4FA4-A21D-96882897AB9A}.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/OOP/Inheritance/{77F097BC-1FE2-4FA4-A21D-96882897AB9A}.png -------------------------------------------------------------------------------- /OOP/Inheritance/{81C98B3B-0954-4A39-A99F-AB05BA07E41E}.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/OOP/Inheritance/{81C98B3B-0954-4A39-A99F-AB05BA07E41E}.png -------------------------------------------------------------------------------- /OOP/Polymorphism/Polymorphism.md: -------------------------------------------------------------------------------- 1 | 2 | # What is Polymorphism 3 | 4 | The word **polymorphism** means having many forms. In programming, polymorphism refers to the ability to use the same function name (but with different signatures) for different types. 5 | 6 | The term Polymorphism means "many forms," and it allows methods to perform different tasks based on the object that it is acting upon 7 | 8 | ## Example of Inbuilt Polymorphic Functions 9 | 10 | ```python 11 | # Python program to demonstrate in-built polymorphic functions 12 | 13 | # len() being used for a string 14 | print(len("geeks")) 15 | 16 | # len() being used for a list 17 | print(len([10, 20, 30])) 18 | ``` 19 | 20 | **Output:** 21 | ``` 22 | 5 23 | 3 24 | ``` 25 | 26 | ## Examples of User-Defined Polymorphic Functions 27 | 28 | ```python 29 | # A simple Python function to demonstrate Polymorphism 30 | def add(x, y, z=0): 31 | return x + y + z 32 | 33 | # Driver code 34 | print(add(2, 3)) 35 | print(add(2, 3, 4)) 36 | ``` 37 | 38 | **Output:** 39 | ``` 40 | 5 41 | 9 42 | ``` 43 | 44 | 45 | 46 | ```python 47 | class Pakistan(): 48 | def capital(self): 49 | print("Islamabad is the capital of Pakistan.") 50 | 51 | def language(self): 52 | print("Urdu is the national language of Pakistan.") 53 | 54 | def type(self): 55 | print("Pakistan is a developing country.") 56 | 57 | class Bangladesh(): 58 | def capital(self): 59 | print("Dhaka is the capital of Bangladesh.") 60 | 61 | def language(self): 62 | print("Bengali is the most widely spoken language of Bangladesh.") 63 | 64 | def type(self): 65 | print("Bangladesh is a developing country.") 66 | 67 | # Creating objects for each class 68 | obj_pak = Pakistan() 69 | obj_bangladesh = Bangladesh() 70 | 71 | # Loop through the objects and call their methods 72 | for country in (obj_pak, obj_bangladesh): 73 | country.capital() 74 | country.language() 75 | country.type() 76 | 77 | ``` 78 | 79 | 80 | -------------------------------------------------------------------------------- /OOP/Polymorphism/Polymorphism.py: -------------------------------------------------------------------------------- 1 | # # class Shape: 2 | # # def calculate_area(self, radius): 3 | # # return 3.14 * radius * radius # Area of a circle 4 | 5 | # # def calculate_area(self, length, width = 1): 6 | # # return length * width # Area of a rectangle 7 | 8 | # # # Usage 9 | # # shape = Shape() 10 | # # circle_area = shape.calculate_area(10) # This will give an error 11 | # # rectangle_area = shape.calculate_area(5, 10) 12 | # # print(f"Rectangle Area: {rectangle_area}") 13 | # # print(circle_area) 14 | 15 | # # class Pakistan(): 16 | # # def capital(self): 17 | # # print("Islamabad is the capital of Pakistan.") 18 | 19 | # # def language(self): 20 | # # print("Urdu is the national language of Pakistan.") 21 | 22 | # # def type(self): 23 | # # print("Pakistan is a developing country.") 24 | 25 | # # class Bangladesh(): 26 | # # def capital(self): 27 | # # print("Dhaka is the capital of Bangladesh.") 28 | 29 | # # def language(self): 30 | # # print("Bengali is the most widely spoken language of Bangladesh.") 31 | 32 | # # def type(self): 33 | # # print("Bangladesh is a developing country.") 34 | 35 | # # # Creating objects for each class 36 | # # obj_pak = Pakistan() 37 | # # obj_bangladesh = Bangladesh() 38 | 39 | # # # Loop through the objects and call their methods 40 | # # for country in (obj_pak, obj_bangladesh): 41 | # # country.capital() 42 | # # country.language() 43 | # # country.type() 44 | 45 | # # class Pol: 46 | # # def add(self,*a): 47 | # # return sum(a) 48 | 49 | 50 | 51 | # # over = Pol() 52 | # # print(over.add(1)) 53 | 54 | # # # import random as np 55 | # # # vr = np. 56 | 57 | 58 | # # # print(list.__base__) 59 | 60 | 61 | 62 | 63 | # # class Person1: 64 | # # def running(self): 65 | # # print("Person1 is Running") 66 | # # def running(self): 67 | # # print("Person2 is Running") 68 | # # def running(self): 69 | # # print("Person3 is Running") 70 | 71 | 72 | 73 | # # p1 = Person1() 74 | # # p1.running() 75 | 76 | 77 | 78 | # class Addition(object): 79 | # def add(self , x,y): 80 | # return x+y 81 | # def add(self, x,y,z): 82 | # return x + y + z 83 | # def add(self , a,b,c,d): 84 | # return a + b + c + d 85 | # # def add(self , *a): 86 | # # return sum(a) 87 | 88 | 89 | # a1 = Addition() 90 | # print(a1.add(2)) 91 | 92 | 93 | class Animal: 94 | def sound(self): 95 | print("Some generic animal sound") 96 | def eat(self): 97 | print("Some generic animal eating") 98 | 99 | 100 | 101 | class Dog(Animal): 102 | def sound(self): 103 | super().sound() 104 | print("Woof! Woof!") 105 | 106 | class Cat(Animal): 107 | def sound(self): 108 | print("Meow!") 109 | 110 | a1 = Animal() 111 | a2 = Dog() 112 | a2.sound() 113 | a3 = Cat() 114 | 115 | 116 | 117 | 118 | 119 | 120 | # class Credit: 121 | # def payment(self): 122 | # print("Payment is done by credit") 123 | # class Paypal: 124 | # def payment(self): 125 | # print("Payment is done by paypal") 126 | 127 | 128 | -------------------------------------------------------------------------------- /OOP/Polymorphism/Types.md: -------------------------------------------------------------------------------- 1 | # Types 2 | # 1.Compile-time Polymorphism (Method Overloading) 3 | 4 | **Compile-time polymorphism**, commonly referred to as **method overloading**, occurs when multiple methods in the same class have the same name but differ in the type or number of their parameters. The method to be executed is determined at compile time based on the method signature. 5 | 6 | ### Key Points about Method Overloading: 7 | - **Same Method Name**: Multiple methods share the same name. 8 | - **Different Parameters**: They differ in the number of parameters or the types of parameters. 9 | - **Single Class**: Method overloading is implemented within a single class. 10 | - **Static Binding**: The method call is resolved at compile time. 11 | 12 | ### Example of Method Overloading 13 | 14 | Let's illustrate method overloading with a simple `Calculator` class that can add different types of numbers: 15 | 16 | ```python 17 | class Calculator: 18 | # Method to add two integers 19 | def add(self, a: int, b: int) -> int: 20 | return a + b 21 | 22 | # Method to add three integers 23 | def add(self, a: int, b: int, c: int) -> int: 24 | return a + b + c 25 | 26 | # Method to add two floating-point numbers 27 | def add(self, a: float, b: float) -> float: 28 | return a + b 29 | 30 | # Using the Calculator 31 | calc = Calculator() 32 | 33 | # These calls would raise an error because the last defined 'add' method will overwrite the previous ones. 34 | # Uncommenting the following lines will raise errors. 35 | # print(calc.add(5, 10)) # Error: TypeError, no matching method 36 | # print(calc.add(5, 10, 15)) # This would work if the first definition were still there 37 | # print(calc.add(5.5, 2.5)) # This would also work if the floating point version were the last defined. 38 | 39 | ``` 40 | 41 | ### Note: 42 | In Python, unlike languages like C++ or Java, method overloading does not work as expected because the last defined method with the same name overrides the previous ones. 43 | 44 | ### Alternative to Method Overloading in Python 45 | 46 | You can achieve similar functionality using default arguments or variable-length arguments: 47 | 48 | #### Using Default Arguments 49 | 50 | ```python 51 | class Calculator: 52 | # Method to add numbers with default parameters 53 | def add(self, a: int, b: int = 0, c: int = 0) -> int: 54 | return a + b + c 55 | 56 | calc = Calculator() 57 | print(calc.add(5)) # Output: 5 (only 'a' is provided) 58 | print(calc.add(5, 10)) # Output: 15 ('a' and 'b' are provided) 59 | print(calc.add(5, 10, 15)) # Output: 30 (all parameters are provided) 60 | ``` 61 | 62 | #### Using Variable-length Arguments 63 | 64 | ```python 65 | class Calculator: 66 | # Method to add an arbitrary number of numbers 67 | def add(self, *args) -> int: 68 | return sum(args) 69 | 70 | calc = Calculator() 71 | print(calc.add(5)) # Output: 5 72 | print(calc.add(5, 10)) # Output: 15 73 | print(calc.add(5, 10, 15)) # Output: 30 74 | print(calc.add(1, 2, 3, 4, 5)) # Output: 15 (can take any number of arguments) 75 | ``` 76 | 77 | ### Summary 78 | - **Compile-time Polymorphism** (Method Overloading) is a technique that allows the same method name to perform different tasks based on its parameters. 79 | - Python does not support traditional method overloading but provides alternative ways to achieve similar results using default parameters or variable-length arguments. 80 | 81 | 82 | 83 | # 2. Runtime Polymorphism (Method Overriding) 84 | 85 | **Runtime polymorphism**, commonly known as **method overriding**, occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. The method to be invoked is determined at runtime based on the object type, allowing the same method call to behave differently depending on the object that it is invoked on. 86 | 87 | ### Key Points about Method Overriding: 88 | - **Same Method Name**: Both the superclass and the subclass have a method with the same name and signature. 89 | - **Subclass Implementation**: The subclass provides its own implementation of the method. 90 | - **Dynamic Binding**: The method call is resolved at runtime, which means the correct method is called based on the object type. 91 | 92 | ### Example of Method Overriding 93 | 94 | Let's illustrate method overriding with a simple example involving a base class `Animal` and derived classes `Dog` and `Cat`: 95 | 96 | ```python 97 | class Animal: 98 | def sound(self): 99 | print("Some generic animal sound") 100 | 101 | class Dog(Animal): 102 | def sound(self): 103 | print("Woof! Woof!") 104 | 105 | class Cat(Animal): 106 | def sound(self): 107 | print("Meow!") 108 | 109 | # Create instances of Dog and Cat 110 | animal1 = Dog() 111 | animal2 = Cat() 112 | 113 | # Call the sound method 114 | animal1.sound() # Output: Woof! Woof! 115 | animal2.sound() # Output: Meow! 116 | ``` 117 | 118 | ### Explanation of the Example: 119 | 1. **Base Class**: The `Animal` class has a method `sound()` that prints a generic animal sound. 120 | 2. **Derived Classes**: The `Dog` and `Cat` classes override the `sound()` method to provide their specific implementations. 121 | 3. **Method Call**: When we call the `sound()` method on an instance of `Dog`, it invokes the overridden method in the `Dog` class. Similarly, for an instance of `Cat`, it invokes the method in the `Cat` class. 122 | 123 | ### Advantages of Runtime Polymorphism: 124 | - **Flexibility**: You can use a unified interface (the base class) while providing specific implementations in derived classes. 125 | - **Code Maintenance**: It enhances the maintainability of code by allowing changes to be made in derived classes without altering the base class. 126 | 127 | ### Real-Life Example 128 | 129 | 1. **Shape Area Calculation**: 130 | - **Base Class**: `Shape` with a method `area()`. 131 | - **Derived Classes**: `Circle` and `Rectangle`, each implementing the `area()` method to calculate the area based on their specific shapes. 132 | 133 | ```python 134 | import math 135 | 136 | class Shape: 137 | def area(self): 138 | pass 139 | 140 | class Circle(Shape): 141 | def __init__(self, radius): 142 | self.radius = radius 143 | 144 | def area(self): 145 | return math.pi * (self.radius ** 2) 146 | 147 | class Rectangle(Shape): 148 | def __init__(self, length, width): 149 | self.length = length 150 | self.width = width 151 | 152 | def area(self): 153 | return self.length * self.width 154 | 155 | # Create instances of Circle and Rectangle 156 | shapes = [Circle(5), Rectangle(4, 6)] 157 | 158 | # Calculate areas 159 | for shape in shapes: 160 | print(f"Area: {shape.area()}") 161 | ``` 162 | 163 | **Output**: 164 | ``` 165 | Area: 78.53981633974483 166 | Area: 24 167 | ``` 168 | 169 | ### Summary 170 | - **Runtime Polymorphism** (Method Overriding) allows subclasses to provide specific implementations for methods defined in their superclass. 171 | - It promotes flexibility and maintainability in code design by enabling the same method to behave differently depending on the object type. -------------------------------------------------------------------------------- /OOP/Polymorphism/week.py: -------------------------------------------------------------------------------- 1 | # # age = int(input("write your age : ")) 2 | # # No_of_weeks_in_one_year = int(365/7) 3 | # # years_left = 90 - age 4 | # # no_weeks_left = No_of_weeks_in_one_year * years_left 5 | # # print(f"You have {no_weeks_left} weeks left.") 6 | # # age = int(input("Enter your age : ")) 7 | # # total_weeks = int(age)*365/7 8 | # # print(int(total_weeks)) 9 | 10 | 11 | # # total=90 12 | # # age=int(input("Enter your age")) 13 | # # age_calculate=total-age 14 | # # ageinweeks=age_calculate*52 15 | # # print(ageinweeks) 16 | # user_age = int(input("Enter your age... ")) 17 | # total_years = 90 18 | # remaining_years = total_years - user_age 19 | # remaining_weeks = remaining_years * 52 20 | # print(f"You have approximately {remaining_weeks} weeks left to live.") -------------------------------------------------------------------------------- /Operators in python/Operators_in_python.py: -------------------------------------------------------------------------------- 1 | # Arithmetic Operators 2 | # a: int = int(input("Write your first num: ")) 3 | # b: int = int(input("Write your second num: ")) 4 | 5 | # add: int = a + b 6 | # sub: int = a - b 7 | # mul: int = a * b 8 | # mod: int = a % b 9 | # p: int = a ** b 10 | 11 | # print("Addition:", add) 12 | # print("Subtraction:", sub) 13 | # print("Multiplication:", mul) 14 | # print("Modulus:", mod) 15 | # print("Exponentiation:", p) 16 | 17 | # Relational Operators or Comparison Operators 18 | # a: int = int(input("Write your first num: ")) 19 | # b: int = int(input("Write your second num: ")) 20 | # print("Is a greater than b?", a > b) 21 | # print("Is a less than b?", a < b) 22 | # print("Is a equal to b?", a == b) 23 | # print("Is a not equal to b?", a != b) 24 | # print("Is a greater than or equal to b?", a >= b) 25 | # print("Is a less than or equal to b?", a <= b) 26 | 27 | 28 | 29 | 30 | # Logical Operators 31 | # a : bool = True 32 | # b : bool = False 33 | # print(a and b) 34 | # print(a or b) 35 | # print(not a) 36 | 37 | 38 | # Bitwise Operators 39 | # a: int = int(input("Enter the first number: ")) 40 | # b: int = int(input("Enter the second number: ")) 41 | 42 | # print(a & b) # Bitwise AND 43 | # print(a | b) # Bitwise OR 44 | # print(~a) # Bitwise NOT 45 | # print(a ^ b) # Bitwise XOR 46 | # print(a >> 2) # Right shift 47 | # print(a << 2) # Left shift 48 | 49 | # Assignment Operators 50 | # a: int = int(input("Enter the first number: ")) 51 | # b: int = int(input("Enter the second number: ")) 52 | # b += a 53 | # print(b) 54 | # b -= a 55 | # print(b) 56 | # b *= a 57 | # print(b) 58 | # b <<= a 59 | # print(b) 60 | 61 | # Identity Operators 62 | # a : int = 10 63 | # b : int = 20 64 | # c : int = a 65 | 66 | # print(a is not b) 67 | # print(a is c) 68 | 69 | 70 | 71 | # Membership Operators 72 | # x : int = 24 73 | # y : int = 20 74 | # list1 : list = [10, 20, 30, 40, 50] 75 | 76 | # if (x not in list1): 77 | # print("x is NOT present in given list") 78 | # else: 79 | # print("x is present in given list") 80 | 81 | # if (y in list1): 82 | # print("y is present in given list") 83 | # else: 84 | # print("y is NOT present in given list") 85 | 86 | 87 | 88 | 89 | # Ternary Operators 90 | # a: int = 10 91 | # b : int = 20 92 | # min = a if a < b else b 93 | 94 | # print(min) 95 | 96 | a = 10 97 | b = 10 98 | if not b != a: 99 | print("uzair") 100 | -------------------------------------------------------------------------------- /Operators in python/f_string.py: -------------------------------------------------------------------------------- 1 | name = "uzair" 2 | age = 20 3 | 4 | print(f" MY name is {name.upper()} and my age is {age} ") 5 | -------------------------------------------------------------------------------- /Operators in python/main.py: -------------------------------------------------------------------------------- 1 | # Output 2 | # print("Hello World") 3 | 4 | # Data types 5 | 6 | # Primitive and Non primitive 7 | 8 | 9 | # primitive : u can store single value 10 | 11 | # str : string : anything which comes inside inverted commas is called string 12 | # int : integer : 123546846465468 13 | # float : decimal number : 123.456 14 | # bool : boolean : true/false 15 | 16 | # type() 17 | 18 | # print( type("5765") ) 19 | 20 | # "" 21 | # '' 22 | # ''''' 23 | 24 | 25 | # print(''' 'Quaid' Said : Work "Work" and Work ''') 26 | # print ('''uzair 27 | # yasin ''') 28 | 29 | # Escape Sequence 30 | # \n : new line 31 | # \t : tab space 32 | # \\ : back slash 33 | # print(" 'Quaid' Said : Work \"Work\" and Work ") 34 | # print("uzair \nyasin") 35 | 36 | 37 | # Variables 38 | 39 | # name = 5.5 40 | # print(name) 41 | # Rules of Variable 42 | 43 | # no space 44 | # dont start with integer 45 | # dont use special character 46 | # dont use keyword 47 | 48 | 49 | # meaningful name 50 | # a = 0 51 | # print = "uzair" 52 | # print(print) 53 | 54 | # stages 55 | 56 | # 1. declaration 57 | # 2. initialization 58 | 59 | # name = "uzair" 60 | 61 | 62 | # String 63 | # indexing 64 | # slicing 65 | # steping 66 | # [start : end : step] 67 | # for reversing string we can give step in minus 68 | # name = "My name is Muhammad Uzair and I am a Piaic Student" 69 | # print(name[::]) 70 | 71 | # immutable : anything which is unchangeable 72 | # # mutable : anything which is changeable 73 | 74 | 75 | # # String function 76 | # # 1. lower() 77 | # # 2. upper() 78 | # # 3. title() 79 | # # 4. capitalize() 80 | 81 | 82 | # # name = "uzaira" 83 | # # Second_str = "" .join("uzair") 84 | # # # print(name) 85 | # # print(Second_str) 86 | 87 | # # print("uzair","yasin" , sep="-") 88 | # # print("Yasin ") 89 | 90 | # # print("Hello", "World") 91 | # # num = False 92 | # # print(type(num)) 93 | 94 | # # print("uzair" , end= "-") 95 | # # print("yasin") 96 | # # print("Yasin " 97 | 98 | # # name = " uzair" 99 | # num1 = 20 100 | # num = 55 101 | # # edu = "Bs" 102 | # print(num <= num1) 103 | 104 | # # print( "hello my name is " , name , "and my age is" ,age , "and my edu is " , edu ) 105 | # # print(f"hell my name is{name}and my age {age} and edu is {edu}") 106 | 107 | 108 | 109 | # a = 5 110 | # b = 10 111 | 112 | # a = 5 113 | # print(a) 114 | # print(a != b) 115 | 116 | 117 | 118 | 119 | age = int(input("write your age: ")) 120 | print("The age is " , age) 121 | print(type(age)) -------------------------------------------------------------------------------- /Print statement/print.md: -------------------------------------------------------------------------------- 1 | # Print() Function 2 | 3 | Python print() function prints the message to the screen or any other standard output device 4 | 5 | 6 | 7 | 8 | # Easy explanation 9 | The print() function in Python is used to display output on the screen. It's one of the most basic yet powerful functions, helping you see messages, values, and results of your code. You simply pass what you want to print inside the parentheses, and Python will display it. 10 | 11 | Example 1: Printing a Simple Message 12 | In this example, we'll print a basic message to the screen. 13 | 14 | ```python 15 | print("Hello, World!") 16 | ``` 17 | 18 | Output: 19 | 20 | ``` 21 | Hello, World! 22 | ``` 23 | # what is string 24 | ### Anything written inside inverted commas is called string (will explain this concept in upcoming classes) 25 | 26 | # Commas in print functions 27 | 28 | ## single comma 29 | 30 | ```python 31 | print('Hello, World!') 32 | ``` 33 | 34 | ## double comma 35 | 36 | ```python 37 | print("Hello, World!") 38 | ``` 39 | 40 | ## triple comma 41 | 42 | ```python 43 | print('''Hello, World!''') 44 | ``` 45 | 46 | # difference between them 47 | 48 | ### you will use single comma when you need to use double comma inside 49 | ### you will use double comma when you need to use single comma inside 50 | ### you will use triple comma when you need to use double comma and single comma inside 51 | ### triple comma also use for writing double line string 52 | 53 | 54 | # Parameters in print function 55 | 56 | 57 | 58 | ## Python end parameter in print() 59 | 60 | By default, Python's print() function ends with a newline. A programmer with C/C++ background may wonder how to print without a newline. Python’s print() function comes with a parameter called ‘end‘. By default, the value of this parameter is ‘\n’, i.e., the new line character. 61 | 62 | Example 1: 63 | Here, we can end a print statement with any character/string using this parameter. 64 | 65 | ```python 66 | # ends the output with a space 67 | print("Welcome to", end = ' ') 68 | print("GeeksforGeeks", end= ' ') 69 | ``` 70 | 71 | 72 | # Easy Explanation 73 | 74 | 75 | The `end` parameter in the `print()` function lets you control what appears at the end of the printed output. By default, `print()` adds a newline (`\n`) at the end, so each `print()` call starts on a new line. With `end`, you can change this to any other character or string, like a space or comma, or even prevent a new line entirely. 76 | 77 | ### Example 1: Using `end` to Print on the Same Line 78 | 79 | Here, we'll print multiple items on the same line by changing the `end` parameter. 80 | 81 | ```python 82 | print("Hello", end=" ") 83 | print("World!") 84 | ``` 85 | 86 | **Output:** 87 | ``` 88 | Hello World! 89 | ``` 90 | 91 | In this example, `end=" "` adds a space instead of a new line, so the next `print()` statement continues on the same line. 92 | 93 | ### Example 2: Using `end` with Custom Text 94 | 95 | You can also set `end` to any string. Here, we’ll use `end=" - "` to separate items. 96 | 97 | ```python 98 | print("Python", end=" - ") 99 | print("is", end=" - ") 100 | print("fun!") 101 | ``` 102 | 103 | **Output:** 104 | ``` 105 | Python - is - fun! 106 | ``` 107 | 108 | In this case, each `print()` adds `" - "` at the end, creating a custom separator. This is useful when you want to format your output in a specific way. 109 | 110 | 111 | 112 | # Easy and more explanation 113 | 114 | 115 | ### sep parameter in print() 116 | 117 | The separator between the arguments to print() function in Python is space by default (softspace feature), which can be modified and can be made to any character, integer, or string as per our choice. The ‘sep’ parameter is used to achieve the same, and it is found only in Python 3.x or later. It is also used for formatting the output strings. 118 | 119 | Examples: 120 | 121 | ```python 122 | # code for disabling the softspace feature 123 | print('G','F','G', sep='') 124 | 125 | # for formatting a date 126 | print('09','12','2016', sep='-') 127 | 128 | # another example 129 | print('pratik','geeksforgeeks', sep='@') 130 | 131 | 132 | ``` 133 | 134 | The `sep` parameter in the `print()` function controls how multiple items are separated when printed. By default, `sep` is set to a single space (`' '`), so when you provide multiple arguments to `print()`, they are separated by a space. 135 | 136 | ### Usage of `sep` 137 | 138 | If you want to use a different separator, you can specify it using the `sep` parameter. This can be any string, such as a comma, hyphen, newline, or even an empty string. 139 | 140 | ### Syntax 141 | ```python 142 | print(object1, object2, ..., sep='separator') 143 | ``` 144 | 145 | ### Examples 146 | 147 | #### 1. Default `sep` (space) 148 | When you don’t specify `sep`, `print()` separates each argument with a space. 149 | ```python 150 | print("apple", "banana", "cherry") # Output: apple banana cherry 151 | ``` 152 | 153 | #### 2. Custom Separator: Comma 154 | Using `sep=","` places a comma between each item. 155 | ```python 156 | print("apple", "banana", "cherry", sep=", ") # Output: apple, banana, cherry 157 | ``` 158 | 159 | #### 3. Custom Separator: Hyphen 160 | Using `sep="-"` places a hyphen between each item. 161 | ```python 162 | print("apple", "banana", "cherry", sep="-") # Output: apple-banana-cherry 163 | ``` 164 | 165 | #### 4. Custom Separator: Empty String 166 | Using `sep=""` places no space between items, concatenating them directly. 167 | ```python 168 | print("apple", "banana", "cherry", sep="") # Output: applebananacherry 169 | ``` 170 | 171 | #### 5. Custom Separator: Newline 172 | Using `sep="\n"` places each item on a new line. 173 | ```python 174 | print("apple", "banana", "cherry", sep="\n") 175 | # Output: 176 | # apple 177 | # banana 178 | # cherry 179 | ``` 180 | 181 | ### Why Use `sep`? 182 | 183 | The `sep` parameter is handy when formatting output without needing to manually concatenate strings. It can make the code cleaner and easier to read, especially when dealing with a large number of items or dynamic data. 184 | 185 | 186 | # summary table 187 | 188 | | Parameter | Default | Description | Example Usage | Example Output | 189 | |-----------|---------|---------------------------------------|----------------------------------------|---------------------------------| 190 | | `sep` | `' '` | Specifies the separator between multiple objects | `print("apple", "banana", sep=", ")` | `apple, banana` | 191 | | `end` | `'\n'` | Specifies the string appended at the end of the output | `print("Hello", end="!")` | `Hello!` (no newline after) 192 | 193 | 194 | 195 | # An escape sequence 196 | In Python is a special way to represent certain characters in a string that are otherwise hard to include. They start with a backslash (`\`) and tell Python to interpret the next character in a specific way. For example, `\n` is an escape sequence for a new line, so when Python sees it, it moves to the next line in the output. 197 | 198 | ### Example 1: New Line (`\n`) 199 | The `\n` escape sequence creates a new line in a string. 200 | 201 | ```python 202 | text = "Hello,\nWorld!" 203 | print(text) 204 | ``` 205 | 206 | **Output:** 207 | ``` 208 | Hello, 209 | World! 210 | ``` 211 | 212 | Here, `\n` tells Python to break the line, so "World!" appears on a new line. 213 | 214 | ### Example 2: Tab (`\t`) 215 | The `\t` escape sequence adds a horizontal tab space in a string. 216 | 217 | ```python 218 | text = "Hello,\tWorld!" 219 | print(text) 220 | ``` 221 | 222 | **Output:** 223 | ``` 224 | Hello, World! 225 | ``` 226 | 227 | In this example, `\t` adds a tab space between "Hello," and "World!". Escape sequences make it easier to control formatting in strings. 228 | 229 | 230 | # More information 231 | 232 | Escape sequences in Python's `print()` function allow you to include special characters within strings. These sequences start with a backslash (`\`) followed by a character, letting you insert things like newlines, tabs, quotes, or even Unicode characters. 233 | 234 | ### Common Escape Sequences 235 | 236 | | Escape Sequence | Description | Example Usage | Output | 237 | |-----------------|-----------------------------|-----------------------------|---------------------------------| 238 | | `\n` | Newline | `print("Hello\nWorld")` | `Hello`
`World` | 239 | | `\t` | Horizontal Tab | `print("Hello\tWorld")` | `Hello World` | 240 | | `\\` | Backslash | `print("This is a backslash: \\")` | `This is a backslash: \` | 241 | | `\'` | Single Quote | `print('It\'s Python')` | `It's Python` | 242 | | `\"` | Double Quote | `print("He said, \"Hi\"")` | `He said, "Hi"` | 243 | | `\r` | Carriage Return | `print("Hello\rWorld")` | `World` (overwrites "Hello") | 244 | | `\b` | Backspace | `print("Hello\bWorld")` | `HellWorld` (removes "o") | 245 | | `\f` | Form Feed | `print("Hello\fWorld")` | `Hello`
` World` | 246 | | `\uXXXX` | Unicode Character (16-bit) | `print("\u2764")` | ❤️ (heart symbol) | 247 | | `\UXXXXXXXX` | Unicode Character (32-bit) | `print("\U0001F600")` | 😀 (grinning face emoji) | 248 | | `\xXX` | ASCII Character (hex) | `print("\x48\x69")` | `Hi` | 249 | | `\N{name}` | Named Unicode Character | `print("\N{check mark}")` | ✅ | 250 | 251 | ### Examples 252 | 253 | 1. **Newline (`\n`)** 254 | ```python 255 | print("Hello\nWorld") 256 | # Output: 257 | # Hello 258 | # World 259 | ``` 260 | 261 | 2. **Tab (`\t`)** 262 | ```python 263 | print("Hello\tWorld") 264 | # Output: Hello World 265 | ``` 266 | 267 | 3. **Unicode Character (`\u` and `\U`)** 268 | ```python 269 | print("\u2764") # Output: ❤️ (heart symbol) 270 | print("\U0001F600") # Output: 😀 (grinning face emoji) 271 | ``` 272 | 273 | 4. **Double Quote (`\"`) and Single Quote (`\'`)** 274 | ```python 275 | print("She said, \"Hi\"") 276 | # Output: She said, "Hi" 277 | 278 | print('It\'s Python') 279 | # Output: It's Python 280 | ``` 281 | 282 | 5. **Backslash (`\\`)** 283 | ```python 284 | print("This is a backslash: \\") 285 | # Output: This is a backslash: \ 286 | ``` 287 | 288 | Escape sequences are a powerful tool in `print()` for handling special characters and formatting strings precisely. -------------------------------------------------------------------------------- /Print statement/print.py: -------------------------------------------------------------------------------- 1 | # print('''Someone said : 2 | # # this is good''') 3 | 4 | 5 | # # print("uzair", end=" word ") 6 | # # print("yasin") 7 | 8 | 9 | # # print("uzair" , "yasin","ali","ahmed" , sep=" _ " ) 10 | 11 | 12 | # print("Muhammad \"Uzair\" \'Yasin\'") 13 | # print("\U0001F600") 14 | # # "" 15 | # name = "1" 16 | # print(type(name)) 17 | # print('uzair "ali" ') 18 | # print("uzair yasin 'rafay'") 19 | # print('''uzair "ali" , 'rafay' 20 | # yasin''') 21 | 22 | # # Escape sequences 23 | # print("uzair \tyasin") 24 | 25 | # print("uzair \nyasin") 26 | 27 | # print("yasin\ruzair") 28 | # print("uzair \"yasin\"") 29 | 30 | 31 | # Variables 32 | # it is used to stores values or u can say it a container 33 | # # 34 | # name = "uzair" 35 | 36 | # print(name) 37 | 38 | # Rules no to do 39 | # no number at start 40 | # no spaces 41 | # no hiyhen 42 | # no pre used words 43 | 44 | # rule to do 45 | # meaningful variables 46 | 47 | 48 | # int and float variables 49 | 50 | # num = 5.5 51 | 52 | # type_var = type(num) 53 | 54 | # print(type_var) 55 | 56 | 57 | # input func 58 | 59 | # name = input("write your name : ") 60 | # print("your name is " , name) 61 | 62 | 63 | # age = input("write your age : ") 64 | # print("your age is " , age) 65 | # # print(type(age)) 66 | 67 | 68 | # type casting 69 | 70 | 71 | # # age = int(input("write your age : ")) 72 | # # print("your age is " , age) 73 | # # print(type(age)) 74 | 75 | # #list to dic 76 | 77 | # li = [1,2,3,4] 78 | # dict = {} 79 | # for x,y in enumerate(li): 80 | # dict[x] = y 81 | 82 | 83 | # print(dict) 84 | 85 | # string to list 86 | 87 | # name = "uzair" 88 | # li = [] 89 | # for x in name: 90 | # li.append(x) 91 | 92 | # print(li) 93 | 94 | # # string to dictionary 95 | # name = "uzair" 96 | 97 | # dict = {} 98 | 99 | # for x,y in enumerate(name): 100 | # dict[x] = y 101 | 102 | # print(dict) 103 | 104 | 105 | # list to string 106 | 107 | # li = ["u","z","a","i","r"] 108 | # string_li = "".join(li) 109 | # print(string_li) 110 | 111 | 112 | 113 | # continue 114 | 115 | 116 | # String 117 | 118 | # anything inside a inverted commas is considered as a string 119 | 120 | # name = "my name is uzair and my age is 20" 121 | 122 | # for x,y in enumerate(name): 123 | # print(f"{x} : {y}") 124 | 125 | # syntax [start, end - 1,step] 126 | # print(name[11:16: 2]) 127 | 128 | # reverse string 129 | # print(name[::-1]) 130 | 131 | 132 | # string Func 133 | # name = "my name is uzair and my age is 20" 134 | 135 | # print(name.upper()) 136 | # print(name.lower()) 137 | # print(name.capitalize()) 138 | # print(name.title()) 139 | # print(name.count("a")) 140 | # print(name.find("a")) 141 | # print(name.replace("a", "b")) 142 | # print(name.split(" ")) 143 | # print(name.strip(" ")) 144 | # print(name.startswith("m")) 145 | # print(name.endswith("0")) 146 | # print(name.center(50,"*")) 147 | 148 | 149 | # # If statement 150 | # simple if 151 | # marks = 50 152 | 153 | # # if marks == 50: 154 | # print("Grade A") 155 | 156 | # if else 157 | 158 | 159 | # # if marks == 50: 160 | # print("Grade A") 161 | 162 | # # else: 163 | # print("Grade B") 164 | 165 | 166 | # if elif 167 | # marks = 50 168 | 169 | # if marks == 50: 170 | # print("Grade A") 171 | # elif marks < 50: 172 | # print("Grade b") 173 | # elif marks > 50: 174 | # print("Grade c") 175 | # else: 176 | # print("Grade D") 177 | 178 | 179 | 180 | 181 | # nested if 182 | 183 | # marks = 50 184 | # age = 20 185 | # if marks == 50: 186 | # print("Grade A") 187 | # if age < 18: 188 | # print("You are eligible for driving") 189 | # else: 190 | # print("You are not eligible for driving") 191 | 192 | # else: 193 | # print("Grade B") 194 | 195 | 196 | # print("statement below if") 197 | 198 | 199 | # for loop 200 | 201 | 202 | # name = "uzair" 203 | 204 | # simple loop 205 | # for x in name: 206 | # print(x , end = "") 207 | 208 | # range loop 209 | # for x in range(0,11,2): 210 | # print(x) 211 | 212 | # # nested loop 213 | # for x in range(1,4): 214 | # for y in range(1,4): 215 | # print(x,y) 216 | 217 | 218 | 219 | # while loop 220 | 221 | # score = 0 222 | 223 | # while score < 5: 224 | # print(score) 225 | # score += 1 226 | 227 | 228 | # control statements 229 | 230 | 231 | # score = 0 232 | 233 | # while score < 5: 234 | # print(score) 235 | # score += 1 236 | # if score == 3: 237 | # continue 238 | 239 | 240 | 241 | # for x in range(1,10): 242 | # if x == 6: 243 | # continue 244 | # else: 245 | # print(x) 246 | 247 | # Functions 248 | # def even_odd(x): 249 | # """This function is used to test whether a number is even or odd""" 250 | # if x % 2 == 0: 251 | # print("even") 252 | # else: 253 | # print("odd") 254 | 255 | # for x in range(1,4): 256 | # even_odd(int(input("write any number : " ))) 257 | 258 | # print(enumerate.__doc__) 259 | 260 | # non Pre (multiple types values can b stored) 261 | 262 | # List 263 | # li = [1,4,2,3, "uzair"] 264 | 265 | 266 | 267 | # List Functions 268 | 269 | # li.append(6) 270 | # print(li) 271 | # li.insert(2,7) 272 | # print(li) 273 | # li.remove(4) 274 | # print(li) 275 | # li.pop(2) 276 | # print(li) 277 | # li.sort() 278 | # print(li) 279 | # li.reverse() 280 | # print(li) 281 | # li.clear() 282 | # print(li) 283 | # li.extend([6,7,8]) 284 | # print(li) 285 | # index = li.index(4) 286 | # print(index) 287 | # li = [1,2,3,4 , "uzair",True, 5 288 | # .count(4) 289 | # print(li) 290 | # li = [1,2,3,4 , "uzair",True, 5 291 | # .copy() 292 | # print(li) 293 | # 294 | 295 | 296 | # Tuple 297 | # tu = (1,2,3,4,"string") 298 | 299 | # print(tu[2:4:2]) 300 | 301 | 302 | # Tuple Function 303 | 304 | # tu = (1,2,3,4,"string") 305 | 306 | # tu.count(1) 307 | 308 | # # print(tu.index(4)) 309 | 310 | 311 | 312 | # Dictionary 313 | 314 | # dict = {"a" : "Uzair", "b" : 20 , "c" : "Bscs"} 315 | 316 | 317 | # for x ,y in dict.items(): 318 | # print(f"{x} : {y}") 319 | 320 | 321 | # print(dict["b"]) 322 | 323 | 324 | # dict2 = {} 325 | 326 | 327 | # dict2["a"] = 1 328 | # dict2["b"] = 2 329 | # dict2["c"] = 3 330 | # dict2["d"] = 4 331 | 332 | # print(dict2) 333 | 334 | 335 | # Dict Functios 336 | dict = {"a" : "Uzair", "b" : 20 , "c" : "bscs"} 337 | # print(dict.keys()) 338 | # print(dict.values()) 339 | # print(dict.items()) 340 | # print(dict.get("a")) 341 | # print(dict.get("e")) 342 | # print(dict.setdefault("d","rafay")) 343 | # print(dict) 344 | # print(dict.update({"d":"ali"})) 345 | # print(dict) 346 | # print(dict.pop("a")) 347 | # print(dict) 348 | # print(dict.popitem()) 349 | # print(dict) 350 | 351 | 352 | 353 | # Error Handling 354 | # try: 355 | # age = int(input("write your age : ")) 356 | # print(age) 357 | # except Exception as e: 358 | # print("error occurred") 359 | # else: 360 | # print("No error occurred") 361 | # finally: 362 | # print("done") 363 | 364 | # print("uzair") 365 | 366 | 367 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | "Python_Lectures By Muhammad Uzair" 2 | -------------------------------------------------------------------------------- /String/__pycache__/string.cpython-312.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/String/__pycache__/string.cpython-312.pyc -------------------------------------------------------------------------------- /String/index.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/String/index.png -------------------------------------------------------------------------------- /String/main.py: -------------------------------------------------------------------------------- 1 | # # # Output 2 | # # # print("Hello World") 3 | 4 | # # # Data types 5 | 6 | # # # Primitive and Non primitive 7 | 8 | 9 | # # # primitive : u can store single value 10 | 11 | # # # str : string : anything which comes inside inverted commas is called string 12 | # # # int : integer : 123546846465468 13 | # # # float : decimal number : 123.456 14 | # # # bool : boolean : true/false 15 | 16 | # # # type() 17 | 18 | # # # print( type("5765") ) 19 | 20 | # # # "" 21 | # # # '' 22 | # # # ''''' 23 | 24 | 25 | # # # print(''' 'Quaid' Said : Work "Work" and Work ''') 26 | # # # print ('''uzair 27 | # # # yasin ''') 28 | 29 | # # # Escape Sequence 30 | # # # \n : new line 31 | # # # \t : tab space 32 | # # # \\ : back slash 33 | # # # print(" 'Quaid' Said : Work \"Work\" and Work ") 34 | # # # print("uzair \nyasin") 35 | 36 | 37 | # # # Variables 38 | 39 | # # # name = 5.5 40 | # # # print(name) 41 | # # # Rules of Variable 42 | 43 | # # # no space 44 | # # # dont start with integer 45 | # # # dont use special character 46 | # # # dont use keyword 47 | 48 | 49 | # # # meaningful name 50 | # # # a = 0 51 | # # # print = "uzair" 52 | # # # print(print) 53 | 54 | # # # stages 55 | 56 | # # # 1. declaration 57 | # # # 2. initialization 58 | 59 | # # # name = "uzair" 60 | 61 | 62 | # # # String 63 | # # # indexing 64 | # # # slicing 65 | # # # steping 66 | # # # [start : end : step] 67 | # # # for reversing string we can give step in minus 68 | # # # name = "My name is Muhammad Uzair and I am a Piaic Student" 69 | # # # print(name[::]) 70 | 71 | # # # immutable : anything which is unchangeable 72 | # # # mutable : anything which is changeable 73 | 74 | 75 | # # # String function 76 | # # # 1. lower() 77 | # # # 2. upper() 78 | # # # 3. title() 79 | # # # 4. capitalize() 80 | 81 | 82 | # # # name = "uzaira" 83 | # # # Second_str = "" .join("uzair") 84 | # # # # print(name) 85 | # # # print(Second_str) 86 | 87 | # # # print("uzair ",sep="+") 88 | # # # print("Yasin ") 89 | 90 | 91 | 92 | # # num = "uzair yasin" 93 | 94 | # # # for z,y in enumerate(num): 95 | # # # print(z,y) 96 | 97 | # # print(num[:]) 98 | 99 | 100 | # # [start,end,step] 101 | 102 | 103 | # # # string = "uzair" 104 | # # # string2 = string.upper() 105 | 106 | # # # print("original string" , string) 107 | # # # print("changed string" , string2) 108 | 109 | 110 | # # string = '''uzair rafay 111 | # # ali "ahmed " ''' 112 | 113 | # # string2 = "uzair\trafay\nali\t\"ahmed\"" 114 | 115 | # # print(string) 116 | # # print() 117 | # # print(string2) 118 | 119 | 120 | 121 | # string = "uzair yasin" 122 | 123 | # li = list(string) 124 | 125 | # li.pop() 126 | 127 | # string2 = "".join(li) 128 | # print(string2) 129 | 130 | 131 | 132 | # INPUT FUNCTION 133 | 134 | # name = input("write your name : ") 135 | # print("Your name is :" + name) 136 | 137 | age = int(input("write your age : ")) 138 | print("Your age is :" + age) 139 | # age_int = int(age) 140 | # print(type(age)) 141 | # print(type(age_int)) -------------------------------------------------------------------------------- /String/string.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "\n", 13 | "b\n", 14 | " follows a, c follows b\n" 15 | ] 16 | } 17 | ], 18 | "source": [ 19 | "# string = \"b follows a, c follows b\"\n", 20 | "# string1 = string.partition('b')\n", 21 | "# for x in string1:\n", 22 | "# print(x)" 23 | ] 24 | } 25 | ], 26 | "metadata": { 27 | "kernelspec": { 28 | "display_name": "Python 3", 29 | "language": "python", 30 | "name": "python3" 31 | }, 32 | "language_info": { 33 | "codemirror_mode": { 34 | "name": "ipython", 35 | "version": 3 36 | }, 37 | "file_extension": ".py", 38 | "mimetype": "text/x-python", 39 | "name": "python", 40 | "nbconvert_exporter": "python", 41 | "pygments_lexer": "ipython3", 42 | "version": "3.12.5" 43 | } 44 | }, 45 | "nbformat": 4, 46 | "nbformat_minor": 2 47 | } 48 | -------------------------------------------------------------------------------- /String/string1.py: -------------------------------------------------------------------------------- 1 | # # # # "Quaid e Azam" : ' ' 2 | # # # # # uzair 3 | # # # # # uzair 4 | # # # # # uzair 5 | # # # # uzair 6 | # # # # uzair 7 | # # # # uzair 8 | # # # # uzair 9 | # # # # uzair 10 | # # # # uzair 11 | # # # # uzair 12 | 13 | # # # # string_1 = ''' 'hello' 14 | # # # # "world" ''' 15 | # # # # print(string_1) 16 | 17 | 18 | 19 | # # # # Accessing character in String using index 20 | # # # 1 21 | # # # # String1 = "GeeksForGeeks" 22 | # # # # print("Initial String: ", String1) 23 | 24 | # # # # print(String1[7]) 25 | # # # # print(String1[-7]) 26 | # # # # print(String1[20]) 27 | 28 | # # # # Slicing 29 | 30 | # # # # Creating a String 31 | # # # # String1 = "GeeksForGeeks" 32 | # # # # print("Initial String: ") 33 | # # # # print(String1) 34 | 35 | # # # # # Printing 3rd to 12th character 36 | # # # # print("\nSlicing characters from 5-8: ") 37 | # # # # print(String1[5:8]) 38 | 39 | # # # # Python String Reversed 40 | 41 | # # # name = "Uzair Yasin " 42 | # # # # [start : end : step] 43 | # # # # print(name[0:7:3]) 44 | # # # print(name[::-2]) 45 | # # # print(name) 46 | 47 | 48 | 49 | # # # # 1 . n a e (10 times) (index) 50 | # # # # 2 . my name is this (10 times) (slicing) 51 | # # # # 3 . 6 step (20 times ) 52 | # # # # # 4 . 10 string (10 times) 53 | 54 | # # # # Python Program to Update 55 | # # # # character of a String 56 | 57 | # # # String1 = "Hello, I'm a Geek" 58 | # # # print("Initial String: ") 59 | # # # print(String1) 60 | 61 | # # # # Updating a character of the String 62 | # # # ## As python strings are immutable, they don't support item updation directly 63 | # # # ### there are following two ways 64 | # # # #1 65 | # # # list1 = list(String1) 66 | # # # print(list1) 67 | # # # list1[2] = 'p' 68 | # # # String2 = ''.join(list1) 69 | # # # print("\nUpdating character at 2nd Index: ") 70 | # # # print(String2) 71 | 72 | # # #2 73 | # # # String3 = String1[0:2] + 'p' + String1[3:] 74 | # # # print(String3) 75 | 76 | 77 | # # # Deleting/Updating from a String 78 | 79 | # # # name = "Uzair Yasin" 80 | # # # print(name) 81 | # # # list1 = list(name) 82 | # # # print(list1) 83 | # # # print(type(list1)) 84 | 85 | # # # list1[0]= "Z" 86 | # # # string1 = " ".join(list1) 87 | # # # print(string1) 88 | 89 | 90 | # # # Type casting 91 | # # # # name = "Uzair Yasin" 92 | # # # # integer = int(name) 93 | # # # float1 = 2.0 94 | # # # print(type(float1)) 95 | # # # print(float1) 96 | # # # integer2 = int(float1) 97 | # # # print(type(integer2)) 98 | # # # print(integer2) 99 | # # # # print(type(name)) 100 | # # # # print(type(integer)) 101 | 102 | # # # Escape Sequence 103 | # # # name = "Muhammad \"Uzair\" 'Yasin'" 104 | # # # # \n to move to nxt line 105 | # # # # \t to add space equals to one tab or 4 space bars 106 | # # # # \"uzair\" 107 | 108 | # # # print(name) 109 | 110 | # # # strig 5 time convert list , 5 tuple , 5 set 111 | # # # 10 times 112 | # # quote = "\"Quaid-e-Azam\" said : \n\t\t\tWork , Work and Work" 113 | # # print (quote) 114 | 115 | # # String Methods 116 | 117 | # # Lower func = to make all characters in lower case 118 | # # name = "UZAIR YASIN" 119 | # # name2 = name.lower() 120 | # # print(name) 121 | # # print(name2) 122 | 123 | # # Upper func = to make all characters in Upper case 124 | # # name = "Uzair yasin" 125 | # # name2 = name.upper() 126 | # # print(name) 127 | # # print(name2) 128 | 129 | # # Title func = to make the first character of the word in Upper case 130 | # # name = "uzair yasin" 131 | # # name2 = name.title() 132 | # # print(name) 133 | # # print(name2) 134 | 135 | # # swapcase func = to make all Upper case into lower and all the lower case in upper case 136 | # # name = "MUHAMMAD uzair YASIN" 137 | # # name2 = name.swapcase() 138 | # # print(name) 139 | # # print(name2) 140 | 141 | # # # Capitalize func = to make all first character of the first word in Upper case and make all other lower case 142 | # # name = "uzaiR YaSiN" 143 | # # name2 = name.capitalize() 144 | # # print(name) 145 | # # print(name2) 146 | 147 | # # Casefold func = to make all characters in lower case same as lower case func 148 | # # name = "ß" 149 | # # name2 = name.casefold() 150 | # # name3 = name.lower() 151 | # # print(name) 152 | # # print(name2) 153 | # # print(name3) 154 | 155 | # # # center() = to create space if you gave any other 156 | # # name = "Uzair YaSin" 157 | # # name2 = name.center(70, ".") 158 | # # print(name) 159 | # # print(name2) 160 | 161 | # # Endswith() 162 | 163 | # # string = "geeksforgeeks" 164 | # # print(string.endswith("geek")) 165 | 166 | # # text = "geeks for geeks." 167 | 168 | # # result = text.endswith('for geeks.') 169 | # # print (result) 170 | 171 | # # result = text.endswith('geeks.') 172 | # # print (result) 173 | 174 | # # result = text.endswith('for geeks.') 175 | # # print (result) 176 | 177 | # # result = text.endswith('geeks for geeks.') 178 | # # print (result) 179 | 180 | # # text = "geeks for geeks." 181 | 182 | # # result = text.endswith('eks', 12 , 15) 183 | # # print(result) 184 | 185 | 186 | 187 | 188 | # # # expantabs() 189 | 190 | # # string = "i\tlove" 191 | 192 | # # # using expandtabs to insert spacing 193 | # # print (string) 194 | # # print(string.expandtabs(16)) 195 | # # print() 196 | 197 | # # Find() 198 | # # string = " hello world is the first code of every first programmer first" 199 | # # print(string.find("de")) 200 | # # print(string.find("first" ,21)) 201 | # # print(string.find("first" ,41)) 202 | 203 | 204 | 205 | # # Python code for implementation of isprintable() 206 | 207 | # # # checking for printable characters 208 | # # string = "\n \t \r " 209 | # # print(string.isprintable()) 210 | 211 | # # # checking if \n is a printable character 212 | # # string = 'My name is \n Ayush' 213 | # # print(string.isprintable()) 214 | 215 | # # # checking if space is a printable character 216 | # # string = '' 217 | # # print( string.isprintable()) 218 | 219 | # # # checking for whitespace characters 220 | # # string = '' 221 | 222 | # # print(string.isspace()) 223 | 224 | # # string1 = str(list2) 225 | # string1 = "uzair" 226 | # string1 = " _ ".join(string1) 227 | # print(string1) 228 | 229 | 230 | 231 | # # elements in tuples 232 | # tuple1 = ('1', '2', '3','4') 233 | 234 | # # put any character to join 235 | # s = "" 236 | 237 | # # joins elements of list1 by '-' 238 | # # and stores in string s 239 | # s = s.join(tuple1) 240 | # print(type(s)) 241 | # # join use to join a list of 242 | # # strings to a separator s 243 | # print(s) 244 | # utf-8( 245 | 246 | # string1 = "uzair" 247 | # string3 = string1.center(24 , ".") 248 | # string2= string1.rjust(24 , ".") 249 | # print(string2) 250 | # print(string3) 251 | 252 | # string = " geeksforgeeks" 253 | # print(string) 254 | # print(string.lstrip()) 255 | # string = "geeks for geeks" 256 | 257 | # print(string.lstrip("skeeg for")) 258 | 259 | # # string which is to be stripped 260 | # string = "geeks for geeks" 261 | 262 | # # Removes given set of characters from 263 | # # right. 264 | # print(string.lstrip('geeks for')) 265 | 266 | 267 | # text = "hello" 268 | # encoded_text = text.encode("utf-8") 269 | # print(encoded_text) 270 | 271 | 272 | # string = "b follows a, c follows b" 273 | # print(string.partition('follows')) 274 | 275 | # string = "I am happy, I am proud" 276 | # print(string.partition('am')) 277 | 278 | # partition() 279 | 280 | # string = "b follows a, c follows b" 281 | # string1 = string.partition('b') 282 | # for x in string1: 283 | # print(x) 284 | 285 | # string = 'I am happy, I am proud' 286 | # string1 = string.partition('I') 287 | # print(string1) 288 | 289 | # string = "Hello world" 290 | # new_string = string.replace("world", "Good Bye") 291 | # print(f"this is original string : {string}") 292 | # print(f"this is new string : {new_string}") 293 | 294 | # string = "GeeksForGeeks" 295 | # print(string.index("V")) 296 | # print("uzair") 297 | 298 | # text = "geeks for geeks" 299 | 300 | # print(text.zfill(25)) 301 | # print(text.zfill(20)) 302 | # print(text.zfill(10)) 303 | 304 | # original_string = "Hello World" 305 | # encoded_string = original_string.encode(encoding='utf-8', errors='strict') 306 | 307 | 308 | # Joining with string 309 | # string1 = "geeks" 310 | # print(" ".join(string1)) 311 | 312 | 313 | # string = 'geeks' 314 | # print(string) 315 | # print(string.replace("k" , "t")) 316 | 317 | 318 | 319 | # name = "uzair yasin ali ahmed rafay" 320 | # for x,y in enumerate(name): 321 | # print(f"{x} : {y}") 322 | 323 | 324 | # # print(name[2]) 325 | # print(name[0] , end="") 326 | # print(name[1] , end="") 327 | # print(name[2] , end="") 328 | # print(name[3] , end="") 329 | # print(name[4]) 330 | 331 | 332 | # slicing 333 | # print(name[:]) 334 | # name [ start : end - 1 : step ] 335 | 336 | # stepping 337 | # name = "123456789" 338 | # name2 = "iuahixruiubak ugc" 339 | 340 | # print(name[]) 341 | 342 | 343 | # intro = "My name is uzair and my age is 20 and my qualification is Bs " 344 | # # for x,y in enumerate(intro): 345 | # # print(f"{x} : {y}") 346 | 347 | 348 | # print(intro [11 : 16] , intro [31:33] , intro[58 : 60]) 349 | 350 | # numbers = "123456789" 351 | # print(numbers[1::2]) 352 | 353 | 354 | # name = "uzair" 355 | # print(name) 356 | # print(name.center(10, ".")) 357 | # print(name2) 358 | 359 | # name = "mujtba" 360 | 361 | 362 | 363 | 364 | 365 | # name.upper() -------------------------------------------------------------------------------- /Tuple/myhtml: -------------------------------------------------------------------------------- 1 | ! -------------------------------------------------------------------------------- /Tuple/tuple.md: -------------------------------------------------------------------------------- 1 | 2 | # Python Tuples 3 | 4 | The main difference between both is that a Python tuple is immutable, unlike a Python list, which is mutable. 5 | 6 | - We can find items in a tuple since finding any item does not make changes in the tuple. 7 | 8 | ```python 9 | var = ("uzair", "for", "uzair") 10 | print(var) 11 | ``` 12 | 13 | - One cannot add items to a tuple once it is created. 14 | - Tuples cannot be appended or extended. 15 | - We cannot remove items from a tuple once it is created. 16 | 17 | ## Creating Python Tuples 18 | 19 | There are various ways to create a tuple in Python. They are as follows: 20 | 21 | ### Using Round Brackets 22 | 23 | ```python 24 | var: tuple[int | str | float, ...] = (2, 3, 8.5, "uzair", "for", "uzair") 25 | print(type(var)) 26 | print(var) 27 | 28 | values: tuple[int | str, ...] = (1, 2, 4, "uzair", "rafay") 29 | print(values) 30 | ``` 31 | 32 | ### With One Item 33 | 34 | ```python 35 | mytuple = ("uzair",) 36 | print(type(mytuple)) 37 | 38 | # NOT a tuple 39 | mytuple: str = "uzair" 40 | print(type(mytuple)) 41 | ``` 42 | 43 | ### Tuple Constructor 44 | 45 | ```python 46 | tu: tuple[int | str, ...] = (1, 2, 3, 4, 6, "uzair") 47 | print(tu) 48 | list1 = list(tu) 49 | print(list1) 50 | list1.append("ali") 51 | tu1: tuple[int | str, ...] = tuple(list1) 52 | print(tu1) 53 | ``` 54 | 55 | ## Different Operations Related to Tuples 56 | 57 | Below are the different operations related to tuples in Python: 58 | 59 | ### Concatenation 60 | 61 | ```python 62 | a = "uzia" 63 | b = "iugd" 64 | print(a + b) 65 | 66 | # Code for concatenating 2 tuples 67 | tuple1 = (0, 1, 2, 3) 68 | tuple2 = ('python', 'uzair') 69 | 70 | # Concatenating the above two 71 | result = (tuple1 + tuple2) 72 | print(result[0]) 73 | ``` 74 | 75 | ### Nesting 76 | 77 | ```python 78 | # Code for creating nested tuples 79 | tuple1 = (0, 1, 2, 3) 80 | tuple2 = ('python', 'uzair') 81 | 82 | tuple3 = (tuple1, tuple2) 83 | print(tuple3[0]) 84 | # print(tuple3) 85 | ``` 86 | 87 | ### Repetition 88 | 89 | ```python 90 | # Code to create a tuple with repetition 91 | tuple3 = ('python', "uzair") * 5 92 | print(tuple3) 93 | ``` 94 | 95 | ### Slicing 96 | 97 | ```python 98 | tuple1 = (1, 3, 2, 3, 5, 6, 7, 7, 8, 9, 10) 99 | print(tuple1[::3]) 100 | ``` 101 | 102 | ### Deleting 103 | 104 | ```python 105 | # Code for deleting a tuple 106 | tuple3 = (0, 1) 107 | 108 | del tuple3 109 | # print(tuple3) # This will raise an error since tuple3 is deleted 110 | ``` 111 | 112 | ### Finding the Length 113 | 114 | ```python 115 | # Code for printing the length of a tuple 116 | tuple2 = ('python', 'uzair') 117 | print(len(tuple2)) 118 | ``` 119 | 120 | ### Multiple Data Types with Tuples 121 | 122 | ```python 123 | # Tuple with different datatypes 124 | tuple_obj = ("immutable", True, 23) 125 | print(tuple_obj) 126 | ``` 127 | 128 | ### Conversion of Lists to Tuples 129 | 130 | ```python 131 | # Tuple with different datatypes 132 | tuple_obj = ("immutable", True, 23) 133 | print(tuple_obj) 134 | ``` 135 | 136 | ### Tuples in a Loop 137 | 138 | ```python 139 | list1: list = [1, 2, 3, 4, 5] 140 | print(list1) 141 | tuple1: tuple = tuple(list1) 142 | print(tuple1) 143 | ``` 144 | -------------------------------------------------------------------------------- /Tuple/tuple.py: -------------------------------------------------------------------------------- 1 | # the main difference between both is Python tuple is immutable, unlike the Python list which is mutable. 2 | 3 | # We can find items in a tuple since finding any item does not make changes in the tuple. 4 | 5 | # var = ("uzair", "for", "uzair") 6 | # print(var) 7 | 8 | 9 | # One cannot add items to a tuple once it is created. 10 | # Tuples cannot be appended or extended. 11 | # We cannot remove items from a tuple once it is created. 12 | 13 | 14 | 15 | 16 | # Creating Python Tuples 17 | # There are various ways by which you can create a tuple in Python. They are as follows: 18 | 19 | # Using round brackets 20 | 21 | # var : tuple[int | str | float , ...] = ( 2,3 ,8.5,"uzair", "for", "uzair") 22 | # print(type(var)) 23 | # print(var) 24 | 25 | 26 | # values : tuple[int | str , ... ] = (1,2,4,"uzair","rafay") 27 | 28 | # print(values) 29 | 30 | 31 | # With one item 32 | 33 | 34 | 35 | # mytuple = ("uzair",) 36 | # print(type(mytuple)) 37 | 38 | # #NOT a tuple 39 | # mytuple : str = "uzair" 40 | # print(type(mytuple)) 41 | 42 | 43 | # Tuple Constructor 44 | # tu : tuple[int | str ,...] = (1,2,3,4,6 ,"uzair") 45 | # print(tu) 46 | # list1 = list(tu) 47 | # print(list1) 48 | # list1.append("ali") 49 | # tu1 : tuple [int | str , ...] = tuple(list1) 50 | # print(tu1) 51 | 52 | 53 | 54 | 55 | # Different Operations Related to Tuples 56 | # Below are the different operations related to tuples in Python: 57 | 58 | # Concatenation 59 | 60 | # a = "uzia" 61 | # b = "iugd" 62 | # print(a + b) 63 | 64 | # # Code for concatenating 2 tuples 65 | # tuple1 = (0, 1, 2, 3) 66 | # tuple2 = ('python', 'uzair') 67 | 68 | # # Concatenating above two 69 | # result = (tuple1 + tuple2) 70 | # print(result[0]) 71 | 72 | # # Nesting 73 | 74 | 75 | # # Code for creating nested tuples 76 | # tuple1 = (0, 1, 2, 3) 77 | # tuple2 = ('python', 'uzair') 78 | 79 | # tuple3 = (tuple1, tuple2) 80 | # print(tuple3[0]) 81 | # # print(tuple3) 82 | 83 | 84 | # # Repetition 85 | # # Code to create a tuple with repetition 86 | # tuple3 = ('python',"uzair")*5 87 | # print(tuple3) 88 | 89 | # Slicing 90 | # tuple1 = (1,3,2,3,5,6,7,7,8,9,10) 91 | # print(tuple1[::3]) 92 | 93 | # Deleting 94 | # Code for deleting a tuple 95 | 96 | # tuple3 = ( 0, 1) 97 | 98 | # del tuple3 99 | # print(tuple3) 100 | 101 | # Finding the length 102 | # Code for printing the length of a tuple 103 | # tuple2 = ('python', 'uzair') 104 | # print(len(tuple2)) 105 | 106 | # Multiple Data Types with tuples 107 | 108 | 109 | # tuple with different datatypes 110 | # tuple_obj = ("immutable",True,23) 111 | # print(tuple_obj) 112 | 113 | 114 | # Conversion of lists to tuples 115 | 116 | 117 | # tuple with different datatypes 118 | # tuple_obj = ("immutable",True,23) 119 | # print(tuple_obj) 120 | 121 | # Tuples in a Loop 122 | 123 | 124 | # list1 : list = [1,2,3,4,5] 125 | # print(list1) 126 | # tuple1 : tuple = tuple(list1) 127 | # print(tuple1) 128 | 129 | 130 | # li = [] 131 | # a = (2,3,4) 132 | # b = (5,6,7) 133 | # tu = (a + b) 134 | # print(tu) 135 | # print(tu.index(2)) 136 | 137 | # tuple1 = (0, 1, 2, 3) 138 | # tuple2 = ('python', 'uzair') 139 | 140 | # tuple3 = (tuple1, tuple2) 141 | # print(tuple3[0]) 142 | 143 | 144 | # tuple3 = (1,) * 3 145 | # print(tuple3) 146 | 147 | # tu = (1,2,3,4,5,6,7) 148 | # # 149 | # for x in tu: 150 | # print(x) 151 | # def input_(): 152 | # x = input( " number : ").split() 153 | # return x 154 | # y = input_() 155 | # print(int(y)) 156 | 157 | 158 | # def square_list(x,y): 159 | # for items in x: 160 | # h = items*2 161 | # y.appemd 162 | # print(x) 163 | 164 | # li2 = [] 165 | # li = [1,2,3,4] 166 | # # square_list(li,li2) 167 | # a = 5 168 | # b = 3 169 | 170 | # tem = a 171 | # a = b 172 | # b = tem 173 | # import random 174 | # num = random.randint 175 | 176 | 177 | # tu = (1,"yourname" ,2,"edu",3,"rollnum") 178 | 179 | 180 | 181 | # li= [1,2,10,13,2,1,6,9,10] 182 | # user_input = int(input("write which highest number you want : ")) 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | # tu = (1,2,3,4,"uzair" , 5.6) 192 | 193 | # tu. 194 | 195 | 196 | # tu1 = [1] 197 | # tu2 = [5,6,7,8] 198 | # tu3 = [tu1,tu2] 199 | 200 | # # print(tu3) 201 | # tu = (1,2,3,4,"uzair" , 5.6) 202 | 203 | # tu. 204 | 205 | 206 | 207 | 208 | name = input('Enter name:') 209 | edu = input('education:') 210 | roll_no = input('rollno:') 211 | tu = (name, edu, roll_no) 212 | print(tu) 213 | li = list(tu) 214 | print(li) 215 | li.insert(0, 'Ali') 216 | print(li) -------------------------------------------------------------------------------- /Variables in python/variables.md: -------------------------------------------------------------------------------- 1 | # Variables 2 | Python Variable is containers that store values. Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. 3 | In Python, variables are used to store data values that can be accessed and manipulated throughout a program. Python variables don’t require explicit declaration of types, as Python is dynamically typed, meaning it automatically determines the variable’s type based on the assigned value. 4 | 5 | ### Declaring Variables 6 | In Python, you can create a variable simply by assigning a value to a name: 7 | 8 | ```python 9 | x = 10 # integer 10 | name = "Alice" # string 11 | pi = 3.14 # float 12 | is_active = True # boolean 13 | ``` 14 | 15 | ### Rules for Naming Variables 16 | 17 | 1. **Start with a letter or underscore**: Variable names must begin with a letter (a-z, A-Z) or an underscore (_). 18 | 2. **Can contain letters, numbers, and underscores**: After the first character, variables can have letters, numbers, and underscores. 19 | 3. **Case-sensitive**: `name` and `Name` are treated as two different variables. 20 | 4. **Avoid reserved words**: You cannot use Python keywords (like `if`, `for`, `while`, etc.) as variable names. 21 | 22 | ### Examples of Valid Variable Names 23 | 24 | ```python 25 | age = 25 26 | first_name = "John" 27 | _is_active = True 28 | score_1 = 95 29 | ``` 30 | 31 | ### Examples of Invalid Variable Names 32 | 33 | ```python 34 | 1st_place = "Gold" # Starts with a number 35 | first-name = "John" # Contains a hyphen 36 | for = 10 # Uses a reserved keyword 37 | ``` 38 | 39 | ### Assigning Multiple Variables at Once 40 | 41 | You can assign values to multiple variables in a single line: 42 | 43 | ```python 44 | x, y, z = 1, 2, 3 45 | ``` 46 | 47 | Or, assign the same value to multiple variables: 48 | 49 | ```python 50 | a = b = c = 5 51 | ``` 52 | 53 | ### Data Types in Variables 54 | 55 | Python variables can store different types of data. Here are the most common data types: 56 | 57 | 1. **Integers (`int`)**: Whole numbers, like `10`, `-3`, or `1000`. 58 | 2. **Floats (`float`)**: Decimal numbers, like `3.14` or `0.001`. 59 | 3. **Strings (`str`)**: Text enclosed in quotes, like `"Hello"` or `'World'`. 60 | 4. **Booleans (`bool`)**: Logical values `True` or `False`. 61 | 5. **Lists (`list`)**: Ordered collections of items, like `[1, 2, 3]`. 62 | 6. **Dictionaries (`dict`)**: Key-value pairs, like `{"name": "Alice", "age": 25}`. 63 | 7. **Tuples (`tuple`)**: Ordered, immutable collections, like `(1, 2, 3)`. 64 | 8. **Sets (`set`)**: Unordered collections of unique items, like `{1, 2, 3}`. 65 | 66 | ### Example Usage 67 | 68 | ```python 69 | name = "John" 70 | age = 30 71 | height = 5.9 72 | is_student = True 73 | 74 | print(name, "is", age, "years old and", height, "feet tall.") 75 | # Output: John is 30 years old and 5.9 feet tall. 76 | ``` 77 | 78 | ### Variable Type Conversion 79 | 80 | You can convert variable types using functions like `int()`, `float()`, `str()`, etc. 81 | 82 | ```python 83 | x = "10" 84 | y = int(x) # y is now an integer with value 10 85 | 86 | pi = 3.14 87 | str_pi = str(pi) # str_pi is now a string with value "3.14" 88 | ``` 89 | 90 | ### Updating Variable Values 91 | 92 | You can update a variable by reassigning it: 93 | 94 | ```python 95 | count = 10 96 | count = count + 5 # Now count is 15 97 | ``` 98 | 99 | Or, use shorthand operators: 100 | 101 | ```python 102 | count += 5 # Equivalent to count = count + 5 103 | ``` 104 | 105 | ### Variable Scope 106 | 107 | 1. **Local Variables**: Defined inside functions and accessible only within that function. 108 | 2. **Global Variables**: Defined outside functions and accessible anywhere in the code. 109 | 110 | Example of a global and local variable: 111 | 112 | ```python 113 | x = "global" 114 | 115 | def my_function(): 116 | x = "local" 117 | print(x) # Output: local 118 | 119 | my_function() 120 | print(x) # Output: global 121 | ``` 122 | 123 | ### Summary 124 | - Variables store data and don’t require explicit types. 125 | - Follow naming conventions and avoid using reserved keywords. 126 | - Variables can store various data types, which can be converted as needed. 127 | - Use global and local scopes carefully to manage variable access and avoid conflicts -------------------------------------------------------------------------------- /Variables in python/variables.py: -------------------------------------------------------------------------------- 1 | # # name = True 2 | 3 | # # print(type(name)) 4 | 5 | # # mber = 5 6 | # # print(_umber) 7 | 8 | 9 | # name = "uzair" 10 | # # print(name) 11 | # name = "ali" 12 | # print(name) 13 | 14 | # NAME = "rafay" 15 | # NAME = "ahmed" 16 | # print(NAME) 17 | 18 | 19 | # name = "uzair" 20 | # email = "uzair.email" 21 | 22 | 23 | 24 | # someone said 25 | # "ali" is a 'good' boy 26 | # but 27 | # he often make mistakes 28 | 29 | 30 | # print("someone said\n\t\t\"ali\" is a 'good' boy\n\tbut\nhe often make mistakes") 31 | # use variable to store your name and other info and print it in a meaningful way 32 | 33 | 34 | name : str = "ali" 35 | 36 | age : int = 20 37 | 38 | email :str = "ali.email@gmail.com" 39 | 40 | print(f"My name is {name} and my age is {age} and my email is {email}") 41 | 42 | # print(f"My name is {name}, I am {age} years old, and my email is {email}") 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /__pycache__/string.cpython-312.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Uzair-DeVops/Python_Lectures/15182236d24b16008227aa42d0821088fe51513a/__pycache__/string.cpython-312.pyc -------------------------------------------------------------------------------- /practise/hello_world.py: -------------------------------------------------------------------------------- 1 | # # anything which comes inside the inverted commas is called string 2 | # # ctrl + s for save 3 | # # ctrl + / for comments 4 | # # numbers is know as integers in python and you dont use commas during print 5 | # # escape sequence : \n (next line) \t (for space) \ "text \" 6 | # # print('hello \nworld \t Piaic') 7 | # # print(" \"he said\" : something") 8 | 9 | 10 | 11 | 12 | # # print : str 13 | # # print = "piaic" 14 | # # print(print) 15 | 16 | 17 | # # print(4) 18 | 19 | # # # anything you use to store data is called variable 20 | 21 | # # declaration 22 | # your_name : str 23 | # # # initialization 24 | # # your_name = 8 25 | 26 | # # # dont start var name with number 27 | # # # pre define name cant be use as a var 28 | # # # you cant use space 29 | # # # you cant use special character 30 | 31 | # # # make clear var names 32 | # # if you define datatype of any var you have to store same type of data init 33 | 34 | 35 | 36 | 37 | # # f" uzair {var} " syntax 38 | 39 | 40 | # # message : str = " ahmed " 41 | # # print(message.strip()) 42 | 43 | # # url: str = input("Write your URL: ") 44 | 45 | # # if url.startswith('http://'): 46 | # # print(url.removeprefix('http://')) 47 | # # elif url.startswith('https://'): 48 | # # print(url.removeprefix('https://')) 49 | # # else: 50 | # # print("Invalid URL") 51 | 52 | 53 | # # # num : int; num1 :int; num2 : int = 87,64,67 54 | # # # print(num,num1,num2) 55 | # # # Using type hints for individual variables 56 | 57 | # # # num: int 58 | # # # num1: int 59 | # # # num2: int 60 | 61 | # # # # Assigning values to the variables 62 | # # # num, num1, num2 = 87, 64, 67 63 | 64 | # # # print(num, num1, num2) 65 | 66 | 67 | # # # message : str = "Hello Python Crash Course reader!" 68 | # # # print(message) 69 | 70 | # # # name : str = "uzair" 71 | # # # age : int = 20 72 | # # # address : str = "Lahore" 73 | # # # print(f" My name is {name.title()} \n and my age is {age} \n and my is address {address} ") 74 | 75 | # # # name : str = " uzair" 76 | # # # print(name) 77 | # # # print(name.strip()) 78 | 79 | # # # nostarch_url : str = 'https://nostarch.com' 80 | # # # print(nostarch_url) 81 | # # # print(nostarch_url.removeprefix('https://nostarch')) 82 | # # # universe_age : int = 140_000_00000 83 | # # # print(universe_age) 84 | 85 | # # num1 : int 86 | # # num2 : int 87 | # # num3 : int 88 | 89 | # # num1,num2,num3 = 6 ,5 ,8 90 | # # FORMULA_OF_WATER : str = "H20" 91 | 92 | 93 | 94 | 95 | # # import os; 96 | # # base_path = r'C:\Users\LENOVO\OneDrive\Desktop\a' 97 | # # for i in range(1,101): 98 | # # folder_name = f'Folder_{i}' 99 | # # folder_path = os.path.join (base_path,folder_name) 100 | # # os.makedirs(folder_path,exist_ok = True) 101 | 102 | # # print(f'Folder_{i} created') 103 | 104 | 105 | 106 | # # from typing import Union 107 | # # ic :dict[str,Union[str,int,list]] = {"a": 60 ,"b" : "uahf"} 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | # # num = -10 116 | # # num2 = 9 117 | 118 | # # div = num / num2 119 | # # print(div) 120 | # # div2 = abs(int(div)) 121 | # # print(div2) 122 | 123 | # # num = 5 124 | # # num = num % 2 125 | # # print(num) 126 | 127 | 128 | # def add(): 129 | # """Adds two numbers together.""" 130 | # return 131 | # def subtract(x, y): 132 | # """Subtracts two numbers.""" 133 | # return x - y 134 | # def multiply(x, y): 135 | # """Multiplies two numbers.""" 136 | # return x * y 137 | # def divide(x, y): 138 | # """Divides two numbers.""" 139 | # if y == 0: 140 | # return "Division by zero is not allowed." 141 | # return x / y 142 | 143 | # # print(add.__doc__) 144 | 145 | 146 | # # num1 = int(input("write first number : ")) 147 | # # num2 = int(input("write second number :")) 148 | 149 | # # print(f"which function do you want to perform select from one of this [+ , - , * , /]") 150 | # # func = input("give function : ") 151 | # # if func == "+" : 152 | # # print(add(num1,num2)) 153 | # # elif func == "-" : 154 | # # print(subtract(num1,num2)) 155 | # # elif func == "*" : 156 | # # print(multiply(num1,num2)) 157 | # # elif func == "/" : 158 | # # print(divide(num1,num2)) 159 | # # else: 160 | # # print("invalid function") -------------------------------------------------------------------------------- /revision/OOP_rev.py: -------------------------------------------------------------------------------- 1 | # class Dog: 2 | # def __init__(self, name, breed, age): 3 | # self.name = name 4 | # self.breed = breed 5 | # self.age = age 6 | # def eat(self,meal): 7 | # print(f"{self.name} is eating {meal}") 8 | # def bark(self): 9 | # print(f"{self.name} is barking") 10 | # def sleep(self): 11 | # print(f"{self.name} is sleeping") 12 | 13 | 14 | 15 | print("uzair") 16 | 17 | 18 | # # d1 = Dog("tommy" , "German" , 5) 19 | 20 | # # print(d1.name) 21 | 22 | # # print(d1.breed) 23 | 24 | # # print(d1.age) 25 | 26 | # # d1.eat("dog food") 27 | # # d1.bark() 28 | # # d1.sleep() 29 | 30 | # # print() 31 | # # d2 = Dog("Jack" , "Russian" ,6) 32 | 33 | # # d2.eat("cat food") 34 | # # d2.bark() 35 | # # d2.sleep() 36 | # # print(d2.name) 37 | 38 | # # print(d2.breed) 39 | 40 | # # print(d2.age) 41 | 42 | 43 | 44 | # # inheritance 45 | # class GrandFather: 46 | # def guide_g(self): 47 | # print("Father is guiding you") 48 | # def work_g(self): 49 | # print("Father is working") 50 | # class Father: 51 | # def guide(self): 52 | # print("Father is guiding you") 53 | # def work(self): 54 | # print("Father is working") 55 | # class Mother(Father): 56 | # def protect(self): 57 | # print("Mother is protecting you") 58 | # def cook(self): 59 | # print("Mother is cooking") 60 | 61 | # class Child(Mother): 62 | # def play(self): 63 | # print("Child is playing") 64 | # def eat(self): 65 | # print("Child is eating") 66 | 67 | # class Child2(Child,GrandFather): 68 | # def play2(self): 69 | # print("Child is playing") 70 | # def eat2(self): 71 | # print("Child is eating") 72 | # c1 = Child() 73 | 74 | # c1.play() 75 | # c1.eat() 76 | # c1.cook() 77 | # c1.guide() 78 | 79 | 80 | # # m1 = Mother() 81 | 82 | # # m1.protect() 83 | # # m1.cook() 84 | 85 | # # m1.guide() 86 | 87 | 88 | 89 | 90 | # Encapsulation 91 | # class Dog: 92 | # def __init__(self, name, breed, age): 93 | # self.__name = name 94 | # self.__breed = breed 95 | # self.__age = age 96 | # def __eat(self,meal): 97 | # print(f"{self.__name} is eating {meal}") 98 | # def __bark(self): 99 | # print(f"{self.__name} is barking") 100 | # def __sleep(self): 101 | # print(f"{self.__name} is sleeping") 102 | # def admin(self): 103 | # return self.__name,self.__breed,self.__age 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | # d1 = Dog("tommy" , "German" , 5) 112 | # print(d1.admin()) 113 | 114 | # print(d1.__name) 115 | 116 | # print(d1.__breed) 117 | 118 | # print(d1.__age) 119 | 120 | # d1.__eat("dog food") 121 | # d1.__bark() 122 | # d1.__sleep() 123 | 124 | # print() 125 | # d2 = Dog("Jack" , "Russian" ,6) 126 | 127 | # d2.eat("cat food") 128 | # d2.bark() 129 | # d2.sleep() 130 | # print(d2.name) 131 | 132 | # print(d2.breed) 133 | 134 | # print(d2.age) 135 | 136 | 137 | 138 | 139 | # Polymorphism 140 | 141 | 142 | # class Cal: 143 | 144 | # def add(self,a,b,c): 145 | # return a + b + c 146 | # class Cal2(Cal): 147 | # def add(self,a,b): 148 | # return a + b 149 | 150 | 151 | 152 | 153 | # c1=Cal() 154 | # c2 = Cal2() 155 | 156 | 157 | # print(c1.add(1,2,3)) 158 | 159 | # print(c2.add(1,2)) 160 | 161 | 162 | 163 | 164 | # Abstraction 165 | 166 | # from abc import ABC , abstractmethod 167 | # class Animal(ABC): 168 | # @abstractmethod 169 | # def sound(self): 170 | # pass 171 | # def eat(self): 172 | # print("Some generic animal eating") 173 | # def sleep(self): 174 | # print("Some generic animal sleeping") 175 | 176 | # class Dog(Animal): 177 | # def sound(self): 178 | # print("Woof") 179 | # def eat(self): 180 | # print("Dog eating") 181 | 182 | # class Cat(Animal): 183 | # def sound(self): 184 | # print("Meow") 185 | # def eat(self): 186 | # print("Cat eating") 187 | 188 | 189 | 190 | 191 | 192 | 193 | # c1 = Cat() 194 | 195 | # c1.eat() 196 | 197 | # c1.sound() 198 | 199 | 200 | # d1 =Dog() 201 | # d1.sound() 202 | # d1.eat() 203 | -------------------------------------------------------------------------------- /revision/revision.py: -------------------------------------------------------------------------------- 1 | # print('''Someone said : 2 | # # this is good''') 3 | 4 | 5 | # # print("uzair", end=" word ") 6 | # # print("yasin") 7 | 8 | 9 | # # print("uzair" , "yasin","ali","ahmed" , sep=" _ " ) 10 | 11 | 12 | # print("Muhammad \"Uzair\" \'Yasin\'") 13 | # print("\U0001F600") 14 | # # "" 15 | # name = "1" 16 | # print(type(name)) 17 | # print('uzair "ali" ') 18 | # print("uzair yasin 'rafay'") 19 | # print('''uzair "ali" , 'rafay' 20 | # yasin''') 21 | 22 | # # Escape sequences 23 | # print("uzair \tyasin") 24 | 25 | # print("uzair \nyasin") 26 | 27 | # print("yasin\ruzair") 28 | # print("uzair \"yasin\"") 29 | 30 | 31 | # Variables 32 | # it is used to stores values or u can say it a container 33 | # # 34 | # name = "uzair" 35 | 36 | # print(name) 37 | 38 | # Rules no to do 39 | # no number at start 40 | # no spaces 41 | # no hiyhen 42 | # no pre used words 43 | 44 | # rule to do 45 | # meaningful variables 46 | 47 | 48 | # int and float variables 49 | 50 | # num = 5.5 51 | 52 | # type_var = type(num) 53 | 54 | # print(type_var) 55 | 56 | 57 | # input func 58 | 59 | # name = input("write your name : ") 60 | # print("your name is " , name) 61 | 62 | 63 | # age = input("write your age : ") 64 | # print("your age is " , age) 65 | # # print(type(age)) 66 | 67 | 68 | # type casting 69 | 70 | 71 | # # age = int(input("write your age : ")) 72 | # # print("your age is " , age) 73 | # # print(type(age)) 74 | 75 | # #list to dic 76 | 77 | # li = [1,2,3,4] 78 | # dict = {} 79 | # for x,y in enumerate(li): 80 | # dict[x] = y 81 | 82 | 83 | # print(dict) 84 | 85 | # string to list 86 | 87 | # name = "uzair" 88 | # li = [] 89 | # for x in name: 90 | # li.append(x) 91 | 92 | # print(li) 93 | 94 | # # string to dictionary 95 | # name = "uzair" 96 | 97 | # dict = {} 98 | 99 | # for x,y in enumerate(name): 100 | # dict[x] = y 101 | 102 | # print(dict) 103 | 104 | 105 | # list to string 106 | 107 | # li = ["u","z","a","i","r"] 108 | # string_li = "".join(li) 109 | # print(string_li) 110 | 111 | 112 | 113 | # continue 114 | 115 | 116 | # String 117 | 118 | # anything inside a inverted commas is considered as a string 119 | 120 | # name = "my name is uzair and my age is 20" 121 | 122 | # for x,y in enumerate(name): 123 | # print(f"{x} : {y}") 124 | 125 | # syntax [start, end - 1,step] 126 | # print(name[11:16: 2]) 127 | 128 | # reverse string 129 | # print(name[::-1]) 130 | 131 | 132 | # string Func 133 | # name = "my name is uzair and my age is 20" 134 | 135 | # print(name.upper()) 136 | # print(name.lower()) 137 | # print(name.capitalize()) 138 | # print(name.title()) 139 | # print(name.count("a")) 140 | # print(name.find("a")) 141 | # print(name.replace("a", "b")) 142 | # print(name.split(" ")) 143 | # print(name.strip(" ")) 144 | # print(name.startswith("m")) 145 | # print(name.endswith("0")) 146 | # print(name.center(50,"*")) 147 | 148 | 149 | # # If statement 150 | # simple if 151 | # marks = 50 152 | 153 | # # if marks == 50: 154 | # print("Grade A") 155 | 156 | # if else 157 | 158 | 159 | # # if marks == 50: 160 | # print("Grade A") 161 | 162 | # # else: 163 | # print("Grade B") 164 | 165 | 166 | # if elif 167 | # marks = 50 168 | 169 | # if marks == 50: 170 | # print("Grade A") 171 | # elif marks < 50: 172 | # print("Grade b") 173 | # elif marks > 50: 174 | # print("Grade c") 175 | # else: 176 | # print("Grade D") 177 | 178 | 179 | 180 | 181 | # nested if 182 | 183 | # marks = 50 184 | # age = 20 185 | # if marks == 50: 186 | # print("Grade A") 187 | # if age < 18: 188 | # print("You are eligible for driving") 189 | # else: 190 | # print("You are not eligible for driving") 191 | 192 | # else: 193 | # print("Grade B") 194 | 195 | 196 | # print("statement below if") 197 | 198 | 199 | # for loop 200 | 201 | 202 | # name = "uzair" 203 | 204 | # simple loop 205 | # for x in name: 206 | # print(x , end = "") 207 | 208 | # range loop 209 | # for x in range(0,11,2): 210 | # print(x) 211 | 212 | # # nested loop 213 | # for x in range(1,4): 214 | # for y in range(1,4): 215 | # print(x,y) 216 | 217 | 218 | 219 | # while loop 220 | 221 | # score = 0 222 | 223 | # while score < 5: 224 | # print(score) 225 | # score += 1 226 | 227 | 228 | # control statements 229 | 230 | 231 | # score = 0 232 | 233 | # while score < 5: 234 | # print(score) 235 | # score += 1 236 | # if score == 3: 237 | # continue 238 | 239 | 240 | 241 | # for x in range(1,10): 242 | # if x == 6: 243 | # continue 244 | # else: 245 | # print(x) 246 | 247 | # Functions 248 | # def even_odd(x): 249 | # """This function is used to test whether a number is even or odd""" 250 | # if x % 2 == 0: 251 | # print("even") 252 | # else: 253 | # print("odd") 254 | 255 | # for x in range(1,4): 256 | # even_odd(int(input("write any number : " ))) 257 | 258 | # print(enumerate.__doc__) 259 | 260 | # non Pre (multiple types values can b stored) 261 | 262 | # List 263 | # li = [1,4,2,3, "uzair"] 264 | 265 | 266 | 267 | # List Functions 268 | 269 | # li.append(6) 270 | # print(li) 271 | # li.insert(2,7) 272 | # print(li) 273 | # li.remove(4) 274 | # print(li) 275 | # li.pop(2) 276 | # print(li) 277 | # li.sort() 278 | # print(li) 279 | # li.reverse() 280 | # print(li) 281 | # li.clear() 282 | # print(li) 283 | # li.extend([6,7,8]) 284 | # print(li) 285 | # index = li.index(4) 286 | # print(index) 287 | # li = [1,2,3,4 , "uzair",True, 5 288 | # .count(4) 289 | # print(li) 290 | # li = [1,2,3,4 , "uzair",True, 5 291 | # .copy() 292 | # print(li) 293 | # 294 | 295 | 296 | # Tuple 297 | # tu = (1,2,3,4,"string") 298 | 299 | # print(tu[2:4:2]) 300 | 301 | 302 | # Tuple Function 303 | 304 | # tu = (1,2,3,4,"string") 305 | 306 | # tu.count(1) 307 | 308 | # # print(tu.index(4)) 309 | 310 | 311 | 312 | # Dictionary 313 | 314 | # dict = {"a" : "Uzair", "b" : 20 , "c" : "Bscs"} 315 | 316 | 317 | # for x ,y in dict.items(): 318 | # print(f"{x} : {y}") 319 | 320 | 321 | # print(dict["b"]) 322 | 323 | 324 | # dict2 = {} 325 | 326 | 327 | # dict2["a"] = 1 328 | # dict2["b"] = 2 329 | # dict2["c"] = 3 330 | # dict2["d"] = 4 331 | 332 | # print(dict2) 333 | 334 | 335 | # Dict Functios 336 | dict = {"a" : "Uzair", "b" : 20 , "c" : "bscs"} 337 | # print(dict.keys()) 338 | # print(dict.values()) 339 | # print(dict.items()) 340 | # print(dict.get("a")) 341 | # print(dict.get("e")) 342 | # print(dict.setdefault("d","rafay")) 343 | # print(dict) 344 | # print(dict.update({"d":"ali"})) 345 | # print(dict) 346 | # print(dict.pop("a")) 347 | # print(dict) 348 | # print(dict.popitem()) 349 | # print(dict) 350 | 351 | 352 | 353 | # Error Handling 354 | try: 355 | age = int(input("write your age : ")) 356 | print(age) 357 | except Exception as e: 358 | print("error occurred") 359 | else: 360 | print("No error occurred") 361 | finally: 362 | print("done") 363 | 364 | print("uzair") 365 | 366 | 367 | --------------------------------------------------------------------------------