├── Chapter_10th.py ├── Chapter_11th.py ├── Chapter_12th_data_read.py ├── Chapter_12th_os.py ├── Chapter_12th_subprocess.py ├── Chapter_13th.py ├── Chapter_14th.py ├── Chapter_15th.py ├── Chapter_16th_sql.py ├── Chapter_16th_sql_example2.py ├── Chapter_16th_sql_example2_adv.py ├── Chapter_17th_cprofile.py ├── Chapter_17th_debug.py ├── Chapter_17th_unittest.py ├── Chapter_18th.py ├── Chapter_19th.py ├── Chapter_3rd.py ├── Chapter_4th.py ├── Chapter_5th.py ├── Chapter_6th.py ├── Chapter_7th.py ├── Chapter_8th.py ├── Chapter_9th_Inheritance_Fruit_example.py ├── Chapter_9th_class.py ├── Chapter_9th_inheritance.py ├── README.md ├── Score.csv ├── books.xml ├── demofile.txt ├── employee_birthday.csv ├── employee_birthday.txt ├── employees.xml └── temperature.csv /Chapter_10th.py: -------------------------------------------------------------------------------- 1 | # Example 1 2 | # make sure you have demofile.txt file in your working directory 3 | f = open("demofile.txt", "r") 4 | print(f.read()) 5 | 6 | # Output 7 | # C:\Users\My Name>python demo_file_open.py 8 | # Hello! Welcome to demofile.txt 9 | # This file is for testing purposes. 10 | # Good Luck! 11 | 12 | # Example 2 13 | f = open("demofile.txt", "r") 14 | print(f.read(5)) 15 | 16 | # Output 17 | # C:\Users\My Name>python demo_file_open2.py 18 | # Hello 19 | 20 | # Example 3 21 | f = open("demofile.txt", "r") 22 | print(f.readline()) 23 | 24 | # Output 25 | # C:\Users\My Name>python demo_file_readline.py 26 | # Hello! Welcome to demofile.txt 27 | 28 | 29 | # Example 4 30 | f = open("demofile.txt", "r") 31 | print(f.readline()) 32 | print(f.readline()) 33 | 34 | # Output 35 | # C:\Users\My Name>python demo_file_readline2.py 36 | # Hello! Welcome to demofile.txt 37 | # This file is for testing purposes. 38 | 39 | 40 | # Example 5 41 | f = open("demofile.txt", "r") 42 | for x in f: 43 | print(x) 44 | 45 | 46 | # Output 47 | # C:\Users\My Name>python demo_file_readline3.py 48 | # Hello! Welcome to demofile.txt 49 | # This file is for testing purposes. 50 | # Good Luck! 51 | 52 | # Example 6 53 | 54 | f = open("demofile.txt", "r") 55 | print(f.readline()) 56 | f.close() 57 | 58 | # Output 59 | # C:\Users\My Name>python demo_file_close.py 60 | # Hello! Welcome to demofile.txt 61 | 62 | 63 | # Example 7 64 | f = open("demofile2.txt", "a") 65 | f.write("Now the file has more content!") 66 | f.close() 67 | 68 | # open and read the file after the appending: 69 | f = open("demofile2.txt", "r") 70 | print(f.read()) 71 | 72 | 73 | # Output 74 | # C:\Users\My Name>python demo_file_append.py 75 | # Hello! Welcome to demofile2.txt 76 | # This file is for testing purposes. 77 | # Good Luck!Now the file has more content! 78 | 79 | 80 | # Example 8 81 | f = open("demofile3.txt", "w") 82 | f.write(" I have deleted the content!") 83 | f.close() 84 | 85 | #open and read the file after the appending: 86 | f = open("demofile3.txt", "r") 87 | print(f.read()) 88 | 89 | 90 | # Output 91 | # C:\Users\My Name>python demo_file_write.py 92 | # I have deleted the content! 93 | 94 | 95 | # Example 9 96 | import os 97 | os.remove("demofile.txt") 98 | 99 | # Example 10 100 | import os 101 | if os.path.exists("demofile.txt"): 102 | os.remove("demofile.txt") 103 | else: 104 | print("The file does not exist") 105 | 106 | 107 | # Example 11 108 | # Create myfolder in working directory before executing code below. 109 | import os 110 | os.rmdir("myfolder") 111 | -------------------------------------------------------------------------------- /Chapter_11th.py: -------------------------------------------------------------------------------- 1 | # Example 1 2 | import csv 3 | with open('employee_birthday.txt', 'w', newline='') as file: 4 | writer = csv.writer(file) 5 | writer.writerow(["name", "department", "birthday month"]) 6 | writer.writerow(["John Smith", "Accounting","November"]) 7 | writer.writerow(["Erica Meyers","IT", "March"]) 8 | writer.writerow(["Jennifer maik","Math","June"]) 9 | 10 | 11 | # Example 2 12 | import csv 13 | with open('employee_birthday.txt') as csv_file: 14 | csv_reader = csv.reader(csv_file, delimiter=',') 15 | line_count = 0 16 | for row in csv_reader: 17 | if line_count == 0: 18 | print(f'Column names are {", ".join(row)}') 19 | line_count += 1 20 | else: 21 | print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.') 22 | line_count += 1 23 | print(f'Processed {line_count} lines.\n\n\n') 24 | 25 | 26 | # Output 27 | # Column names are name, department, birthday month 28 | # John Smith works in the Accounting department, and was born in November. 29 | # Erica Meyers works in the IT department, and was born in March. 30 | # Jennifer maik works in the Math department, and was born in June. 31 | # Processed 4 lines. 32 | 33 | 34 | # Example 3 35 | from lxml import etree 36 | #The etree object parses the entire lxml file into a tree structure, with each tag as a branch, and nested tags become its children or branches. 37 | 38 | def parseBookXML(xmlFile): 39 | with open(xmlFile) as fobj: 40 | xml = fobj.read() 41 | root = etree.fromstring(xml) # read string type file text and convert into XML format using etree. 42 | book_dict = {} 43 | books = [] 44 | for book in root.getchildren(): # The .getchildren() accesses the sub-tags within a tree. 45 | for elem in book.getchildren(): #The method called on book gives access to the contents of the book (author, genre, etc) 46 | if elem.text: # elem.text accesses the text inside each of the tags whereas, tag gives the tag names such as author, price, etc. 47 | text = elem.text 48 | else: 49 | text = '' 50 | if elem.tag == 'author': 51 | last_name, first_name = text.split(',') 52 | print(elem.tag + ':', first_name, last_name) 53 | else: 54 | print(elem.tag + ": " + text) 55 | book_dict[elem.tag] = text 56 | if book.tag == "book": 57 | books.append(book_dict) 58 | book_dict = {} 59 | return books 60 | 61 | my_books = parseBookXML("books.xml") 62 | # The entire information is collected and stored in a variable my_books. 63 | my_books # print all data 64 | 65 | -------------------------------------------------------------------------------- /Chapter_12th_data_read.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Aug 6 15:54:08 2020 4 | 5 | @author: sana.rasheed 6 | """ 7 | 8 | 9 | # Example 10 | import csv 11 | file = "Score.csv" 12 | reader = csv.reader(open(file, 'r')) 13 | for row in reader: 14 | print(row) 15 | -------------------------------------------------------------------------------- /Chapter_12th_os.py: -------------------------------------------------------------------------------- 1 | # Example 1 2 | # Before executing this example, create tempdir folder in C:// directory 3 | import os 4 | os.chdir("C:\\tempdir") 5 | 6 | 7 | # Example 2 8 | os.getcwd() # get Current Working Directory 9 | # output: 'C:\\tempdir' 10 | 11 | 12 | # Example 3 13 | os.chdir("C:\\tempdir") 14 | os.getcwd() 15 | # output: 'C:\\tempdir' 16 | os.chdir("..") 17 | os.getcwd() 18 | # output: 'C:\\' 19 | 20 | 21 | # Example 4 22 | os.chdir("tempdir") 23 | os.getcwd() 24 | # output: 'C:\\tempdir' 25 | 26 | os.rmdir("C:\\tempdir") 27 | # Output 28 | # PermissionError: [WinError 32] The process cannot access the file 29 | # because it is being used by another process: 'C:\\tempdir' 30 | 31 | 32 | 33 | # Example 34 | # try any one from below in terminal. 35 | os.listdir("C:\python37") # if you have this folder in C drive 36 | # os.listdir("C:\Windows") 37 | 38 | # Output of python37 folder: 39 | # ['DLLs', 'Doc', 'fantasy-1.py', 'fantasy.db', 'fantasy.py', 'frame.py', 'gridexample.py', 40 | # 'include', 'Lib', 'libs', 'LICENSE.txt', 'listbox.py', 'NEWS.txt', 'place.py', 'players.db', 41 | # ,'tcl', 'test.py','© 'python3.dll', 'python36.dll', 'pythonw.exe', 'sclst.py', 'Script, 'python.exe', 42 | # 'Tools', 'tooltip.py', 'vcruntime140.dll', 'virat.jpg', 'virat.py'] 43 | -------------------------------------------------------------------------------- /Chapter_12th_subprocess.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Aug 7 12:54:29 2020 4 | 5 | @author: sana.rasheed 6 | """ 7 | 8 | # Example 1 9 | import subprocess 10 | # run the command 11 | subprocess.call(['dir'], shell= True) # returns the files in the current directory 12 | 13 | # Output 14 | # 0 15 | 16 | 17 | # Exammple 2 18 | import subprocess # import module 19 | # run the command 20 | output =subprocess.check_output(['dir'], shell= True) # returns the files in the current directory 21 | print(output) 22 | 23 | # Output 24 | # b' Volume in drive E is New Volume\r\n Volume Serial Number is 100E-A8F7\r\n\r\n Directory of E:\\task\\Python task\\Python\\Python\r\n\r\n08/07/2020 03:57 pm .\r\n08/07/2020 03:57 pm ..\r\n06/07/2020 05:10 pm 611 2. testing.py\r\n07/07/2020 07:20 am 345 3. debugging.py\r\n11/06/2020 03:04 pm 1,849 4.10.numpy.py\r\n11/06/2020 03:04 pm 833 4.10.numpy_linear_algebra.py\r\n11/06/2020 03:04 pm 906 4.4.lxml.py\r\n08/07/2020 03:57 pm 1,311 4.6.configparser.py\r\n07/07/2020 09:13 pm 682 4.8.Threading.py\r\n11/06/2020 03:04 pm 252 4.9.temperature.csv\r\n 25 | 26 | 27 | # Example 3 28 | # data_read.py file is available in repository. Make sure it's available in current working directory 29 | import subprocess 30 | # it will read data and store in theproc variable 31 | theproc = subprocess.check_output("python chapter_12th_data_read.py", shell = True) 32 | print(theproc) # to see the output of theproc 33 | -------------------------------------------------------------------------------- /Chapter_13th.py: -------------------------------------------------------------------------------- 1 | # import libraries 2 | import logging 3 | import time 4 | import datetime 5 | import threading 6 | 7 | def get_cubic(num): 8 | print(datetime.datetime.now()) 9 | print("Cube: {}".format(num * num * num)) 10 | 11 | def get_inverse(num): 12 | print(datetime.datetime.now()) 13 | print("Inverted: {}".format(1 / num)) 14 | 15 | # Example 1 16 | # main execution 17 | if __name__ == "__main__": 18 | # creating thread 19 | t1 = threading.Thread(target=get_cubic, args=(10,)) 20 | t2 = threading.Thread(target=get_inverse, args=(10,)) 21 | # Starting the threads 22 | t1.start() 23 | t2.start() 24 | # waiting for each to finish 25 | t1.join() 26 | t2.join() 27 | # both threads completely executed 28 | print("Done!") 29 | 30 | # Output 31 | # Cube: 1000 32 | # Inverted: 0.1 33 | # Done! 34 | 35 | 36 | # Example 2 37 | if __name__ == "__main__": 38 | # creating thread 39 | t1 = threading.Thread(target=get_cubic, args=(10,)) 40 | t2 = threading.Thread(target=get_inverse, args=('10',)) 41 | # Starting the threads 42 | t1.start() 43 | t2.start() 44 | # waiting for each to finish 45 | t1.join() 46 | t2.join() 47 | # both threads completely executed 48 | print("Done!") 49 | 50 | 51 | # Output 52 | 53 | # Cube: 1000 54 | # Done! 55 | # Exception in thread Thread-16: 56 | # Traceback (most recent call last): 57 | # File "C:\Users\anaconda3\lib\threading.py", line 926, in _bootstrap_inner 58 | # self.run() 59 | # File "C:\Users\anaconda3\lib\threading.py", line 870, in run 60 | # self._target(*self._args, **self._kwargs) 61 | # File "E:\Python task\Python\4.8.Threading.py", line 12, in get_inverse 62 | # print("Inverted: {}".format(1 / num)) 63 | # TypeError: unsupported operand type(s) for /: 'int' and 'str' 64 | -------------------------------------------------------------------------------- /Chapter_14th.py: -------------------------------------------------------------------------------- 1 | # Example 1 2 | import requests 3 | x = requests.get("https://github.com/") 4 | 5 | print(x) 6 | print(x.status_code) 7 | 8 | # Output 9 | # 10 | # 200 11 | 12 | 13 | 14 | # Example 2 15 | import requests 16 | res = requests.get('https://api.github.com/users/sana-rasheed') 17 | print(res) 18 | print(res.status_code) 19 | data = res.json() 20 | print("Followering: ", data['following']) 21 | print("Followers: ", data['followers']) 22 | 23 | # Output 24 | # 25 | # 200 26 | # Followering: 1 27 | # Followers: 30 28 | 29 | 30 | 31 | # Example 3 32 | import requests 33 | url='https://official-joke-api.appspot.com/jokes/programming/random' 34 | res = requests.get(url) # get API end-point response 35 | data = res.json()[0] # convert response text into json format 36 | for key in data: 37 | print(key,":",data[key]) 38 | 39 | # Output 40 | # id : 74 41 | # type : programming 42 | # setup : Why do C# and Java developers keep breaking their keyboards? 43 | # punchline : Because they use a strongly typed language. 44 | 45 | 46 | 47 | # Example 4 48 | import requests 49 | myobj = [('Ali', 56),('Ahmed', 87),('Amna', 76)] 50 | 51 | r = requests.post("http://httpbin.org/post", data=myobj) # post data to API 52 | r # To show API response status 53 | data = r.json() # convert response text into json format 54 | d = data['form'] # Posted data available under form tag 55 | print(d) 56 | 57 | # Output 58 | # {'Ahmed': '87', 'Ali': '56', 'Amna': '76'} 59 | -------------------------------------------------------------------------------- /Chapter_15th.py: -------------------------------------------------------------------------------- 1 | 2 | # Example 1 3 | class Greeter: 4 | def _init_(self, name): 5 | self.name= _name 6 | def say_hello(self): 7 | print('hello {}!'.format(self.name)) 8 | def say_goodbye(self): 9 | print('goodbye {}!'.format(self.name)) 10 | # End of class 11 | 12 | my_greeter= Greeter() 13 | print('get id,type and available methods and attributes for Greeter class:') 14 | print(id(my_greeter)) 15 | print(type(my_greeter)) 16 | print(dir(my_greeter)) 17 | 18 | # Output 19 | # get id,type and available methods and attributes for Greeter class: 2387805337096 20 | # 21 | # ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_init_', 'say_goodbye', 'say_hello'] 22 | 23 | 24 | 25 | # Example 2 26 | my_var= 'This is a variable' 27 | print('\ncheck id,type and methods for a variable containing string value:') 28 | print(id(my_var)) 29 | print(type(my_var)) 30 | print(dir(my_var)) 31 | 32 | # Output 33 | # check id,type and methods for a variable containing string value: 2387807488400 34 | # 35 | # ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] 36 | 37 | 38 | 39 | # Example 3 40 | my_num=453.324 41 | print('\ncheck id,type and methods for a variable containing numeric value:') 42 | print(id(my_num)) 43 | print(type(my_num)) 44 | print(dir(my_num)) 45 | 46 | # Output 47 | # check id,type and methods for a variable containing numeric value: 2387807736720 48 | # 49 | # ['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__round__', '__rpow__', '__rsub__', '__rtruediv__', '__set_format__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real'] 50 | 51 | 52 | 53 | # Example 4 54 | import inspect # imported inspect module 55 | import os 56 | testvar= 'Hello' 57 | class Greeter: 58 | def _init_(self,name): 59 | self.name= name 60 | def say_hello(self): 61 | print('Hello {}!'.format(self.name)) 62 | def say_goodbye(self): 63 | print('Goodbye {}!'.format(self.name)) 64 | # End of class 65 | 66 | my_greeter= Greeter() # class object 67 | 68 | #lambda function 69 | exp = lambda x:x*x 70 | 71 | # normal python user-definedfunction/method 72 | def show_name_age(first_name:str,last_name:str,age:int): 73 | print('{} {} is {} years old'.format(first_name,last_name,age)) 74 | 75 | inspect.getmembers(my_greeter) # returns members of the class my_greeter 76 | # print( inspect.getmembers(my_greeter) ) 77 | 78 | # introspection of ismodule 79 | print('\n Checking if os is a module:', inspect.ismodule(os)) 80 | print('\n Checking if testvar is a module:', inspect.ismodule(testvar)) 81 | print('\n Inspect ismethod vs. isfunction comparison'.upper()) 82 | 83 | # introspection of is method 84 | print('\n Ismethod:\n show_name_age:', inspect.ismethod(show_name_age), 85 | 'exp:', inspect.ismethod(exp), 86 | 'Greeter.say_hello:', inspect.ismethod(my_greeter.say_hello) ) 87 | 88 | # introspection of is function 89 | print('\n Isfunction:\n show_name_age:',inspect.isfunction(show_name_age), 90 | 'exp:', inspect.isfunction(exp), 91 | 'Greeter.say_hello:', inspect.isfunction(my_greeter.say_hello) ) 92 | 93 | 94 | # Output 95 | # Checking if os is a module: True 96 | # Checking if testvar is a module: False 97 | # INSPECT ISMETHOD VS. ISFUNCTION COMPARISON 98 | # Ismethod: 99 | # show_name_age: False exp: False Greeter.say_hello: True 100 | # Isfunction: 101 | # show_name_age: True exp: True Greeter.say_hello: False 102 | 103 | 104 | 105 | 106 | # Example 5 107 | import inspect 108 | # normal python user-defined function/method 109 | def show_name_age(first_name:str,last_name:str,age:int): 110 | print('{} {} is {} years old'.format(first_name,last_name,age)) 111 | 112 | #signature of a method:accesses parameters,their inferred or fixed data types. 113 | sig= inspect.signature(show_name_age) 114 | print (sig.parameters) 115 | 116 | # Output 117 | # OrderedDict([('first_name', ), ('last_name', ), 118 | # ('age', )]) 119 | 120 | 121 | # Example 6 122 | print(sig.parameters['first_name'].annotation) 123 | 124 | # Output 125 | # 126 | 127 | 128 | ### Decorator 129 | print("\n\nDecorator Example") 130 | # Example 7 131 | def extract_function_name(func): 132 | def internal_method(*args, **kwargs): 133 | print('The method called is:', func.__name__) 134 | returned_value = func(*args, **kwargs) 135 | print('The method execution is complete.') 136 | return returned_value 137 | return internal_method 138 | 139 | # adding decorator to the function 140 | @extract_function_name 141 | def sum_two_numbers(a, b): 142 | print("This is called inside the function") 143 | return a + b 144 | 145 | @extract_function_name 146 | def product_two_numbers(a, b): 147 | print("This is called inside the function") 148 | return a*b 149 | 150 | a, b = 3, 4 151 | # getting the value through return of the function 152 | print('Sum function value:', sum_two_numbers(a, b)) 153 | print('Product function value', product_two_numbers(a, b)) 154 | 155 | # Output 156 | # The method called is: sum_two_numbers 157 | # This is called inside the function 158 | # The method execution is complete. 159 | # Sum function value: 7 160 | # The method called is: product_two_numbers 161 | # This is called inside the function 162 | # The method execution is complete. 163 | # Product function value 12 164 | 165 | 166 | 167 | -------------------------------------------------------------------------------- /Chapter_16th_sql.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Aug 7 13:15:35 2020 4 | 5 | @author: sana.rasheed 6 | """ 7 | 8 | ### Chapter 16th - SQLite 9 | 10 | # Example 1 11 | # Create Database 12 | import sqlite3 13 | try: 14 | sqliteConnection = sqlite3.connect('SQLite_Python.db') 15 | cursor = sqliteConnection.cursor() 16 | print("Database created and Successfully Connected to SQLite") 17 | sqlite_select_Query = "select sqlite_version();" 18 | cursor.execute(sqlite_select_Query) 19 | record = cursor.fetchall() 20 | print("SQLite Database Version is: ", record) 21 | cursor.close() 22 | except sqlite3.Error as error: 23 | print("Error while connecting to sqlite", error) 24 | 25 | finally: 26 | if (sqliteConnection): 27 | sqliteConnection.close() 28 | print("The SQLite connection is closed") 29 | 30 | # Outputput 31 | # Database created and Successfully Connected to SQLite 32 | # SQLite Database Version is: [('3.31.1',)] 33 | # The SQLite connection is closed 34 | 35 | 36 | # ========================================================= 37 | # Connect to Databse, Create Table and Close connection with Database. 38 | import sqlite3 39 | try: 40 | sqliteConnection = sqlite3.connect('SQLite_Python.db') 41 | sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers ( 42 | id INTEGER PRIMARY KEY, 43 | name TEXT NOT NULL, 44 | email text NOT NULL UNIQUE, 45 | joining_date datetime, 46 | salary REAL NOT NULL);''' 47 | cursor = sqliteConnection.cursor() 48 | print("Successfully Connected to SQLite") 49 | cursor.execute(sqlite_create_table_query) 50 | sqliteConnection.commit() 51 | print("SQLite table created") 52 | cursor.close() 53 | except sqlite3.Error as error: 54 | print("Error while creating a sqlite table", error) 55 | finally: 56 | if (sqliteConnection): 57 | sqliteConnection.close() 58 | print("sqlite connection is closed") 59 | 60 | # Output 61 | # Successfully Connected to SQLite 62 | # SQLite table created 63 | # sqlite connection is closed 64 | 65 | 66 | # ========================================================= 67 | # Connect to Database 68 | import sqlite3 69 | conn = sqlite3.connect('test.db') 70 | print ( "Opened database successfully") 71 | 72 | 73 | # ========================================================= 74 | # Connect to Database and Execute Query to Create COMPANY Table 75 | import sqlite3 76 | conn = sqlite3.connect('test.db') 77 | print ("Opened database successfully") 78 | 79 | conn.execute('''CREATE TABLE COMPANY 80 | (ID INT PRIMARY KEY NOT NULL, 81 | NAME TEXT NOT NULL, 82 | AGE INT NOT NULL, 83 | ADDRESS CHAR(50), 84 | SALARY REAL);''') 85 | print( "Table created successfully") 86 | conn.close() 87 | 88 | # Output 89 | # Opened database successfully 90 | # Table created successfully 91 | 92 | 93 | # ========================================================= 94 | # Connect to Database and INSERT DATA into COMPANY Tabele 95 | import sqlite3 96 | conn = sqlite3.connect('test.db') 97 | print ("Opened database successfully") 98 | conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \ 99 | VALUES (1, 'Paul', 32, 'California', 20000.00 )"); 100 | conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \ 101 | VALUES (2, 'Allen', 25, 'Texas', 15000.00 )"); 102 | conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \ 103 | VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )"); 104 | conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \ 105 | VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )"); 106 | conn.commit() 107 | print ("Records created successfully") 108 | conn.close() 109 | 110 | # Output 111 | # Opened database successfully 112 | # Records created successfully 113 | 114 | # NOTE: delete test.db if table already exists error occur, after executing conn.close() 115 | # Alternatively, create new table and insert data 116 | 117 | # ===================================================================== 118 | 119 | import sqlite3 120 | conn = sqlite3.connect('test.db') 121 | print ("Opened database successfully") 122 | cursor = conn.execute("SELECT id, name, address, salary from COMPANY") 123 | for row in cursor: 124 | print ("ID = ", row[0]) 125 | print ("NAME = ", row[1]) 126 | print ("ADDRESS = ", row[2]) 127 | print ("SALARY = ", row[3], "\n") 128 | print ("Operation done successfully") 129 | conn.close() 130 | 131 | # Output 132 | 133 | # Opened database successfully 134 | # ID = 1 135 | # NAME = Paul 136 | # ADDRESS = California 137 | # SALARY = 20000.0 138 | # ID = 2 139 | # NAME = Allen 140 | # ADDRESS = Texas 141 | # SALARY = 15000.0 142 | # ID = 3 143 | # NAME = Teddy 144 | # ADDRESS = Norway 145 | # SALARY = 20000.0 146 | # ID = 4 147 | # NAME = Mark 148 | # ADDRESS = Rich-Mond 149 | # SALARY = 65000.0 150 | # Operation done successfully 151 | 152 | 153 | # ================================================ 154 | 155 | import sqlite3 156 | conn = sqlite3.connect('test.db') 157 | print ("Opened database successfully") 158 | conn.execute("UPDATE COMPANY set SALARY = 25000.00 where ID = 1") 159 | conn.commit() 160 | print ("Total number of rows updated :", conn.total_changes) 161 | cursor = conn.execute("SELECT id, name, address, salary from COMPANY") 162 | for row in cursor: 163 | print("ID = ", row[0]) 164 | print ("NAME = ", row[1]) 165 | print ("ADDRESS = ", row[2]) 166 | print ("SALARY = ", row[3], "\n") 167 | print ("Operation done successfully") 168 | conn.close() 169 | 170 | # Output 171 | 172 | # Opened database successfully 173 | # Total number of rows updated : 1 174 | # ID = 1 175 | # NAME = Paul 176 | # ADDRESS = California 177 | # SALARY = 25000.0 178 | # ID = 2 179 | # NAME = Allen 180 | # ADDRESS = Texas 181 | # SALARY = 15000.0 182 | # ID = 3 183 | # NAME = Teddy 184 | # ADDRESS = Norway 185 | # SALARY = 20000.0 186 | # ID = 4 187 | # NAME = Mark 188 | # ADDRESS = Rich-Mond 189 | # SALARY = 65000.0 190 | # Operation done successfully 191 | 192 | # ====================================================================== 193 | 194 | import sqlite3 195 | conn = sqlite3.connect('test.db') 196 | print ("Opened database successfully") 197 | conn.execute("DELETE from COMPANY where ID = 2;") 198 | conn.commit() 199 | print ("Total number of rows deleted :", conn.total_changes) 200 | cursor = conn.execute("SELECT id, name, address, salary from COMPANY") 201 | for row in cursor: 202 | print ("ID = ", row[0]) 203 | print ("NAME = ", row[1]) 204 | print( "ADDRESS = ", row[2]) 205 | print( "SALARY = ", row[3], "\n") 206 | print ("Operation done successfully") 207 | conn.close() 208 | 209 | # Output 210 | 211 | # Opened database successfully 212 | # Total number of rows deleted : 1 213 | # ID = 1 214 | # NAME = Paul 215 | # ADDRESS = California 216 | # SALARY = 20000.0 217 | # ID = 3 218 | # NAME = Teddy 219 | # ADDRESS = Norway 220 | # SALARY = 20000.0 221 | # ID = 4 222 | # NAME = Mark 223 | # ADDRESS = Rich-Mond 224 | # SALARY = 65000.0 225 | # Operation done successfully 226 | -------------------------------------------------------------------------------- /Chapter_16th_sql_example2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Aug 7 14:25:45 2020 4 | 5 | @author: sana.rasheed 6 | """ 7 | 8 | ### Chapter 16th - SQLite 9 | 10 | # Example 2 11 | # Functions implementated for quick DB connection and Table creations 12 | import sqlite3 13 | from sqlite3 import Error 14 | 15 | # Function to open DB connection 16 | def create_connection(db_file): 17 | """ create a database connection to the SQLite database specified by db_file 18 | :param db_file: database file 19 | :return: Connection object or None 20 | """ 21 | conn = None 22 | try: 23 | conn = sqlite3.connect(db_file) 24 | print("The SQLite connection is connected") 25 | return conn 26 | except Error as e: 27 | print(e) 28 | return conn 29 | 30 | # Function to close DB connection 31 | def close_connection(conn): 32 | """ close database connection to the SQLite database specified by db_file 33 | :param db_file: database file 34 | """ 35 | if (conn): 36 | conn.close() 37 | print("The SQLite connection is closed") 38 | 39 | 40 | # Function to create new table in DB 41 | def create_table_in_db(conn, create_table_sql): 42 | """ create a table from the create_table_sql statement 43 | :param conn: Connection object 44 | :param create_table_sql: a CREATE TABLE statement 45 | :return: 46 | """ 47 | try: 48 | c = conn.cursor() 49 | c.execute(create_table_sql) 50 | except Error as e: 51 | print(e) 52 | 53 | # Create STUDENT Table 54 | def create_table(): 55 | database = r"C:\\tempdir\database.db" 56 | sql_create_projects_table = """ CREATE TABLE IF NOT EXISTS STUDENTS ( 57 | id integer PRIMARY KEY, 58 | name text NOT NULL, 59 | gpa integer, 60 | admission_date text 61 | ); """ 62 | # create a database connection 63 | conn = create_connection(database) 64 | 65 | # create tables 66 | if conn is not None: 67 | # create projects table 68 | create_table_in_db(conn, sql_create_projects_table) 69 | else: 70 | print("Error! cannot create the database connection.") 71 | close_connection(conn) 72 | 73 | 74 | # main execution to create table 75 | create_table() 76 | 77 | # ====================================================== 78 | 79 | # Add student data in table 80 | def add_student(conn, student): 81 | """ 82 | Create a new student entry into the student table 83 | :param conn: 84 | :param student: 85 | :return: student id 86 | """ 87 | sql = ''' INSERT INTO STUDENTS(name,gpa,admission_date) 88 | VALUES(?,?,?) ''' 89 | cur = conn.cursor() 90 | cur.execute(sql, student) 91 | return cur.lastrowid 92 | 93 | # main function to add student in table 94 | def main_function(): 95 | database =r"C:\\tempdir\database.db" 96 | 97 | # create a database connection 98 | conn = create_connection(database) 99 | with conn: 100 | # add a new student 101 | student = ('Alan', 1.9, '2019-1-30'); 102 | student_id = add_student(conn, student) 103 | 104 | print('The Student ID:', student_id) 105 | close_connection(conn) 106 | 107 | 108 | # Execute main funtion to add student 'Alan' in table 109 | main_function() 110 | 111 | 112 | # ============================================================== 113 | ### READ TABLE 114 | database = r"C:\\tempdir\database.db" 115 | #create a database connection 116 | conn = create_connection(database) 117 | try: 118 | cursor = conn.cursor() 119 | table_name = "STUDENTS" 120 | sql_string = "SELECT * from " + table_name 121 | sqlite_select_query = sql_string 122 | 123 | cursor.execute(sqlite_select_query) 124 | records = cursor.fetchall() 125 | print("Total rows are: ", len(records)) 126 | cursor.close() 127 | except sqlite3.Error as error: 128 | print("Failed to read data from sqlite table", error) 129 | finally: 130 | close_connection(conn) 131 | print(records) 132 | 133 | -------------------------------------------------------------------------------- /Chapter_16th_sql_example2_adv.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Aug 7 14:38:33 2020 4 | 5 | @author: sana.rasheed 6 | """ 7 | 8 | ### Chapter 16th - SQLite 9 | ''' 10 | Author NOTE: 11 | Few functions have been improved and not covered in book. 12 | You can test it for your own learning. 13 | ''' 14 | # Example 3 - Advance implementation of Example 2 15 | # Functions implementated for quick DB connection and Table creations 16 | import sqlite3 17 | from sqlite3 import Error 18 | 19 | # Function to open DB connection 20 | def create_connection(db_file): 21 | """ create a database connection to the SQLite database specified by db_file 22 | :param db_file: database file 23 | :return: Connection object or None 24 | """ 25 | conn = None 26 | try: 27 | conn = sqlite3.connect(db_file) 28 | print("The SQLite connection is connected") 29 | return conn 30 | except Error as e: 31 | print(e) 32 | return conn 33 | 34 | # Function to close DB connection 35 | def close_connection(conn): 36 | """ close database connection to the SQLite database specified by db_file 37 | :param db_file: database file 38 | """ 39 | if (conn): 40 | conn.close() 41 | print("The SQLite connection is closed") 42 | 43 | 44 | # Function to create new table in DB 45 | def create_table_in_db(conn, create_table_sql): 46 | """ create a table from the create_table_sql statement 47 | :param conn: Connection object 48 | :param create_table_sql: a CREATE TABLE statement 49 | :return: 50 | """ 51 | try: 52 | c = conn.cursor() 53 | c.execute(create_table_sql) 54 | except Error as e: 55 | print(e) 56 | 57 | # Create STUDENT Table - MODIFIED 58 | def create_table(database): 59 | sql_create_projects_table = """ CREATE TABLE IF NOT EXISTS STUDENTS ( 60 | id integer PRIMARY KEY, 61 | name text NOT NULL, 62 | gpa integer, 63 | admission_date text 64 | ); """ 65 | # create a database connection 66 | conn = create_connection(database) 67 | 68 | # create tables 69 | if conn is not None: 70 | # create projects table 71 | create_table_in_db(conn, sql_create_projects_table) 72 | else: 73 | print("Error! cannot create the database connection.") 74 | close_connection(conn) 75 | 76 | 77 | # main execution to create table 78 | database = r"C:\\tempdir\database.db" # DB location 79 | create_table(database) # parse db name to create table in it. 80 | 81 | # ====================================================== 82 | 83 | # Add student data in table 84 | def add_student(conn, student): 85 | """ 86 | Create a new student entry into the student table 87 | :param conn: 88 | :param student: 89 | :return: student id 90 | """ 91 | sql = ''' INSERT INTO STUDENTS(name,gpa,admission_date) 92 | VALUES(?,?,?) ''' 93 | cur = conn.cursor() 94 | cur.execute(sql, student) 95 | return cur.lastrowid 96 | 97 | # main function to add student in table - MODIFIED 98 | def main_function(student): 99 | database =r"C:\\tempdir\database.db" 100 | 101 | # create a database connection 102 | conn = create_connection(database) 103 | with conn: 104 | # add a new student 105 | student_id = add_student(conn, student) 106 | 107 | print('The Student ID:', student_id) 108 | close_connection(conn) 109 | 110 | 111 | # Execute main funtion to add multiple students in table 112 | student1 = ('Fahad', 3.4, '2019-1-30'); 113 | main_function(student1) 114 | student2 = ('Munira', 2.9, '2012-2-30'); 115 | main_function(student2) 116 | student3 = ('Khawar', 3.79, '2018-11-30'); 117 | main_function(student3) 118 | 119 | # direct input to function to add new students 120 | main_function(('Ahad', 3.33, '2019-12-03')) 121 | main_function(('Momina', 2.83, '2020-02-13')) 122 | 123 | # ============================================================== 124 | ### READ TABLE 125 | database = r"C:\\tempdir\database.db" 126 | #create a database connection 127 | conn = create_connection(database) 128 | try: 129 | cursor = conn.cursor() 130 | table_name = "STUDENTS" 131 | sql_string = "SELECT * from " + table_name 132 | sqlite_select_query = sql_string 133 | 134 | cursor.execute(sqlite_select_query) 135 | records = cursor.fetchall() 136 | print("Total rows are: ", len(records)) 137 | cursor.close() 138 | except sqlite3.Error as error: 139 | print("Failed to read data from sqlite table", error) 140 | finally: 141 | close_connection(conn) 142 | print(records) 143 | 144 | -------------------------------------------------------------------------------- /Chapter_17th_cprofile.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Aug 7 13:26:42 2020 4 | 5 | @author: sana.rasheed 6 | """ 7 | # Chapter 17th 8 | # Example 4 9 | import cProfile 10 | def internal_method(): 11 | temp_var = 0 12 | for ind in range(10000): 13 | temp_var += 1 14 | return temp_var 15 | 16 | def external_method(): 17 | counter = 0 18 | for val in range(10): 19 | counter += internal_method() 20 | print('Total iterations:', counter) 21 | return 22 | 23 | cProfile.run('external_method()') 24 | 25 | # Output 26 | # Total iterations: 100000 27 | # 75 function calls in 0.015 seconds 28 | # Ordered by: standard name 29 | # ncalls tottime percall cumtime percall filename:lineno(function) 30 | # 10 0.014 0.001 0.014 0.001 8. profiling.py:3(internal_method) 31 | # 1 0.000 0.000 0.015 0.015 8. profiling.py:9(external_method) 32 | # 1 0.000 0.000 0.015 0.015 :1() 33 | # 5 0.000 0.000 0.001 0.000 iostream.py:197(schedule) 34 | # 4 0.000 0.000 0.000 0.000 iostream.py:309(_is_master_process) 35 | # 4 0.000 0.000 0.000 0.000 iostream.py:322(_schedule_flush) 36 | # 4 0.000 0.000 0.001 0.000 iostream.py:384(write) 37 | # 5 0.000 0.000 0.000 0.000 iostream.py:93(_event_pipe) 38 | # 5 0.001 0.000 0.001 0.000 socket.py:342(send) 39 | # 5 0.000 0.000 0.000 0.000 threading.py:1050(_wait_for_tstate_lock) 40 | # 5 0.000 0.000 0.000 0.000 threading.py:1092(is_alive) 41 | # 5 0.000 0.000 0.000 0.000 threading.py:507(is_set) 42 | # 1 0.000 0.000 0.015 0.015 {built-in method builtins.exec} 43 | # 4 0.000 0.000 0.000 0.000 {built-in method builtins.isinstance} 44 | # 1 0.000 0.000 0.001 0.001 {built-in method builtins.print} 45 | # 4 0.000 0.000 0.000 0.000 {built-in method nt.getpid} 46 | # 5 0.000 0.000 0.000 0.000 {method 'acquire' of '_thread.lock' objects} 47 | # 5 0.000 0.000 0.000 0.000 {method 'append' of 'collections.deque' objects} 48 | # 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 49 | -------------------------------------------------------------------------------- /Chapter_17th_debug.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Aug 7 13:27:32 2020 4 | 5 | @author: sana.rasheed 6 | """ 7 | # Chapter 17th 8 | # Example 3 9 | import pdb 10 | def sum_values(a, b): 11 | return a + b 12 | 13 | def test_function(): 14 | pdb.set_trace() #we have added a breakpoint here. The code pause execution here. 15 | print('This is the first line') 16 | print("This is the second line.") 17 | value = sum_values(2, 3) 18 | print('The code is done!') 19 | return value 20 | 21 | # execute the function 22 | test_function() 23 | 24 | # Output 25 | # > e:\task\python task\python\python\3. debugging.py(8)test_function() 26 | # 6 def test_function(): 27 | # 7 pdb.set_trace() #we have added a breakpoint here. The code pause execution here. 28 | # ----> 8 print('This is the first line') 29 | # 9 print("This is the second line.") 30 | # 10 value = sum_values(2, 3) 31 | 32 | 33 | -------------------------------------------------------------------------------- /Chapter_17th_unittest.py: -------------------------------------------------------------------------------- 1 | 2 | # Example 1 3 | import unittest 4 | 5 | def join_names(first, last): 6 | return ' '.join([first.capitalize(), last.capitalize()]) 7 | 8 | return_data = join_names('ahmed', 'hadi') 9 | print(return_data) 10 | 11 | class TestStringMethods(unittest.TestCase): #class is inherited from unittest .testcases 12 | def test_is_capitalized(self): 13 | temp1, temp2 = return_data.split(' ') 14 | self.assertTrue(temp1.istitle()) # moves to the next line if true 15 | self.assertTrue(temp2.istitle()) # moves to the next line if true 16 | def test_length(self): 17 | self.assertTrue(len(return_data.split(' ')), 2) 18 | def test_split(self): 19 | self.assertEqual(type(return_data), str) # moves to the next line if both are of str type 20 | # End of TestStringMethods class 21 | 22 | if __name__ == '__main__': 23 | unittest.main() 24 | 25 | 26 | # Output 27 | # Ahmed Hadi 28 | # ---------------------------------------------------------------------- 29 | # Ran 3 tests in 0.008s 30 | # OK 31 | 32 | # Example 2 33 | return_data = 'Ahmed hadi' # 'Shabir ahmed' 34 | if __name__ == '__main__': 35 | unittest.main() 36 | 37 | # Output 38 | # F..ahmed hadi 39 | # ====================================================================== 40 | # FAIL: test_is_capitalized (__main__.TestStringMethods) 41 | # ---------------------------------------------------------------------- 42 | # Traceback (most recent call last): 43 | # File "E:\task\Python task\Python\Python\untitled5.py", line 9, in test_is_capitalized 44 | # self.assertTrue(temp1.istitle()) 45 | # AssertionError: False is not true 46 | # ---------------------------------------------------------------------- 47 | # Ran 3 tests in 0.076s 48 | # FAILED (failures=1) 49 | -------------------------------------------------------------------------------- /Chapter_18th.py: -------------------------------------------------------------------------------- 1 | 2 | # ******************* Execute Examples in terminal ********************* # 3 | # Example 1 4 | ##################### 5 | ### Read INI file ### 6 | ##################### 7 | import configparser 8 | config = configparser.ConfigParser() 9 | # give the correct path of spyder.ini file 10 | config.read("C:\\Users\sana.rasheed\.spyder-py3\config\spyder.ini") #("C:\\Users\.spyder-py3\spyder.ini") 11 | config.sections() 12 | print( config.sections() ) 13 | # Output 14 | # ['main', 15 | # 'internal_console', 16 | # 'main_interpreter', 17 | # 'ipython_console', 18 | # 'variable_explorer', 19 | # 'plots', 20 | # 'editor', 21 | # 'historylog', 22 | # 'help', 23 | # 'onlinehelp', 24 | # 'outline_explorer', 25 | # 'project_explorer', 26 | # 'explorer', 27 | # 'find_in_files', 28 | # 'breakpoints', 29 | # 'profiler', 30 | # 'pylint', 31 | # 'workingdir', 32 | # 'shortcuts', 33 | # 'appearance', 34 | # 'lsp-server', 35 | # 'fallback-completions', 36 | # 'kite'] 37 | 38 | [option for option in config['help']] 39 | print( [option for option in config['help']] ) 40 | 41 | # Output 42 | # ['enable', 43 | # 'max_history_entries', 44 | # 'wrap', 45 | # 'connect/editor', 46 | # 'connect/ipython_console', 47 | # 'math', 48 | # 'automatic_import', 49 | # 'rich_mode', 50 | # 'first_time'] 51 | 52 | 53 | 54 | 55 | # Example 2 56 | ########################## 57 | ### Create Dictionary ### 58 | ######################### 59 | parser = configparser.ConfigParser() 60 | parser.read_dict( 61 | {'section1': 62 | {'tag1': '1','tag2': '2','tag3': '3'}, 63 | 'section2': 64 | {'tagA': 'A','tagB': 'B','tagC': 'C'}, 65 | 'section3': 66 | {'foo': 'x','bar': 'y','baz': 'z'} }) 67 | parser.sections() #['section1', 'section2', 'section3'] 68 | print(parser.sections()) 69 | 70 | # Output 71 | # ['section1', 'section2', 'section3'] 72 | 73 | [option for option in parser['section1']] 74 | print([option for option in parser['section1']]) 75 | 76 | # Output 77 | # 'tag1', 'tag2', 'tag3' 78 | 79 | 80 | 81 | 82 | # Example 3 83 | ############################## 84 | ### Read Text/String file ### 85 | ############################# 86 | sample_config = """ 87 | [My Settings] 88 | user = username 89 | profile = /my/directory/to/profile.png 90 | gender = male 91 | [My new Settings] 92 | user = Sana.Rasheed 93 | profile = /my/directory/to/profile.png 94 | gender = female 95 | """ 96 | 97 | # creates an instance of ConfigParser called config 98 | config = configparser.ConfigParser() 99 | 100 | #read the instance of string using read_string() method 101 | config.read_string(sample_config) 102 | config.sections() #['My Settings'] 103 | print(config.sections()) 104 | # Output 105 | # ['My Settings', 'My new Settings'] 106 | 107 | 108 | user = config["My new Settings"]["user"] #'username' 109 | print(user) 110 | 111 | # Output 112 | # 'Sana.rasheed' 113 | 114 | -------------------------------------------------------------------------------- /Chapter_19th.py: -------------------------------------------------------------------------------- 1 | 2 | # Example 1 3 | import numpy as np 4 | mat = np.array([[1,2,3], [4,5,6], [7,8,9]]) 5 | print('The shape of mat is:', mat.shape) 6 | # Output: The shape of mat is: (3, 3) 7 | 8 | # Example 2 9 | # It can be reshaped to any shape that is consistent with the data size 10 | new_mat = mat.reshape(1,9) 11 | print('The shape of new_mat is:', new_mat.shape) 12 | # Output: The shape of new_mat is: (1, 9) 13 | 14 | # Example 3 15 | # you can try transposing it as well. 16 | trans_new_mat = new_mat.T 17 | print('The transposed shape of new_mat is:', trans_new_mat.shape) 18 | # Output: The transposed shape of new_mat is: (9, 1) 19 | 20 | # Example 4 21 | # you can create diagonal matrices, identity matrices 22 | diag = np.diag([1,2,3,4]) 23 | identity = np.identity(10) # creates a 10 x 10 matrix with ones at diagonals and rest zeros 24 | 25 | # Example 5 26 | # you can create arrays of random numbers or sequences 27 | seq = np.arange(start=0, stop=100, step=5) # creates an array starting from 0, with a step size of 5 till 100. [0,5,10,....,90,95] 28 | 29 | # Example 6 30 | # If you only pass np.random.rand(10), it creates a 1D vector of length 10 31 | rands_1d = np.random.rand(10) 32 | rands_2d = np.random.rand(10, 10) # creates 10x10 matrix with random numbers. 33 | 34 | 35 | # Example 7 36 | my_array = np.array([1,3,5,7,23,6,2,31,5]) 37 | # you can find min and max and min as well as the index of max number or min number 38 | print('The max is {} at index {}'.format(my_array.max(), my_array.argmax())) 39 | # Output:The max is 31 at index 7 40 | print('The min is {} at index {}'.format(my_array.min(), my_array.argmin())) 41 | # Output: The min is 1 at index 0 42 | 43 | # Example 8 44 | import time 45 | # you can perform dot products of matrices in a matter of seconds 46 | my_mat = np.random.rand(1000, 1000) 47 | another_mat = np.random.rand(1000, 1000) 48 | start = time.time() 49 | # make sure the dimensions agree! 50 | dot_mul = my_mat.dot(another_mat) 51 | end = time.time() 52 | print('It took {} seconds to calculate dot product!'.format(round(end-start, 4))) 53 | # Output: It took 11.0579 seconds to calculate dot product! 54 | 55 | start = time.time() 56 | prod = my_mat * another_mat 57 | end = time.time() 58 | print('It took {} seconds to manully calculate dot product!'.format(round(end-start, 4))) 59 | # Output: It took 0.026 seconds to calculate dot product! 60 | 61 | # Example 9 62 | import numpy as np # linear algebra 63 | import numpy.linalg as la 64 | my_mat = np.array([[1,2], [3,4]]) 65 | 66 | # calculate determinant 67 | det = la.det(my_mat) 68 | print('Det: ', det) 69 | 70 | inverse_mat = la.inv(my_mat) 71 | # calculate inverse of a matrix. Inv = adj(matrix)/det(matrix). NOTE: Make sure its not SINGULAR! 72 | print('Inverse_mat: ', inverse_mat) 73 | 74 | # calculate eigen values. NOTE: make sure the matrix is SQUARE [eigen values do not exit 75 | # for matrix whose dimensions are mxn where m!=n] 76 | eig_values, eig_vectors = la.eig(my_mat) 77 | print('Eigen values: ', eig_values, eig_vectors) 78 | 79 | # calculate cholesky factorization. NOTE: make sure matrix is Positive Definite! 80 | cholesky = la.cholesky(np.array([[7,2], [2,1]])) 81 | print('Cholesky: ', cholesky) 82 | 83 | # calculate rank of a matrix. Rank of a matrix is the number of linearly 84 | # independent columns/rows in a matrix.# 85 | rank = la.matrix_rank(my_mat) 86 | print('Rank: ', rank) 87 | 88 | 89 | -------------------------------------------------------------------------------- /Chapter_3rd.py: -------------------------------------------------------------------------------- 1 | # Example 1 2 | print ("Hello World!") 3 | 4 | # Example 2 5 | if 5 > 2: 6 | print("Five is greater than two!") 7 | 8 | # Example 3 9 | # This will give an error due to incorrect indentation 10 | if 5 > 2: 11 | print("Five is greater than two!") # Fix: add 1 tab in the beginning of line. 12 | 13 | # Example 4 14 | #This is a comment 15 | print("Hello, World!") 16 | 17 | 18 | # Example 5 19 | print("Hello, World!") #This is a comment 20 | 21 | 22 | # Example 7 - comment with short-key - select lines below and press Ctrl+1 buttons. 23 | # This is a comment 24 | # written in 25 | # more than just one line 26 | print("Hello, World!") 27 | 28 | 29 | # Example 8 30 | # Computer the value of a block of stock 31 | shares= 150 32 | price= 3 + 5.0/8.0 33 | value= shares * price 34 | print("value",value) 35 | 36 | 37 | # Example 9 38 | # Total value of a portfolio made up of two blocks of stock 39 | portfolio = 0 40 | portfolio += 150 * 2 + 1/4.0 41 | portfolio += 75 * 1 + 7/8.0 42 | print("portfolio", portfolio) 43 | 44 | 45 | # Example 10 46 | x, y, z = "Orange", "Banana", "Cherry" 47 | print(x) 48 | print(y) 49 | print(z) 50 | 51 | # Output 52 | # Orange 53 | # Banana 54 | # Cherry 55 | 56 | # Example 11 57 | x = y = z = "Orange" 58 | print(x) 59 | print(y) 60 | print(z) 61 | 62 | # Output 63 | # Orange 64 | # Orange 65 | # Orange 66 | 67 | # Example 12 68 | first_number = 4 69 | second_number = 6 70 | summation = first_number + second_number 71 | # Output will be 10 72 | 73 | 74 | -------------------------------------------------------------------------------- /Chapter_4th.py: -------------------------------------------------------------------------------- 1 | # Example 1 2 | print('Hello') 3 | print("Hello") 4 | 5 | # Output 6 | # Hello 7 | # Hello 8 | 9 | 10 | # Example 2 11 | a = "Hello" 12 | print(a) 13 | 14 | 15 | # Example 3 16 | # Creating a multiline string 17 | a = """I'm learning Python. 18 | I refer to TechBeamers.com tutorials. 19 | It is the most popular site for Python programmers.""" 20 | print(a) 21 | 22 | 23 | # Example 4 24 | x = 1 # int 25 | y = 2.8 # float 26 | z = 1j # complex 27 | print(type(x)) 28 | print(type(y)) 29 | print(type(z)) 30 | 31 | # Example 5 32 | x = 1 33 | y = 35656222554887711 34 | z = -3255522 35 | print(type(x)) 36 | print(type(y)) 37 | print(type(z)) 38 | 39 | # Example 6 40 | x = 1.10 41 | y = 1.0 42 | z = -35.59 43 | print(type(x)) 44 | print(type(y)) 45 | print(type(z)) 46 | 47 | # Example 7 48 | x = 3+5j 49 | y = 5j 50 | z = -5j 51 | print(type(x)) 52 | print(type(y)) 53 | print(type(z)) 54 | 55 | # Example 8 56 | thislist = ["apple", "banana", "cherry"] 57 | print(thislist) 58 | 59 | # Example 9 60 | thislist = ["apple", "banana", "cherry"] 61 | print(thislist[1]) 62 | 63 | # Output 64 | # banana 65 | 66 | 67 | # Example 10 68 | thislist = ["apple", "banana", "cherry"] 69 | print(thislist[-1]) 70 | 71 | # Output 72 | # cherry 73 | 74 | 75 | # Example 11 76 | thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] 77 | print(thislist[2:5]) 78 | 79 | # Output 80 | # ['cherry', 'orange', 'kiwi'] 81 | 82 | # Example 12 83 | thistuple = ("apple", "banana", "cherry") 84 | print(thistuple[1]) 85 | 86 | # Output 87 | # banana 88 | 89 | 90 | # Example 13 91 | thisdict ={ 92 | "brand": "Ford", 93 | "model": "Mustang", 94 | "year": 1964 95 | } 96 | print(thisdict) 97 | 98 | # Output 99 | # {'brand': 'Ford', 'model': 'Mustang', 'year': 1964} 100 | 101 | 102 | # Example 14 103 | thisdict ={ 104 | "brand": "Ford", 105 | "model": "Mustang", 106 | "year": 1964 107 | } 108 | x = thisdict["model"] 109 | print(x) 110 | 111 | # Output 112 | # Mustang 113 | 114 | 115 | # Example 15 116 | thisset = {"apple", "banana", "cherry"} 117 | print(thisset) 118 | 119 | # Output 120 | # {'apple', 'cherry', 'banana'} 121 | 122 | 123 | # Example 16 124 | thisset = {"apple", "banana", "cherry"} 125 | thisset.add("orange") 126 | print(thisset) 127 | 128 | # Output 129 | # {'apple', 'cherry', 'orange', 'banana'} 130 | 131 | # Example 17 132 | thisset = {"apple", "banana", "cherry"} 133 | thisset.update(["orange", "mango", "grapes"]) 134 | print(thisset) 135 | 136 | # Output 137 | # {'orange', 'cherry', 'banana', 'apple', 'mango', 'grapes'} 138 | 139 | 140 | # Example 18 141 | thisset = {"apple", "banana", "cherry"} 142 | print(len(thisset)) 143 | 144 | # Output 145 | # 3 146 | 147 | 148 | # Example 19 149 | thisset = {"apple", "banana", "cherry"} 150 | thisset.remove("banana") 151 | print(thisset) 152 | 153 | # Output 154 | # {'apple','cherry'} 155 | 156 | # Example 20 157 | cities = frozenset(["Frankfurt", "Basel","Freiburg"]) 158 | cities.add("Strasbourg") 159 | print(cities) 160 | 161 | # Output 162 | # Traceback (most recent call last): 163 | # File "C:\Users\.spyder-py3\temp.py", line 2, in 164 | # cities.add("Strasbourg") 165 | # AttributeError: 'frozenset' object has no attribute 'add' 166 | 167 | 168 | # Example 21 169 | print(10 > 9) 170 | print(10 == 9) 171 | print(10 < 9) 172 | 173 | # Output 174 | # True 175 | # False 176 | # False 177 | 178 | 179 | # Example 22 180 | a = 200 181 | b = 33 182 | if b > a: 183 | print("b is greater than a") 184 | else: 185 | print("b is not greater than a") 186 | 187 | # Output 188 | # b is not greater than a 189 | 190 | 191 | 192 | # Example 23 193 | # create a str 194 | x = b'Python mapping table characters' 195 | print(x) 196 | 197 | # Output 198 | # b'Python mapping table characters' 199 | 200 | 201 | # Example 24 202 | x = b"Bytes objects are immutable sequences of single bytes" 203 | print(x) 204 | 205 | # Output 206 | # b'Bytes objects are immutable sequences of single bytes' 207 | 208 | 209 | # Example 25 210 | # triple single or double quotes allows multiple lines 211 | x = b'''Python Tutorial, 212 | Javascript Tutorial, 213 | MySQL Tutorial''' 214 | print(x) 215 | 216 | # Output 217 | # b'Python Tutorial,\nJavascript Tutorial,\nMySQL Tutorial' 218 | 219 | 220 | 221 | # Example 26 222 | string = "Python is interesting." 223 | # string with encoding 'utf-8' 224 | arr = bytearray(string, 'utf-8') 225 | print(arr) 226 | 227 | # Output 228 | # bytearray(b'Python is interesting.') 229 | 230 | 231 | # Example 27 232 | import datetime 233 | x = datetime.datetime.now() 234 | print(x) 235 | 236 | # Output 237 | # 2020-07-03 17:37:07.999021 238 | 239 | 240 | # Example 28 241 | import datetime 242 | x = datetime.datetime.now() 243 | print(x.year) 244 | print(x.strftime("%A")) 245 | 246 | # Output 247 | # 2020 248 | # Friday 249 | 250 | 251 | # Example 29 252 | import datetime 253 | x = datetime.datetime.now() # current date and time 254 | year = x.strftime("%Y") 255 | month = x.strftime("%m") 256 | day = x.strftime("%d") 257 | print("day: ", day) 258 | time = x.strftime("%H:%M:%S") 259 | print("time: ", time) 260 | date_time = x.strftime("%m/%d/%Y, %H:%M:%S") 261 | print("date and time:", date_time) 262 | 263 | # Output 264 | # day: 03 265 | # time: 13:25:36 266 | # date and time: 07/03/2020, 13:25:36 267 | 268 | 269 | # Example 30 270 | from datetime import datetime 271 | # current date and time 272 | now = datetime.now() 273 | t = now.strftime("%H:%M:%S") 274 | print("time:", t) 275 | s1 = now.strftime("%m/%d/%Y") # mm/dd/YY format 276 | print("s1:", s1) 277 | s2 = now.strftime("%d/%m/%Y") # dd/mm/YY format 278 | print("s2:", s2) 279 | s3 = now.strftime("%d-%m-%Y") # dd-mm-YY format 280 | print("s3:", s3) 281 | s4 = now.strftime("%a-%b-%y") 282 | print("s4:", s4) 283 | s5 = now.strftime("%A-%B-%Y") 284 | print("s5:", s5) 285 | 286 | 287 | # Output 288 | # time: 13:42:48 289 | # s1: 07/16/2020 290 | # s2: 16/07/2020 291 | # s3: 16-07-2020 292 | # s4: Thu-Jul-20 293 | # s5: Thursday-July-2020 294 | 295 | -------------------------------------------------------------------------------- /Chapter_5th.py: -------------------------------------------------------------------------------- 1 | # Example 1 2 | a = 33 3 | b = 200 4 | if b > a: 5 | print("b is greater than a") 6 | 7 | # Output 8 | # b is greater than a 9 | 10 | 11 | # Example 2 12 | a = 33 13 | b = 33 14 | if b > a: 15 | print("b is greater than a") 16 | elif a == b: 17 | print("a and b are equal") 18 | 19 | # Output 20 | # a and b are equal 21 | 22 | 23 | # Example 3 24 | a = 200 25 | b = 33 26 | if b > a: 27 | print("b is greater than a") 28 | elif a == b: 29 | print("a and b are equal") 30 | else: 31 | print("a is greater than b") 32 | 33 | # Output 34 | # a is greater than b 35 | 36 | 37 | # Example 4 38 | x = 41 39 | if x > 10: 40 | print("Above ten,") 41 | if x > 20: 42 | print("Also above 20!") 43 | else: 44 | print("but not above 20.") 45 | 46 | # Output 47 | # Above ten, 48 | # Also above 20! 49 | 50 | 51 | # Example 5 52 | fruits = ["apple", "banana", "cherry"] 53 | for x in fruits: 54 | print(x) 55 | 56 | # Output 57 | # apple 58 | # banana 59 | # cherry 60 | 61 | 62 | # Example 6 63 | for x in "banana": 64 | print(x) 65 | 66 | # Output 67 | # b 68 | # a 69 | # n 70 | # a 71 | # n 72 | # a 73 | 74 | 75 | # Example 7 76 | for x in range(6): 77 | print(x) 78 | else: 79 | print("Finally finished!") 80 | 81 | # Output 82 | # 0 83 | # 1 84 | # 2 85 | # 3 86 | # 4 87 | # 5 88 | # Finally finished! 89 | 90 | 91 | # Example 8 92 | adj = ["red", "big", "tasty"] 93 | fruits = ["apple", "banana", "cherry"] 94 | for x in adj: 95 | for y in fruits: 96 | print(x, y) 97 | # Output 98 | # red apple 99 | # red banana 100 | # red cherry 101 | # big apple 102 | # big banana 103 | # big cherry 104 | # tasty apple 105 | # tasty banana 106 | # tasty cherry 107 | 108 | 109 | # Example 9 110 | i = 1 111 | while i < 6: 112 | print(i) 113 | i += 1 114 | 115 | # Output 116 | # 1 117 | # 2 118 | # 3 119 | # 4 120 | # 5 121 | 122 | 123 | # Example 10 124 | fruits = ["apple", "banana", "cherry"] 125 | for x in fruits: 126 | if x == "banana": 127 | continue 128 | print(x) 129 | 130 | # Output 131 | # apply 132 | # cherry 133 | 134 | 135 | # Example 11 136 | i = 0 137 | while i < 6: 138 | i += 1 139 | if i == 3: 140 | continue 141 | print(i) 142 | 143 | # Output 144 | # 1 145 | # 2 146 | # 4 147 | # 5 148 | # 6 149 | 150 | 151 | # Example 12 152 | fruits = ["apple", "banana", "cherry"] 153 | for x in fruits: 154 | print(x) 155 | if x == "banana": 156 | break 157 | 158 | # Output 159 | # apply 160 | # banana 161 | 162 | # Example 13 163 | i = 1 164 | while i < 6: 165 | print(i) 166 | if i == 3: 167 | break 168 | i += 1 169 | 170 | # Output 171 | # 1 172 | # 2 173 | # 3 174 | 175 | # Example 14 176 | for x in [0, 1, 2]: 177 | pass 178 | 179 | 180 | -------------------------------------------------------------------------------- /Chapter_6th.py: -------------------------------------------------------------------------------- 1 | # Example 1 2 | a = 21 3 | b = 10 4 | c = 0 5 | c = a + b 6 | print (" Value of c is ", c) 7 | c = a - b 8 | print (" Value of c is ", c ) 9 | c = a * b 10 | print( " Value of c is ", c ) 11 | c = a / b 12 | print( " Value of c is ", c ) 13 | 14 | # Output 15 | # Value of c is 31 16 | # Value of c is 11 17 | # Value of c is 210 18 | # Value of c is 2.1 19 | 20 | 21 | # Example 2 22 | x = 10 23 | y = 12 24 | print('x > y is',x>y) 25 | # Output: x > y is False 26 | print('x < y is',x= y is',x>=y) 33 | # Output: x >= y is False 34 | print('x <= y is',x<=y) 35 | # Output: x <= y is True 36 | 37 | 38 | # Example 3 39 | x = True 40 | y = False 41 | print('x and y is',x and y) 42 | print('x or y is',x or y) 43 | print('not x is',not x) 44 | 45 | # Output 46 | # x and y is False 47 | # x or y is True 48 | # not x is False 49 | 50 | 51 | # Example 4 52 | x1 = 5 53 | y1 = 5 54 | x2 = 'Hello' 55 | y2 = 'Hello' 56 | print(x1 is not y1) 57 | print(x2 is y2) 58 | 59 | # Output 60 | # False 61 | # True 62 | 63 | 64 | # Example 5 65 | x = 'Hello world' 66 | y = {1:'a',2:'b'} 67 | print('H' in x) 68 | print('hello' not in x) 69 | print(1 in y) 70 | print('a' in y) 71 | 72 | # Output 73 | # True 74 | # True 75 | # True 76 | # False 77 | 78 | 79 | # Example 6 80 | a = 10 81 | b = 4 82 | print("a & b =", a & b) # Print bitwise AND operation 83 | print("a | b =", a | b) # Print bitwise OR operation 84 | print("~a =", ~a) # Print bitwise NOT operation 85 | print("a ^ b =", a ^ b) # print bitwise XOR operation 86 | 87 | # Output 88 | # a & b = 0 89 | # a | b = 14 90 | # ~a = -11 91 | # a ^ b = 14 92 | -------------------------------------------------------------------------------- /Chapter_7th.py: -------------------------------------------------------------------------------- 1 | # Example 1 2 | def my_function(): 3 | print("Hello from a function") 4 | my_function() 5 | 6 | # Output 7 | # Hello from a function 8 | 9 | 10 | # Example 2 11 | def my_function(fname): 12 | print(fname + " Robert") 13 | 14 | my_function("Emily") 15 | my_function("John") 16 | my_function("Julia") 17 | 18 | # Output 19 | # Emily Robert 20 | # John Robert 21 | # Julia Robert 22 | 23 | 24 | # Example 3 25 | def my_function(fname, lname): 26 | print(fname + " " + lname) 27 | 28 | my_function("Emily", "Robert") 29 | 30 | # Output 31 | # Emily Robert 32 | 33 | 34 | # Example 4 35 | def my_function(fname, lname): 36 | print(fname + " " + lname) 37 | 38 | my_function("Emily") 39 | 40 | # Output 41 | # TypeError: my_function() missing 1 required positional argument: 'lname' 42 | 43 | 44 | # Example 5 45 | def my_function(country = "Norway"): 46 | print("I am from " + country) 47 | 48 | my_function("Pakistan") 49 | my_function("Sweden") 50 | my_function() 51 | my_function("China") 52 | 53 | # Output 54 | # I am from Pakistan 55 | # I am from Sweden 56 | # I am from Norway 57 | # I am from China 58 | 59 | 60 | # Example 6 61 | def my_function(*kids): 62 | print("The youngest child is " + kids[2]) 63 | 64 | my_function("Emily", "John", "Julia") 65 | 66 | # Output 67 | # The youngest child is Julia 68 | 69 | 70 | # Example 7 71 | def my_function(child3, child2, child1): 72 | print("The youngest child is " + child3) 73 | 74 | my_function(child1 = "Emily", child2 = "John", child3 = "Julia") 75 | 76 | # Output 77 | # The youngest child is Julia 78 | 79 | 80 | # Example 8 81 | def my_function(child3, child2, child1): 82 | print("The youngest child is " + child3) 83 | 84 | my_function(child3 = "Julia", child2 = "John",child1 = "Emily" ) 85 | 86 | 87 | # Output 88 | # The youngest child is Julia 89 | 90 | 91 | # Example 9 92 | def my_function(**kid): 93 | print("His last name is " + kid["lname"]) 94 | 95 | my_function(fname = "John", lname = "Robert") 96 | 97 | # Output 98 | # His last name is Robert 99 | 100 | 101 | # Example 10 102 | def my_function(food): 103 | for x in food: 104 | print(x) 105 | 106 | fruits = ["apple", "banana", "cherry"] 107 | my_function(fruits) 108 | 109 | # Output 110 | # apple 111 | # banana 112 | # cherry 113 | 114 | 115 | # Example 11 116 | def my_function(x): 117 | return 5 * x 118 | 119 | print(my_function(3)) 120 | print(my_function(5)) 121 | print(my_function(9)) 122 | 123 | 124 | # Output 125 | # 15 126 | # 25 127 | # 45 128 | 129 | 130 | # Example 12 131 | def tri_recursion(k): 132 | if(k > 0): 133 | result = k + tri_recursion(k - 1) 134 | print(result) 135 | else: 136 | result = 0 137 | return result 138 | 139 | print("\n\nRecursion Example Results") 140 | tri_recursion(6) 141 | 142 | # Output 143 | # Recursion Example Results 144 | # 1 145 | # 3 146 | # 6 147 | # 10 148 | # 15 149 | # 21 150 | 151 | # Example 13 152 | x = lambda a: a + 10 153 | print(x(5)) 154 | 155 | # Output 156 | # 15 157 | 158 | # Example 14 159 | x = lambda a, b: a * b 160 | print(x(5, 6)) 161 | 162 | # Output 163 | # 30 164 | 165 | 166 | # Example 15 167 | x = lambda a, b, c: a + b + c 168 | print(x(5, 6, 2)) 169 | 170 | # Output 171 | # 13 172 | 173 | 174 | # Example 16 175 | def myfunc(n): 176 | return lambda a : a * n 177 | 178 | mydoubler = myfunc(2) 179 | print(mydoubler(11)) 180 | 181 | # Output 182 | # 22 183 | 184 | mytripler = myfunc(3) 185 | print(mytripler(11)) 186 | 187 | # Output 188 | # 33 189 | 190 | mydoubler = myfunc(2) 191 | mytripler = myfunc(3) 192 | print(mydoubler(11)) 193 | print(mytripler(11)) 194 | 195 | # Output 196 | # 22 197 | # 33 198 | -------------------------------------------------------------------------------- /Chapter_8th.py: -------------------------------------------------------------------------------- 1 | # Example 2 | # 3/0 # type it directly in terminal - it will give you following error 3 | # Traceback (most recent call last): 4 | # File "", line 1, in 5 | # 3/0 6 | # ZeroDivisionError: division by zero 7 | 8 | 9 | # Example 10 | divisor = 0 11 | try: 12 | value = 22/divisor 13 | except ZeroDivisionError: 14 | print('The divisor provided was zero.') 15 | 16 | 17 | # Example 18 | my_numbers=[1,2,3,4] 19 | print('The length of the list is:', len(my_numbers)) 20 | #my_numbers[4] # this will give you an error 21 | 22 | # Output: 23 | # The length of this list is: 4 24 | # IndexError: list index out of range 25 | 26 | 27 | # Example 28 | try: 29 | my_numbers[4] 30 | except IndexError: 31 | print('The index you used is invalid.') 32 | 33 | print('The code executed.') 34 | 35 | # Output: 36 | # The index you used is invalid. 37 | # The code executed. 38 | 39 | 40 | # Example 41 | def check_type(year): 42 | assert type(year) == int, 'The type of year is not integer' 43 | print('The type of year is valid.') 44 | return True 45 | 46 | check_type(year=2010) # The type of year is valid. 47 | 48 | # Example this will give you error after uncomment 49 | # check_type(year=2010.22) # AssertionError: The type of year is not integer. 50 | 51 | 52 | # Example 53 | def check_type(year): 54 | try: 55 | assert type(year) == int 56 | except AssertionError: 57 | print('The type of year is invalid') 58 | return False 59 | return True 60 | 61 | print(check_type(year=2010.22)) 62 | # The type of year is invalid. 63 | # False 64 | print(check_type(year=2010)) 65 | # True 66 | 67 | 68 | # Example 69 | try: 70 | print(x) 71 | except: 72 | print("An exception occurred") 73 | 74 | # Output 75 | # An exception occurred 76 | 77 | 78 | # Example 79 | try: 80 | print(x) 81 | except: 82 | print("Something went wrong") 83 | finally: 84 | print("The 'try except' is finished") 85 | 86 | # Output 87 | # Something went wrong 88 | # The 'try except' is finished 89 | 90 | -------------------------------------------------------------------------------- /Chapter_9th_Inheritance_Fruit_example.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Thu Aug 6 15:51:01 2020 4 | 5 | @author: sana.rasheed 6 | """ 7 | ### Chapter 9th - Inheritance 8 | 9 | # Example 15 10 | # Fruit class defined as parent 11 | class Fruit: 12 | """ 13 | A class is defined for fruits, 14 | to create objects of this class.. 15 | """ 16 | def __init__(self, name, nutrients): 17 | try: 18 | assert type(nutrients) == list 19 | except AssertionError: 20 | print('invalid construction') 21 | raise Exception 22 | self.name = name 23 | self.nutrients = nutrients 24 | self.is_ripe = False 25 | def get_name(self): 26 | return self.name 27 | def get_nutrients (self): 28 | print(self.name + ' has following nutrients:') 29 | for value in self.nutrients: 30 | print (value) 31 | def check_ripeness(self): 32 | return self.is_ripe 33 | def ripe_fruit(self): 34 | self.is_ripe = True 35 | # End of Fruit class 36 | 37 | # Citrus is an Inherited Class of Fruit 38 | class Citrus(Fruit): 39 | def __init__(self, name, nutrients): 40 | super().__init__( name,nutrients) 41 | self.type= 'Citrus' 42 | self.characteristic = 'Pulpy and Juicy' 43 | def get_type(self): 44 | return self.type 45 | # End of Citrus class 46 | 47 | Orange = Citrus(name='Orange', nutrients=['vitamin D','vitamin C']) 48 | Orange.get_nutrients() 49 | 50 | # Output 51 | # Orange has following nutrients: 52 | # vitamin D 53 | # vitamin C 54 | -------------------------------------------------------------------------------- /Chapter_9th_class.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Aug 7 13:15:35 2020 4 | 5 | @author: sana.rasheed 6 | """ 7 | 8 | ### Chapter 9th - Class 9 | 10 | # Example 1 11 | class MyClass: 12 | x = 5 13 | print(MyClass) 14 | 15 | # Output 16 | # 17 | 18 | 19 | # Example 2 20 | class MyClass: 21 | x = 5 22 | 23 | p1 = MyClass() 24 | print(p1.x) 25 | 26 | # Output 27 | # 5 28 | 29 | 30 | # Example 3 31 | class Person: 32 | def __init__(self, name, age): 33 | self.name = name 34 | self.age = age 35 | 36 | p1 = Person("John", 36) 37 | print(p1.name) 38 | print(p1.age) 39 | 40 | # Output 41 | # John 42 | # 36 43 | 44 | 45 | # Example 4 46 | class Person: 47 | def __init__(myobject, name, age): 48 | myobject.name = name 49 | myobject.age = age 50 | def myfunc(abc): 51 | print("Hello my name is " + abc.name) 52 | 53 | p1 = Person("John", 36) 54 | p1.myfunc() 55 | 56 | # Output 57 | # Hello my name is John 58 | 59 | 60 | # Example 5 61 | class Person: 62 | def __init__(self, name, age): 63 | self.name = name 64 | self.age = age 65 | def myfunc(self): 66 | print("Hello my name is " + self.name) 67 | 68 | p1 = Person("John", 36) 69 | p1.myfunc() 70 | 71 | # Output 72 | # Hello my name is John 73 | 74 | 75 | 76 | # Example 6 77 | class Person: 78 | def __init__(self, name, age): 79 | self.name = name 80 | self.age = age 81 | def myfunc(self): 82 | print("Hello my name is " + self.name) 83 | 84 | p1 = Person("John", 36) 85 | p1.age = 40 86 | print(p1.age) 87 | 88 | # Output 89 | # 40 90 | 91 | 92 | # Example 7 93 | class Person: 94 | def __init__(self, name, age): 95 | self.name = name 96 | self.age = age 97 | def myfunc(self): 98 | print("Hello my name is " + self.name) 99 | 100 | p1 = Person("John", 36) 101 | del p1.age # delete p1.age 102 | print(p1.age) # return an error as p1.age is deleted 103 | 104 | # Output 105 | # AttributeError: 'Person' object has no attribute 'age' 106 | 107 | 108 | # Example 8 109 | class Person: 110 | def __init__(self, name, age): 111 | self.name = name 112 | self.age = age 113 | def myfunc(self): 114 | print("Hello my name is " + self.name) 115 | 116 | p1 = Person("John", 36) 117 | del p1 # delete p1 118 | print(p1) # return an error as p1 is deleted 119 | 120 | # Output 121 | # NameError: name 'p1' is not defined 122 | 123 | -------------------------------------------------------------------------------- /Chapter_9th_inheritance.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Aug 7 14:15:35 2020 4 | 5 | @author: sana.rasheed 6 | """ 7 | 8 | ### Chapter 9th - Inheritance 9 | ''' 10 | Author Note: 11 | For the sake of learning, I have redefined parent class for each example, 12 | so you execute it successfully. However, we define classes only ONE TIME. 13 | ''' 14 | # Example 9 15 | class Person: 16 | def __init__(self, fname, lname): 17 | self.firstname = fname 18 | self.lastname = lname 19 | def printname(self): 20 | print(self.firstname, self.lastname) 21 | 22 | x = Person("John", "Robert") 23 | x.printname() 24 | 25 | # Output 26 | # John Robert 27 | 28 | 29 | # Example 10 30 | class Person: 31 | def __init__(self, fname, lname): 32 | self.firstname = fname 33 | self.lastname = lname 34 | def printname(self): 35 | print(self.firstname, self.lastname) 36 | 37 | class Student(Person): 38 | pass 39 | 40 | x = Student("Mike", "Olsen") 41 | x.printname() 42 | 43 | # Output 44 | # Mike Olsen 45 | 46 | 47 | # Example 11 48 | class Person: 49 | def __init__(self, fname, lname): 50 | self.firstname = fname 51 | self.lastname = lname 52 | def printname(self): 53 | print(self.firstname, self.lastname) 54 | 55 | class Student(Person): 56 | def __init__(self, fname, lname): 57 | Person.__init__(self, fname, lname) 58 | 59 | x = Student("Mike", "Olsen") 60 | x.printname() 61 | 62 | # Output 63 | # Mike Olsen 64 | 65 | 66 | # Example 12 67 | class Person: 68 | def __init__(self, fname, lname): 69 | self.firstname = fname 70 | self.lastname = lname 71 | def printname(self): 72 | print(self.firstname, self.lastname) 73 | 74 | class Student(Person): 75 | def __init__(self, fname, lname): 76 | super().__init__(fname, lname) 77 | 78 | x = Student("Mike", "Olsen") 79 | x.printname() 80 | 81 | # Output 82 | # Mike Olsen 83 | 84 | 85 | # Example 13 86 | class Person: 87 | def __init__(self, fname, lname): 88 | self.firstname = fname 89 | self.lastname = lname 90 | def printname(self): 91 | print(self.firstname, self.lastname) 92 | 93 | class Student(Person): 94 | def __init__(self, fname, lname): 95 | super().__init__(fname, lname) 96 | self.graduationyear = 2020 97 | 98 | x = Student("Olivia", "Brown") 99 | print(x.graduationyear) 100 | 101 | # Output 102 | # 2020 103 | 104 | 105 | 106 | # Example 14 107 | 108 | class Person: 109 | def __init__(self, fname, lname): 110 | self.firstname = fname 111 | self.lastname = lname 112 | def printname(self): 113 | print(self.firstname, self.lastname) 114 | 115 | class Student(Person): 116 | def __init__(self, fname, lname, year): 117 | super().__init__(fname, lname) 118 | self.graduationyear = year 119 | def welcome(self): 120 | print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear) 121 | 122 | x = Student("Olivia", "Brown", 2020) 123 | x.welcome() 124 | 125 | # Output 126 | # Welcome Olivia Brown to the class of 2020 127 | 128 | 129 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Programming Book 2 | 3 | ## Dear Readers, 4 | 5 | Thank you very much for reading my book. I hope, it will give you a starting point to learn and excel in programming. 6 | 7 | Python scripts are available for book readers for easy learning and coding. Chapter-wise code examples have shared with related data files. 8 | 9 | 10 | ## Have a Happy Coding! 11 | 12 | 13 | ### Regards, 14 | 15 | ### Sana Rasheed 16 | -------------------------------------------------------------------------------- /Score.csv: -------------------------------------------------------------------------------- 1 | AA,28 2 | AB,11 3 | AC,26 4 | CD,24 5 | CE,28 6 | CF,13 7 | EF,17 8 | EG,15 9 | EH,12 10 | GH,22 11 | GI,14 12 | GJ,19 13 | IJ,19 14 | IK,18 15 | IL,21 16 | KL,10 17 | KM,14 18 | -------------------------------------------------------------------------------- /books.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Gambardella, Matthew 5 | XML Developer's Guide 6 | Computer 7 | 44.95 8 | 2000-10-01 9 | An in-depth look at creating applications 10 | with XML. 11 | 12 | 13 | Ralls, Kim 14 | Midnight Rain 15 | Fantasy 16 | 5.95 17 | 2000-12-16 18 | A former architect battles corporate zombies, 19 | an evil sorceress, and her own childhood to become queen 20 | of the world. 21 | 22 | 23 | Corets, Eva 24 | Maeve Ascendant 25 | Fantasy 26 | 5.95 27 | 2000-11-17 28 | After the collapse of a nanotechnology 29 | society in England, the young survivors lay the 30 | foundation for a new society. 31 | 32 | 33 | Corets, Eva 34 | Oberon's Legacy 35 | Fantasy 36 | 5.95 37 | 2001-03-10 38 | In post-apocalypse England, the mysterious 39 | agent known only as Oberon helps to create a new life 40 | for the inhabitants of London. Sequel to Maeve 41 | Ascendant. 42 | 43 | 44 | Corets, Eva 45 | The Sundered Grail 46 | Fantasy 47 | 5.95 48 | 2001-09-10 49 | The two daughters of Maeve, half-sisters, 50 | battle one another for control of England. Sequel to 51 | Oberon's Legacy. 52 | 53 | 54 | Randall, Cynthia 55 | Lover Birds 56 | Romance 57 | 4.95 58 | 2000-09-02 59 | When Carla meets Paul at an ornithology 60 | conference, tempers fly as feathers get ruffled. 61 | 62 | 63 | Thurman, Paula 64 | Splish Splash 65 | Romance 66 | 4.95 67 | 2000-11-02 68 | A deep sea diver finds true love twenty 69 | thousand leagues beneath the sea. 70 | 71 | 72 | Knorr, Stefan 73 | Creepy Crawlies 74 | Horror 75 | 4.95 76 | 2000-12-06 77 | An anthology of horror stories about roaches, 78 | centipedes, scorpions and other insects. 79 | 80 | 81 | Kress, Peter 82 | Paradox Lost 83 | Science Fiction 84 | 6.95 85 | 2000-11-02 86 | After an inadvertant trip through a Heisenberg 87 | Uncertainty Device, James Salway discovers the problems 88 | of being quantum. 89 | 90 | 91 | O'Brien, Tim 92 | Microsoft .NET: The Programming Bible 93 | Computer 94 | 36.95 95 | 2000-12-09 96 | Microsoft's .NET initiative is explored in 97 | detail in this deep programmer's reference. 98 | 99 | 100 | O'Brien, Tim 101 | MSXML3: A Comprehensive Guide 102 | Computer 103 | 36.95 104 | 2000-12-01 105 | The Microsoft MSXML3 parser is covered in 106 | detail, with attention to XML DOM interfaces, XSLT processing, 107 | SAX and more. 108 | 109 | 110 | Galos, Mike 111 | Visual Studio 7: A Comprehensive Guide 112 | Computer 113 | 49.95 114 | 2001-04-16 115 | Microsoft Visual Studio 7 is explored in depth, 116 | looking at how Visual Basic, Visual C++, C#, and ASP+ are 117 | integrated into a comprehensive development 118 | environment. 119 | 120 | -------------------------------------------------------------------------------- /demofile.txt: -------------------------------------------------------------------------------- 1 | C:\Users\My Name>python demo_file_open.py 2 | Hello! Welcome to demofile.txt 3 | This file is for testing purposes. 4 | Good Luck! -------------------------------------------------------------------------------- /employee_birthday.csv: -------------------------------------------------------------------------------- 1 | name,department,birthday month 2 | John Smith,Accounting,Novermber 3 | Erica Meyers,IT,March 4 | Jennifer maik,Math,June 5 | -------------------------------------------------------------------------------- /employee_birthday.txt: -------------------------------------------------------------------------------- 1 | name,department,birthday month 2 | John Smith,Accounting,November 3 | Erica Meyers,IT,March 4 | Jennifer maik,Math,June 5 | -------------------------------------------------------------------------------- /employees.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | Negan 4 | 40 5 | imnegan@twd.com 6 |
7 | Chicago 8 | Illinois 9 | 35245 10 | Near hill top 11 |
12 |
13 | 14 | Louis 15 | 24 16 | talktolouis@twd.com 17 |
18 | Ashburn 19 | Virginia 20 | 125445 21 | Near hill top 22 |
23 |
24 | 25 | Chan 26 | 33 27 | chantalks@twd.com 28 |
29 | Little Rock 30 | Arkansas 31 | 201301 32 | Near hill top 33 |
34 |
35 |
36 | -------------------------------------------------------------------------------- /temperature.csv: -------------------------------------------------------------------------------- 1 | 08:00:00,27.9 2 | 08:10:00,11.4 3 | 08:20:00,26.4 4 | 08:22:00,23.7 5 | 08:24:00,28 6 | 08:40:00,13 7 | 08:50:00,16.7 8 | 09:00:00,15.1 9 | 09:10:00,12.3 10 | 09:20:00,22.3 11 | 09:30:00,13.5 12 | 09:40:00,18.8 13 | 09:50:00,19 14 | 10:00:00,18.3 15 | 10:10:00,20.5 16 | 10:20:00,10.4 17 | 10:30:00,13.6 18 | --------------------------------------------------------------------------------