├── test1.txt ├── test2.txt ├── test.txt ├── img_1.png ├── city.py ├── test3.txt ├── file_handling_write.py ├── output.csv ├── stocks.csv ├── city_module.py ├── test4.txt ├── File_Handling_Read.py ├── palindrome.py ├── classes_and_objects.py ├── Task.md ├── robot_and_person_class.py ├── README.md ├── poem.txt ├── CeaserCipher.py ├── file_Handling_Read_write.py ├── calculator.py ├── Calculator_Class.py ├── class_Instances.py ├── Classes.py ├── Modules.py ├── Scope_Of_Variable.py ├── Conditional_Statements.py ├── Exception.py ├── while loop.py ├── Functions_2.py ├── Inheritence.py ├── classes_2.py ├── Class_Excercise.py ├── Iterative_Statements.py ├── functions.py └── function and classes.py /test1.txt: -------------------------------------------------------------------------------- 1 | I Love Pakistan -------------------------------------------------------------------------------- /test2.txt: -------------------------------------------------------------------------------- 1 | I Love PakistanI Love Python 2 | I Love Python -------------------------------------------------------------------------------- /test.txt: -------------------------------------------------------------------------------- 1 | my first file 2 | This file 3 | 4 | contains three lines 5 | -------------------------------------------------------------------------------- /img_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SajidMajeed92/Python-101/main/img_1.png -------------------------------------------------------------------------------- /city.py: -------------------------------------------------------------------------------- 1 | cities_list = ['Karachi', 'Lahore', 'Islamabad', 'Gujrawala', 'Hyderabad'] 2 | -------------------------------------------------------------------------------- /test3.txt: -------------------------------------------------------------------------------- 1 | Teacher : Why are you late , Ahsan? 2 | Ahsan : Because of the sign. 3 | Teacher : What sign? 4 | Ahsan: The one that says "School Ahead, Go Slow" -------------------------------------------------------------------------------- /file_handling_write.py: -------------------------------------------------------------------------------- 1 | with open("test.txt",'w',encoding = 'utf-8') as f: 2 | f.write("my first file\n") 3 | f.write("This file\n\n") 4 | f.write("contains three lines\n") -------------------------------------------------------------------------------- /output.csv: -------------------------------------------------------------------------------- 1 | Company Name,PE Ratio, PB Ratio 2 | Reliance,22.23,2.25 3 | Tata Steel,4.39,0.68 4 | Infosys,18.57,4.42 5 | Axis Bank,38.89,2.81 6 | Bajaj Finance,58.61,11.86 7 | -------------------------------------------------------------------------------- /stocks.csv: -------------------------------------------------------------------------------- 1 | Company Name,Price,Earnings Per Share,Book Value 2 | Reliance,1467,66,653 3 | Tata Steel,391,89,572 4 | Infosys,650,35,147 5 | Axis Bank,739,19,263 6 | Bajaj Finance,4044,69,341 7 | -------------------------------------------------------------------------------- /city_module.py: -------------------------------------------------------------------------------- 1 | import city 2 | 3 | # access first city 4 | city_name = city.cities_list[1] 5 | print("Accessing 1st city:", city_name) 6 | 7 | # Get all cities 8 | cities = city.cities_list 9 | print("Accessing All cities :", cities) -------------------------------------------------------------------------------- /test4.txt: -------------------------------------------------------------------------------- 1 | 2 | Teacher : Why are you late , Ahsan? 3 | word count: 8 4 | Ahsan : Because of the sign. 5 | word count: 6 6 | Teacher : What sign? 7 | word count: 4 8 | Ahsan: The one that says "School Ahead, Go Slow"word count: 9 -------------------------------------------------------------------------------- /File_Handling_Read.py: -------------------------------------------------------------------------------- 1 | # f = open("C:/Python38/README.txt") # specifying full path 2 | # Example 3 | f = open("data.txt", "r") 4 | content = f.read() 5 | print(content) 6 | f.close() 7 | 8 | # Another way to write the above example 9 | with open("data.txt", "r") as f: 10 | content = f.read() 11 | print(content) 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /palindrome.py: -------------------------------------------------------------------------------- 1 | # program 1 2 | def isPalindrome(x): 3 | for i in range(0, int(len(x)/2)): 4 | if x[i] != x[len(x)-i-1]: 5 | return False 6 | return True 7 | 8 | input1 = input('Enter string : ') 9 | result = isPalindrome(input1) 10 | if(result): 11 | print(input1, 'is a Palindrome.') 12 | else: 13 | print(input1, 'is not a Palindrome.') 14 | 15 | # Program 2 16 | def is_palindrome(s): 17 | return s == s[::-1] 18 | 19 | print(is_palindrome("racecar")) # True 20 | print(is_palindrome("hello")) # False -------------------------------------------------------------------------------- /classes_and_objects.py: -------------------------------------------------------------------------------- 1 | class Robot: 2 | def __init__(self, name, color, weight): 3 | self.name = name 4 | self.color = color 5 | self.weight = weight 6 | 7 | def introduce_self(self): 8 | print("My name is " + self.name) 9 | 10 | # r1 = Robot() 11 | # r1.name = "Tom" 12 | # r1.color = "red" 13 | # r1.weight = 30 14 | # 15 | # r2 = Robot() 16 | # r2.name = "Jerry" 17 | # r2.color = "blue" 18 | # r2.weight = 40 19 | 20 | r1 = Robot("Tom", "red", 30) 21 | r2 = Robot("Jerry", "blue", 40) 22 | 23 | r1.introduce_self() 24 | r2.introduce_self() -------------------------------------------------------------------------------- /Task.md: -------------------------------------------------------------------------------- 1 | Exercise: Python Read Write File 2 | poem.txt contains famous poem "Road not taken" by poet Robert Frost. You have to read this file in your python program and find out words with maximum occurance. 3 | Solution 4 | 5 | stocks.csv contains stock price, earnings per share and book value. You are writing a stock market application that will process this file and create a new file with financial metrics such as pe ratio and price to book ratio. These are calculated as, 6 | pe ratio = price / earnings per share 7 | price to book ratio = price / book value 8 | 9 | ![img_1.png](img_1.png) -------------------------------------------------------------------------------- /robot_and_person_class.py: -------------------------------------------------------------------------------- 1 | class Robot: 2 | def __init__(self, n, c, w): 3 | self.name = n 4 | self.color = c 5 | self.weight = w 6 | 7 | def introduce_self(self): 8 | print("My name is " + self.name) 9 | 10 | 11 | class Person: 12 | def __init__(self, n, p, i): 13 | self.name = n 14 | self.personality = p 15 | self.isSitting = i 16 | 17 | def sit_down(self): 18 | print("My name is " + self.name) 19 | 20 | 21 | r1 = Robot("Tom", "red", 30) 22 | r2 = Robot("Jerry", "blue", 40) 23 | 24 | p1 = Person("Alice", "aggressive", False) 25 | p2 = Person("Becky", "aggressive", True) 26 | 27 | p1.robot_owned = r2 28 | p2.robot_owned = r1 29 | 30 | 31 | p1.robot_owned.introduce_self() 32 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python-101 2 | **Learn Python Programming** 3 | 4 | Python is a **general-purpose, mordern, dynamic, robust, high level** and **interpreted** programming language. It is used in web development, data science, creating software prototypes, and so on. Fortunately for beginners, Python has simple easy-to-use syntax. This makes Python an excellent language to learn to program for beginners. 5 | 6 | **About Python Programming** 7 | 8 | * **Free and open-source** - You can freely use and distribute Python, even for commercial use. 9 | * **Easy to learn** - Python has a very simple and elegant syntax. It's much easier to read and write Python programs compared to other languages like C++, Java, C#. 10 | * **Portable -** You can move Python programs from one platform to another, and run it without any changes. 11 | -------------------------------------------------------------------------------- /poem.txt: -------------------------------------------------------------------------------- 1 | Two roads diverged in a yellow wood, 2 | And sorry I could not travel both 3 | And be one traveler, long I stood 4 | And looked down one as far as I could 5 | To where it bent in the undergrowth; 6 | 7 | Then took the other, as just as fair, 8 | And having perhaps the better claim, 9 | Because it was grassy and wanted wear; 10 | Though as for that the passing there 11 | Had worn them really about the same, 12 | 13 | And both that morning equally lay 14 | In leaves no step had trodden black. 15 | Oh, I kept the first for another day! 16 | Yet knowing how way leads on to way, 17 | I doubted if I should ever come back. 18 | 19 | I shall be telling this with a sigh 20 | Somewhere ages and ages hence: 21 | Two roads diverged in a wood, and I— 22 | I took the one less traveled by, 23 | And that has made all the difference. -------------------------------------------------------------------------------- /CeaserCipher.py: -------------------------------------------------------------------------------- 1 | def encrypt_text(plaintext, n): 2 | ans = "" 3 | # iterate over the given text 4 | for i in range(len(plaintext)): 5 | ch = plaintext[i] 6 | 7 | # check if space is there then simply add space 8 | if ch == " ": 9 | ans += " " 10 | # check if a character is uppercase then encrypt it accordingly 11 | elif (ch.isupper()): 12 | ans += chr((ord(ch) + n - 65) % 26 + 65) 13 | # check if a character is lowercase then encrypt it accordingly 14 | 15 | else: 16 | ans += chr((ord(ch) + n - 97) % 26 + 97) 17 | 18 | return ans 19 | 20 | 21 | plaintext = input("Enter your Phrase here: ") 22 | n = int(input("Enter the number of n: ")) 23 | print("Plain Text is : " + plaintext) 24 | print("Shift pattern is : " + str(n)) 25 | print("Cipher Text is : " + encrypt_text(plaintext, n)) 26 | 27 | -------------------------------------------------------------------------------- /file_Handling_Read_write.py: -------------------------------------------------------------------------------- 1 | f=open("test1.txt","w") 2 | f.write("I Love Pakistan") 3 | f.close() 4 | 5 | f=open("test2.txt","a") 6 | f.write("\n I Love Python") 7 | f.close() 8 | 9 | f=open("test3.txt","r") 10 | print(f.read()) 11 | f.close() 12 | 13 | f=open("test3.txt","r") 14 | for line in f: 15 | print(line) 16 | f.close() 17 | 18 | 19 | 20 | with open("stocks.csv", "r") as f, open("output.csv", "w") as out: 21 | out.write("Company Name,PE Ratio, PB Ratio\n") 22 | next(f) # This will skip first line in the file which is a header 23 | for line in f: 24 | tokens = line.split(",") 25 | stock = tokens[0] 26 | price = float(tokens[1]) 27 | eps = float(tokens[2]) 28 | book = float(tokens[3]) 29 | pe = round(price / eps, 2) 30 | pb = round(price / book, 2) 31 | out.write(f"{stock},{pe},{pb}\n") -------------------------------------------------------------------------------- /calculator.py: -------------------------------------------------------------------------------- 1 | class Calculator: 2 | 3 | def addition(self): 4 | print(a + b) 5 | 6 | def subtraction(self): 7 | print(a - b) 8 | 9 | def multiplication(self): 10 | print(a * b) 11 | 12 | def division(self): 13 | print(a / b) 14 | a = int(input("Enter first number:")) 15 | b = int(input("Enter first number:")) 16 | 17 | obj = Calculator() 18 | choice = 1 19 | while choice != 0: 20 | print("1. ADD") 21 | print("2. SUB") 22 | print("3. MUL") 23 | print("4. DIV") 24 | choice = int(input("Enter your choice:")) 25 | 26 | if choice == 1: 27 | print(obj.addition()) 28 | elif choice == 2: 29 | print(obj.subtraction()) 30 | elif choice == 3: 31 | print(obj.multiplication()) 32 | elif choice == 4: 33 | print(obj.division()) 34 | else: 35 | print("Invalid choice") -------------------------------------------------------------------------------- /Calculator_Class.py: -------------------------------------------------------------------------------- 1 | class Calculator: 2 | 3 | def addition(self): 4 | print(a + b) 5 | 6 | def subtraction(self): 7 | print(a - b) 8 | 9 | def multiplication(self): 10 | print(a * b) 11 | 12 | def division(self): 13 | print(a / b) 14 | a = int(input("Enter first number:")) 15 | b = int(input("Enter first number:")) 16 | 17 | obj = Calculator() 18 | choice = 1 19 | while choice != 0: 20 | print("1. ADD") 21 | print("2. SUB") 22 | print("3. MUL") 23 | print("4. DIV") 24 | choice = int(input("Enter your choice:")) 25 | 26 | if choice == 1: 27 | print(obj.addition()) 28 | elif choice == 2: 29 | print(obj.subtraction()) 30 | elif choice == 3: 31 | print(obj.multiplication()) 32 | elif choice == 4: 33 | print(obj.division()) 34 | else: 35 | print("Invalid choice") -------------------------------------------------------------------------------- /class_Instances.py: -------------------------------------------------------------------------------- 1 | class Employee: 2 | pass 3 | emp_1=Employee() 4 | emp_2=Employee() 5 | 6 | print (emp_1) 7 | print(emp_2) 8 | 9 | emp_1.first='Ahsan' 10 | emp_1.last='Ali' 11 | emp_1.email='Ahsan.ali@company.com' 12 | emp_1.pay=5000 13 | 14 | emp_2.first='Abdur' 15 | emp_2.last='Rehman' 16 | emp_2.email='Abdur.Rehman@company.com' 17 | emp_2.pay=15000 18 | 19 | print (emp_1.first) 20 | print (emp_2.first) 21 | print (emp_1.email) 22 | print (emp_2.email) 23 | 24 | 25 | class Employee: 26 | 27 | def __init__(self, first, last, pay): 28 | self.first = first 29 | self.last = last 30 | self.email = first + '.' + last + '@email.com' 31 | self.pay = pay 32 | 33 | def fullname(self): 34 | return '{} {}'.format(self.first, self.last) 35 | 36 | emp_1 = Employee('Corey', 'Schafer', 50000) 37 | emp_2 = Employee('Test', 'Employee', 60000) 38 | 39 | print (emp_1) 40 | print(emp_2) -------------------------------------------------------------------------------- /Classes.py: -------------------------------------------------------------------------------- 1 | # Create a Class in Python 2 | # class class_name: 3 | # '''This is a docstring. I have created a new class''' 4 | # 5 | # 6 | # . 7 | # . 8 | # 9 | 10 | class Person: 11 | def __init__(self, name, gender, profession): 12 | # data members (instance variables) 13 | self.name = name 14 | self.gender = gender 15 | self.profession = profession 16 | 17 | # Behavior (instance methods) 18 | def show(self): 19 | print('Name:', self.name, 'Gender:', self.gender, 'Profession:', self.profession) 20 | 21 | # Behavior (instance methods) 22 | def work(self): 23 | print(self.name, 'working as a', self.profession) 24 | 25 | 26 | # create object of a class 27 | Ali = Person('Ali', 'Male', 'Software Engineer') 28 | Ahmed = Person('Ahmed', 'Male', 'Computer Engineer') 29 | 30 | # call methods 31 | Ali.show() 32 | Ali.work() 33 | Ahmed.show() 34 | Ahmed.work() 35 | 36 | -------------------------------------------------------------------------------- /Modules.py: -------------------------------------------------------------------------------- 1 | import math 2 | import random 3 | 4 | number = 25 5 | result = math.sqrt(number) 6 | print(result) 7 | print(math.pi) 8 | 9 | import math as m 10 | 11 | number = 25 12 | result = m.sqrt(number) 13 | print(result) 14 | 15 | print(m.pi) 16 | from math import sqrt 17 | 18 | num = sqrt(64) 19 | print(num) 20 | 21 | from math import pi, sin, sqrt 22 | 23 | value = sin(pi / 2) 24 | print(value) 25 | 26 | num = sqrt(64) 27 | print(num) 28 | 29 | from math import * 30 | 31 | value = sin(pi / 2) 32 | print(value) 33 | 34 | num = sqrt(64) 35 | print(num) 36 | 37 | import math 38 | 39 | print(dir(math)) 40 | 41 | print(math.factorial(5)) 42 | print(random.randint(10, 20)) 43 | 44 | import datetime 45 | 46 | 47 | x = datetime.datetime.now() 48 | print(x) 49 | x = pow(4, 3) 50 | print(x) 51 | 52 | x = math.ceil(1.4) 53 | y = math.floor(1.4) 54 | print(x) # returns 2 55 | print(y) # returns 1 56 | 57 | import time 58 | timenow = time.localtime(time.time()) 59 | year,month,day,hour,minute = timenow[0:5] 60 | 61 | print(str(day) + "/" + str(month) + "/" + str(year)) 62 | print(str(hour) + ":" + str(minute)) 63 | 64 | a = float(input("Enter the length of side a: ")) 65 | b = float(input("Enter the length of side b: ")) 66 | c = float(input("Enter the length of side c: ")) 67 | s = (a + b + c) / 2 68 | area = math.sqrt(s * (s - a) * (s - b) * (s - c)) 69 | print(" Area of the triangle is: ", area) 70 | -------------------------------------------------------------------------------- /Scope_Of_Variable.py: -------------------------------------------------------------------------------- 1 | # A variable scope specifies the region where we can access a variable. 2 | # Based on the scope, we can classify Python variables into three types: 3 | 4 | # Local Variables 5 | # Global Variables 6 | # Nonlocal Variables 7 | # 8 | # Python Local Variables 9 | # When we declare variables inside a function, these variables will have a local scope (within the function). 10 | # We cannot access them outside the function. 11 | 12 | def greet(): 13 | name = 'Muhammad' 14 | print('Hello ', name) 15 | 16 | 17 | greet() 18 | # print(name) 19 | 20 | 21 | num = 0 22 | 23 | 24 | def demo(): 25 | # print(num) 26 | num = 1 27 | print("The Number is:", num) 28 | 29 | 30 | demo() 31 | print(num) 32 | 33 | # Python Global Variables 34 | # In Python, a variable declared outside of the function or in global scope is known as a global variable. 35 | # This means that a global variable can be accessed inside or outside of the function. 36 | 37 | # declare global variable 38 | message = 'Hello' 39 | 40 | 41 | def greet(): 42 | # declare local variable 43 | print('Local', message) 44 | 45 | 46 | greet() 47 | print('Global', message) 48 | 49 | greeting = "Hello" 50 | 51 | 52 | def change_greeting(new_greeting): 53 | global greeting 54 | greeting = new_greeting 55 | 56 | 57 | def greeting_world(): 58 | world = "World" 59 | print(greeting, world) 60 | 61 | 62 | change_greeting("Hi") 63 | greeting_world() 64 | 65 | 66 | # NonLocal or Enclosing Scope 67 | 68 | # Nonlocal Variable is the variable that is defined in the nested function. 69 | # It means the variable can be neither in the local scope nor in the global scope. 70 | # To create a nonlocal variable nonlocal keyword is used. 71 | # In the following code, we created an outer function, and there is a nested function inner(). 72 | # In the scope of outer() function inner() function is defined. 73 | # If we change the nonlocal variable as defined in the inner() function, then changes are reflected in the outer function. 74 | 75 | 76 | def outer(): 77 | first_num = 1 78 | 79 | def inner(): 80 | nonlocal first_num 81 | first_num = 0 82 | second_num = 1 83 | print("inner - second_num is: ", second_num) 84 | 85 | inner() 86 | print("outer - first_num is: ", first_num) 87 | 88 | 89 | outer() 90 | -------------------------------------------------------------------------------- /Conditional_Statements.py: -------------------------------------------------------------------------------- 1 | # python program to illustrate If statement 2 | i = 10 3 | if (i > 15): 4 | print("10 is less than 15") 5 | print("I am Not in if") 6 | 7 | # python program to illustrate If else statement 8 | i = 20 9 | if (i < 15): 10 | print ("i is Smaller than 15") 11 | print ("i'm in if Block") 12 | else: 13 | print("i is Greater than 15") 14 | print("i'm in else Block") 15 | print("I'm not in if and not in else Block") 16 | 17 | # python program to illustrate nested If statement 18 | i = 10 19 | if (i == 10): 20 | # First if statement 21 | if (i < 15): 22 | print("i is smaller than 15") 23 | # Nested - if statement 24 | # Will only be executed if statement above 25 | # it is true 26 | if (i < 12): 27 | print("i is smaller than 12 too") 28 | else: 29 | print("i is greater than 15") 30 | 31 | # A school has following rules for Grading System: 32 | # a. Below 25 - F 33 | # b. 25 to 45 - E 34 | # c. 45 to 50 - D 35 | # d. 50 to 60 - C 36 | # e. 60 to 80 - B 37 | # f. Above 80 - A 38 | # Ask user to enter Marks and print the corresponding Grade. 39 | 40 | marks = input("Enter Your Marks:") 41 | if marks<25: 42 | print "F" 43 | elif marks>=25 and marks<45: 44 | print "E" 45 | elif marks>=45 and marks<50: 46 | print "D" 47 | elif marks>=50 and marks<60: 48 | print "C" 49 | elif marks>=60 and marks<80: 50 | print "B" 51 | else: 52 | print "A" 53 | 54 | #Take values of length and breadth of a rectangle from user and check if it is square or not. 55 | 56 | print "Enter length" 57 | length = input() 58 | print "Enter breadth" 59 | breadth = input() 60 | if length == breadth: 61 | print "Yes, it is square" 62 | else: 63 | print "No, it is only Rectangle" 64 | 65 | 66 | #Take input of age of 3 people by user and determine oldest and youngest among them. 67 | 68 | first_person_age = input("Enter first person age:") 69 | second_person_age = input("Enter Second person age:") 70 | third_person_age = input("Enter third person age:") 71 | 72 | if first_person_age >= second_person_age and first_person_age >= third_person_age: 73 | print "Oldest is",first_person_age 74 | elif second_person_age >= first_person_age and second_person_age >= third_person_age: 75 | print "Oldest is",second_person_age 76 | elif third_person_age >= first_person_age and third_person_age >= second_person_age: 77 | print "Oldest is",third_person_age 78 | else: 79 | print "All are equal" 80 | #Check you are Eligible for vote 81 | age = input("Enter Your age:") 82 | if age>=18: 83 | print("Eligible for Vote") 84 | else: 85 | print("Not Eligible for Vote") -------------------------------------------------------------------------------- /Exception.py: -------------------------------------------------------------------------------- 1 | # try: 2 | # # code that may cause exception 3 | # except: 4 | # # code to run when exception occurs 5 | try: 6 | numerator = 10 7 | denominator = 0 8 | 9 | result = numerator/denominator 10 | 11 | print(result) 12 | except: 13 | print("Error: Denominator cannot be 0.") 14 | 15 | # Output: Error: Denominator cannot be 0. 16 | 17 | try: 18 | 19 | even_numbers = [2, 4, 6, 8] 20 | print(even_numbers[5]) 21 | 22 | except ZeroDivisionError: 23 | print("Denominator cannot be 0.") 24 | 25 | except IndexError: 26 | print("Index Out of Bound.") 27 | 28 | # Python try...finally 29 | # In Python, the finally block is always executed no matter whether there is an exception or not. 30 | # The finally block is optional. And, for each try block, there can be only one finally block. 31 | try: 32 | numerator = 10 33 | denominator = 0 34 | 35 | result = numerator / denominator 36 | 37 | print(result) 38 | except: 39 | print("Error: Denominator cannot be 0.") 40 | 41 | finally: 42 | print("This is finally block.") 43 | 44 | # Example for Exceptional Handling 45 | a = 5 46 | b = 2 47 | 48 | try: 49 | print("resource Open") 50 | print(a/b) 51 | k = int(input("Enter a number")) 52 | print(k) 53 | 54 | except ZeroDivisionError as e: 55 | print("Hey, You cannot divide a Number by Zero" , e) 56 | 57 | except ValueError as e: 58 | print("Invalid Input") 59 | 60 | except Exception as e: 61 | print("Something went Wrong...") 62 | 63 | finally: 64 | print("resource Closed") 65 | 66 | # Example 67 | try: 68 | print('try block') 69 | x=int(input('Enter a number: ')) 70 | y=int(input('Enter another number: ')) 71 | z=x/y 72 | except ZeroDivisionError: 73 | print("except ZeroDivisionError block") 74 | print("Division by 0 not accepted") 75 | else: 76 | print("else block") 77 | print("Division = ", z) 78 | finally: 79 | print("finally block") 80 | x=0 81 | y=0 82 | print ("Out of try, except, else and finally blocks." ) 83 | 84 | # Example with function 85 | 86 | def simple_interest(amount, year, rate): 87 | try: 88 | if rate > 100: 89 | raise ValueError(rate) 90 | interest = (amount * year * rate) / 100 91 | print('The Simple Interest is', interest) 92 | return interest 93 | except ValueError: 94 | print('interest rate is out of range', rate) 95 | 96 | print('Case 1') 97 | simple_interest(800, 6, 8) 98 | 99 | print('Case 2') 100 | simple_interest(800, 6, 800) -------------------------------------------------------------------------------- /while loop.py: -------------------------------------------------------------------------------- 1 | # Practice Question 1: Using the while loop, print the square and cube of all numbers between 10 and 20 (included).Your output should look like this: “The square of 10 is 100. The cube of 10 is 1000.” 2 | # x = 9 3 | # while x < 20: 4 | # x = x+1 5 | # print(f"The square of {x} is {x*x} and cube of {x} is {x*x*x}") 6 | # Practice Question 2: Ask the user for their favorite month of the year, favorite number, and favorite animal. Create a passcode that is a concatenation of the three strings, for example “may4cat”. Using the while loop, ask the user to enter the correct passcode. The user should be allowed to proceed only when the correct passcode is entered. 7 | # month = input("What is your favorite month of the year?") 8 | # number = input("What is your favorite number?") 9 | # animal = input("What is your favorite animal?") 10 | # print(f" Your Password is the concatenation of the three answer that you gave") 11 | # password = month + number + animal 12 | # guess = 0 13 | # while guess != password: 14 | # guess = input("Enter your password to proceed") 15 | # print("Password accepted") 16 | 17 | # Practice Question 3: Using the while loop, produce the following output: 18 | # 19 | # * 20 | # ** 21 | # *** 22 | # **** 23 | # *** 24 | # ** 25 | # * 26 | # 27 | # x = 0 28 | # while x < 4: 29 | # x = x+1 30 | # print("*" * x) 31 | # while x > 1: 32 | # x = x-1 33 | # print("*" * x) 34 | 35 | # Practice Question 4: Using the while loop, produce the following output (which should look like rhombus). 36 | # 37 | # * 38 | # * * 39 | # * * * 40 | # * * * * 41 | # * * * 42 | # * * 43 | # * 44 | # 45 | # x = 0 46 | # while x < 4: 47 | # x = x+1 48 | # print(" " * (4 - x) + "*" * x) 49 | # while x > 1: 50 | # x = x-1 51 | # print(" " * (4 - x) + "*" * x) 52 | 53 | # Practice Question 5 : Ask the user to enter two integers. Then ask the user to calculate the product of the two integers. The user has three attempts to give a correct answer. If the correct answer is not given the program terminates providing a correct answer to the user. Program requirements: 54 | # - Do not use IF statements. 55 | # - Implement error handling for all user input (initial numbers and the product). 56 | # - Use the while loop for getting the correct initial input. 57 | # - Use the while loop for getting the correct solution (also remember the maximum of three attempts). 58 | while True: 59 | a = input("Enter First Integer") 60 | b = input("Enter Second Integer") 61 | max_attempts = 3 62 | try: 63 | a, b = int(a), int(b) 64 | except: 65 | print("Incorrect Input") 66 | continue 67 | else: 68 | break 69 | guess = 0 70 | attempts = 0 71 | while guess != (a*b) and attempts <3: 72 | attempts = attempts+1 73 | while True: 74 | guess = input(f"Attempts #{attempts}.what is {a}*{b}?") 75 | try: 76 | guess = int(guess) 77 | except: 78 | print("Incorrect Input") 79 | continue 80 | else: 81 | break 82 | print(f"Your answer is {guess}. Correct answer is {a*b}") 83 | 84 | 85 | -------------------------------------------------------------------------------- /Functions_2.py: -------------------------------------------------------------------------------- 1 | # We can define the User defined functions in multiple ways. 2 | # The following are the list of available types of functions in Python. 3 | 4 | # With no argument and no return value. 5 | # With no argument and with a Return value. 6 | # Argument and No Return value. 7 | # With argument and return value. 8 | 9 | # Types of Functions in Python 10 | # **Python Function with No argument and No Return value** 11 | # With No Arguments, and No Return Value 12 | 13 | def Adding(): 14 | a = 20 15 | b = 30 16 | Sum = a + b 17 | print("After Calling :", Sum) 18 | 19 | 20 | Adding() 21 | 22 | 23 | # ** Python Function with no argument and with a Return value** 24 | # No arguments and with a Return value Example 25 | # With No Arguments, and with Return Value 26 | 27 | def Multiplication(): 28 | a = 10 29 | b = 25 30 | Multi = a * b 31 | return Multi 32 | 33 | 34 | print("After Calling the Multiplication : ", Multiplication()) 35 | 36 | 37 | # **Python Function with argument and No Return value** 38 | # With Arguments, and NO Return Value 39 | 40 | def Multiplications(a, b): 41 | Multi = a * b 42 | print("After Calling the Function:", Multi) 43 | 44 | 45 | Multiplications(10, 20) 46 | 47 | 48 | # **Python Function with argument and Return value** 49 | # With Arguments, and Return Value 50 | 51 | def Addition(a, b): 52 | Sum = a + b 53 | return Sum 54 | 55 | 56 | # We are calling it Outside the Definition 57 | print("After Calling :", Addition(25, 45)) 58 | 59 | 60 | # Example: Parameterized Function 61 | def greet(name): 62 | print('Hello ', name) 63 | 64 | 65 | greet('Ahmed') # calling function with argument 66 | greet(123) 67 | 68 | 69 | # Multiple Parameters 70 | def greet(name1, name2, name3): 71 | print('Hello', name1, ',', name2, ', and ', name3) 72 | 73 | 74 | greet('Steve', 'Bill', 'Yash') # calling function with string argument 75 | 76 | 77 | # Unknown Number of Arguments 78 | def greet1(*names): 79 | print('Hello ', names[0], ', ', names[1], ', ', names[2]) 80 | 81 | 82 | greet1('Ahsan', 'Bilal', 'Sarim') 83 | 84 | 85 | # The following function works with any number of arguments. 86 | def greet(*names): 87 | i = 0 88 | print('Hello ', end='') 89 | while len(names) > i: 90 | print(names[i], end=', ') 91 | i += 1 92 | 93 | 94 | greet('Ahsan', 'Bilal', 'Sarim') 95 | greet('Steve', 'Bill', 'Yash', 'Kapil', 'John', 'Amir') 96 | 97 | 98 | # Function with Keyword Arguments 99 | # In order to call a function with arguments, the same number of actual arguments must be provided. 100 | # However, a function can be called by passing parameter values using the parameter names in any order. 101 | # For example, the following passes values using the parameter names. 102 | 103 | def greet(firstname, lastname): 104 | print('Hello', firstname, lastname) 105 | 106 | 107 | greet(lastname='Jobs', firstname='Ahmed') # passing parameters in any order using keyword argument 108 | 109 | 110 | # Keyword Argument **kwarg 111 | def greet(**person): 112 | print('Hello ', person['firstname'], person['lastname'], person['age']) 113 | 114 | 115 | greet(firstname='Steve', lastname='Jobs', age=60) 116 | greet(lastname='Jobs', firstname='Steve', age=60) 117 | greet(firstname='Bill', lastname='Gates', age=55) 118 | greet(firstname='Bill', lastname='Gates', age=55) 119 | -------------------------------------------------------------------------------- /Inheritence.py: -------------------------------------------------------------------------------- 1 | # The process of inheriting the properties of the parent class into a child class is called inheritance. 2 | # The existing class is called a base class or parent class and the new class is called a subclass or child class or derived class. 3 | # In Object-oriented programming, inheritance is an important aspect. The main purpose of inheritance is the re-usability of code because we can use the existing class to create a new class instead of creating it from scratch. 4 | # In inheritance, the child class acquires all the data members, properties, and functions from the parent class. Also, a child class can also provide its specific implementation to the methods of the parent class. 5 | 6 | 7 | # Example : Let’s create one parent class called ClassOne and one child class called ClassTwo to implement single inheritance. 8 | # Base class 9 | # Single Inheritance 10 | class Vehicle: 11 | def Vehicle_info(self): 12 | print('Inside Vehicle class') 13 | 14 | 15 | # Child class 16 | class Car(Vehicle): 17 | def car_info(self): 18 | print('Inside Car class') 19 | 20 | 21 | # Create object of Car 22 | car = Car() 23 | 24 | # access Vehicle's info using car object 25 | car.Vehicle_info() 26 | car.car_info() 27 | 28 | 29 | # Multiple Inheritance 30 | # Parent class 1 31 | class Person: 32 | def person_info(self, name, age): 33 | print('Inside Person class') 34 | print('Name:', name, 'Age:', age) 35 | 36 | 37 | # Parent class 2 38 | class Company: 39 | def company_info(self, company_name, location): 40 | print('Inside Company class') 41 | print('Name:', company_name, 'location:', location) 42 | 43 | 44 | # Child class 45 | class Employee(Person, Company): 46 | def Employee_info(self, salary, skill): 47 | print('Inside Employee class') 48 | print('Salary:', salary, 'Skill:', skill) 49 | 50 | 51 | # Create object of Employee 52 | emp = Employee() 53 | 54 | # access data 55 | emp.person_info('Ali', 28) 56 | emp.company_info('Google', 'Atlanta') 57 | emp.Employee_info(12000, 'Machine Learning') 58 | 59 | 60 | # Multiple Inheritance 61 | # Base class 62 | class Vehicle: 63 | def Vehicle_info(self): 64 | print('Inside Vehicle class') 65 | 66 | 67 | # Child class 68 | class Car(Vehicle): 69 | def car_info(self): 70 | print('Inside Car class') 71 | 72 | 73 | # Child class 74 | class SportsCar(Car): 75 | def sports_car_info(self): 76 | print('Inside SportsCar class') 77 | 78 | 79 | # Create object of SportsCar 80 | s_car = SportsCar() 81 | 82 | # access Vehicle's and Car info using SportsCar object 83 | s_car.Vehicle_info() 84 | s_car.car_info() 85 | s_car.sports_car_info() 86 | 87 | 88 | # Hierarchical Inheritance 89 | # Example : Let’s create ‘Vehicle’ as a parent class and two child class ‘Car’ and ‘Truck’ as a parent class. 90 | class Vehicle: 91 | def info(self): 92 | print("This is Vehicle") 93 | 94 | 95 | class Car(Vehicle): 96 | def car_info(self, name): 97 | print("Car name is:", name) 98 | 99 | 100 | class Truck(Vehicle): 101 | def truck_info(self, name): 102 | print("Truck name is:", name) 103 | 104 | 105 | obj1 = Car() 106 | obj1.info() 107 | obj1.car_info('BMW') 108 | 109 | obj2 = Truck() 110 | obj2.info() 111 | obj2.truck_info('Ford') 112 | 113 | 114 | # Example 2: 115 | class Vehicle: 116 | def vehicle_info(self): 117 | print("Inside Vehicle class") 118 | 119 | 120 | class Car(Vehicle): 121 | def car_info(self): 122 | print("Inside Car class") 123 | 124 | 125 | class Truck(Vehicle): 126 | def truck_info(self): 127 | print("Inside Truck class") 128 | 129 | 130 | # Sports Car can inherit properties of Vehicle and Car 131 | class SportsCar(Car, Vehicle): 132 | def sports_car_info(self): 133 | print("Inside SportsCar class") 134 | 135 | 136 | # create object 137 | s_car = SportsCar() 138 | 139 | s_car.vehicle_info() 140 | s_car.car_info() 141 | s_car.sports_car_info() 142 | -------------------------------------------------------------------------------- /classes_2.py: -------------------------------------------------------------------------------- 1 | # Class Attributes 2 | # 3 | # When we design a class, we use instance variables and class variables. 4 | # In Class, attributes can be defined into two parts: 5 | # 6 | # Instance variables: The instance variables are attributes attached to an instance of a class. 7 | # We define instance variables in the constructor ( the __init__() method of a class). 8 | # 9 | # Class Variables: A class variable is a variable that is declared inside of class, but outside of any instance method or __init__() method. 10 | 11 | class Student: 12 | # class variables 13 | school_name = 'ABC School' 14 | 15 | # constructor 16 | def __init__(self, name, age): 17 | # instance variables 18 | self.name = name 19 | self.age = age 20 | 21 | 22 | s1 = Student("Ahmed", 12) 23 | # access instance variables 24 | print('Student:', s1.name, s1.age) 25 | 26 | # access class variable 27 | print('School name:', Student.school_name) 28 | 29 | # Modify instance variables 30 | s1.name = 'Ali' 31 | s1.age = 14 32 | print('Student:', s1.name, s1.age) 33 | 34 | # Modify class variables 35 | Student.school_name = 'XYZ School' 36 | print('School name:', Student.school_name) 37 | 38 | 39 | # 40 | # Class Methods 41 | # 42 | # Instance method: Used to access or modify the object state. If we use instance variables inside a method, such methods are called instance methods. 43 | # Class method: Used to access or modify the class state. In method implementation, if we use only class variables, then such type of methods we should declare as a class method. 44 | # Static method: It is a general utility method that performs a task in isolation. Inside this method, 45 | # we do not use instance or class variable because this static method does not have access to the class attributes. 46 | # 47 | 48 | # class methods demo 49 | class Student: 50 | # class variable 51 | school_name = 'ABC School' 52 | 53 | # constructor 54 | def __init__(self, name, age): 55 | # instance variables 56 | self.name = name 57 | self.age = age 58 | 59 | # instance method 60 | def show(self): 61 | # access instance variables and class variables 62 | print('Student:', self.name, self.age, Student.school_name) 63 | 64 | # instance method 65 | def change_age(self, new_age): 66 | # modify instance variable 67 | self.age = new_age 68 | 69 | # class method 70 | @classmethod 71 | def modify_school_name(cls, new_name): 72 | # modify class variable 73 | cls.school_name = new_name 74 | 75 | 76 | s1 = Student("Harry", 12) 77 | 78 | # call instance methods 79 | s1.show() 80 | s1.change_age(14) 81 | 82 | # call class method 83 | Student.modify_school_name('XYZ School') 84 | # call instance methods 85 | s1.show() 86 | 87 | 88 | # 89 | # Class Naming Convention 90 | # Naming conventions are essential in any programming language for better readability. If we give a sensible name, it will save our time and energy later. Writing readable code is one of the guiding principles of the Python language. 91 | # 92 | # We should follow specific rules while we are deciding a name for the class in Python. 93 | # 94 | # Rule-1: Class names should follow the UpperCaseCamelCase convention 95 | # Rule-2: Exception classes should end in 'Error'. 96 | # Rule-3: If a class is callable (Calling the class from somewhere), in that case, we can give a class name like a function. 97 | # Rule-4: Python has built-in classes are typically lowercase words 98 | 99 | class Fruit: 100 | def __init__(self, name, color): 101 | self.name = name 102 | self.color = color 103 | 104 | def show(self): 105 | print("Fruit is", self.name, "and Color is", self.color) 106 | 107 | 108 | # creating object of the class 109 | obj = Fruit("Apple", "red") 110 | 111 | # Modifying Object Properties 112 | obj.name = "strawberry" 113 | 114 | # calling the instance method using the object obj 115 | obj.show() 116 | 117 | # Output Fruit is strawberry and Color is red 118 | 119 | 120 | # Delete Objects 121 | # In Python, we can also delete the object by using a del keyword. An object can be anything like, class object, list, tuple, set, etc. 122 | class Employee: 123 | department = "IT" 124 | 125 | def show(self): 126 | print("Department is ", self.department) 127 | 128 | 129 | emp = Employee() 130 | emp.show() 131 | 132 | # delete object 133 | del emp 134 | 135 | # Accessing after delete object 136 | emp.show() 137 | # Output : NameError: name 'emp' is not defined 138 | -------------------------------------------------------------------------------- /Class_Excercise.py: -------------------------------------------------------------------------------- 1 | # Write a Python program to create a Vehicle class with max_speed and mileage instance attributes. 2 | class Vehicle: 3 | def __init__(self, max_speed, mileage): 4 | self.max_speed = max_speed 5 | self.mileage = mileage 6 | 7 | 8 | modelX = Vehicle(240, 18) 9 | print("Maximum Speed of Vehicle is :", modelX.max_speed, "\n" "Maximum Mileage given by Vehicle is :", modelX.mileage) 10 | 11 | 12 | # Create a Vehicle class without any variables and methods 13 | class Vehicle: 14 | pass 15 | 16 | 17 | # Define a class that can add and subtract two numbers. 18 | class add_sub: 19 | def __init__(self, x, y): 20 | self.x = x 21 | self.y = y 22 | 23 | # define 'add' method 24 | def add(self): 25 | return self.x + self.y 26 | 27 | # define 'subtract' method 28 | def subtract(self): 29 | return self.x - self.y 30 | 31 | 32 | if __name__ == '__main__': 33 | x = 10 34 | y = 6 35 | # create an instance 36 | opp = add_sub(x, y) 37 | 38 | # call add method 39 | print("The Function return the difference between", x, "and ", y, 'is: ', opp.add()) 40 | 41 | # print(opp.add()) 42 | 43 | # call subtract method 44 | print("The Function return the difference between", x, "and ", y, 'is: ', opp.subtract()) 45 | 46 | 47 | # Define class and instance attributes 48 | 49 | class Cylinder: 50 | # class attribute 51 | pi = 3.14 52 | 53 | def __init__(self, radius, height): 54 | # instance variables 55 | self.radius = radius 56 | self.height = height 57 | 58 | 59 | if __name__ == '__main__': 60 | c1 = Cylinder(4, 20) 61 | c2 = Cylinder(10, 50) 62 | 63 | print('pi for c1:', c1.pi, "and c2:", c2.pi) 64 | print('Radius for c1:', c1.radius, "and c2:", c2.radius) 65 | print('Height for c1:', c1.height, "and c2:", c2.height) 66 | print('Pi for both c1 and c2 is:', Cylinder.pi) 67 | 68 | 69 | # Define class and instance methods 70 | class Cylinder: 71 | # class attribute 72 | pi = 3.14 73 | 74 | def __init__(self, radius, height): 75 | # instance variables 76 | self.radius = radius 77 | self.height = height 78 | 79 | # instance method 80 | def volume(self): 81 | return Cylinder.pi * self.radius ** 2 * self.height 82 | 83 | # class method 84 | @classmethod 85 | def description(cls): 86 | return 'This is a Cylinder class that computes the volume using Pi=', cls.pi 87 | 88 | 89 | if __name__ == '__main__': 90 | c1 = Cylinder(40, 2) # create an instance/object 91 | 92 | print('Volume of Cylinder:', c1.volume()) # access instance method 93 | print(Cylinder.description()) # access class method via class 94 | print(c1.description()) # access class method via instance 95 | 96 | 97 | # Render a class’s attributes and methods protected. 98 | class Article: 99 | def __init__(self, title, page_count): 100 | # initialize protected attributes 101 | self._title = title 102 | self._page_count = page_count 103 | 104 | # define protected method 105 | def _show(self): 106 | # access protected attributes inside class 107 | print("Article Title: ", self._title) 108 | print("Page Count: ", self._page_count) 109 | 110 | 111 | class Author(Article): 112 | def __init__(self, name, title, page_count): 113 | Article.__init__(self, title, page_count) 114 | self.name = name 115 | 116 | def display(self): 117 | print("Author Name: ", self.name) 118 | # access Article's protected method 119 | self._show() 120 | print("------------------ \n") 121 | 122 | 123 | author = Author("Eyong Kevin", "Python Classes and Objects", 3000) 124 | author.display() 125 | # access protected data 126 | print(author._title) 127 | 128 | 129 | # Render a class’s attributes and methods private. 130 | class Language: 131 | # private class attribute 132 | __country = "Cameroon" 133 | 134 | def __init__(self, name): 135 | # initialize private instance attribute 136 | self.__name = name 137 | 138 | # private method 139 | def __show(self): 140 | # access private attributes 141 | print("Country: ", Language.__country) 142 | print("Name :", self.__name) 143 | 144 | # public method 145 | def display(self): 146 | # access private method within class 147 | self.__show() 148 | 149 | 150 | lang = Language("English") 151 | lang.display() 152 | 153 | # access private variable and method 154 | lang._Language__show() 155 | print("Access Private Name: ", lang._Language__name) 156 | -------------------------------------------------------------------------------- /Iterative_Statements.py: -------------------------------------------------------------------------------- 1 | #Python for loop to iterate through the letters in a word 2 | for i in "The Royal Colosseum": 3 | print(i) 4 | 5 | for i in "The Royal Colosseum": 6 | print(i, end="") 7 | #Python for loop using the range() function 8 | for j in range(5): 9 | print(j) 10 | #Python for loop to iterate through a list 11 | AnimalList = ['Cat','Dog','Tiger','Cow'] 12 | for x in AnimalList: 13 | print(x) 14 | #Python for loop to iterate through a dictionary 15 | programmingLanguages = {'J':'Java','P':'Python'} 16 | for key in programmingLanguages.keys(): 17 | print(key,programmingLanguages[key]) 18 | #Python for loop using the zip() function for parallel iteration 19 | a1 = ['Python','Java','CSharp'] 20 | b2 = [1,2,3] 21 | for i,j in zip(a1,b2): 22 | print(i,j) 23 | #Using else statement inside a for loop in Python 24 | flowers = ['Jasmine','Lotus','Rose','Sunflower'] 25 | for f in flowers: 26 | print(f) 27 | else: 28 | print('Done') 29 | #Nested for loops in Python (one loop inside another loop) 30 | list1 = [5,10,15,20] 31 | list2 = ['Tomatoes','Potatoes','Carrots','Cucumbers'] 32 | 33 | for x in list1: 34 | for y in list2: 35 | print(x,y) 36 | #Using break statement inside a for loop in Python 37 | vehicles = ['Car','Cycle','Bus','Tempo'] 38 | 39 | for v in vehicles: 40 | if v == "Bus": 41 | break 42 | print(v) 43 | #Python for loop to count the number of elements in a list 44 | numbers = [12,3,56,67,89,90] 45 | count = 0 46 | 47 | for n in numbers: 48 | count += 1 49 | 50 | print(count) 51 | #Python for loop to find the sum of all numbers in a list 52 | numbers = [12,3,56,67,89,90] 53 | sum = 0 54 | 55 | for n in numbers: 56 | sum += n 57 | 58 | print(sum) 59 | #Python for loop to copy elements from one list to another 60 | list1 = ['Mango', 'Banana', 'Orange'] 61 | list2 = [] 62 | for i in list1: 63 | list2.append(i) 64 | 65 | print(list2) 66 | # Python for loop to find the maximum element in a list 67 | numbers = [1, 4, 50, 80, 12] 68 | max = 0 69 | 70 | for n in numbers: 71 | if (n > max): 72 | max = n 73 | 74 | print(max) 75 | # Python for loop to find the minimum element in a list 76 | numbers = [1,4,50,80,12] 77 | min = 1000 78 | 79 | for n in numbers: 80 | if(n 0: 168 | count += 1 169 | number = int(input("Enter the number ")) 170 | sum += number 171 | start -= 1 172 | average = sum / count 173 | print("Average of given Numbers:", average) 174 | # Printing the square of numbers using while loop 175 | n = 1 176 | while n <= 5: 177 | squareNum = n**2 178 | print(n,squareNum) 179 | n += 1 180 | # Finding the sum of even numbers using while loop 181 | even_sum=0 182 | i=0 183 | while(i<15): 184 | even_sum=even_sum+i 185 | i=i+2 186 | print("sum =",even_sum) -------------------------------------------------------------------------------- /functions.py: -------------------------------------------------------------------------------- 1 | def welcome(): 2 | print("Introduction to function") 3 | welcome() 4 | 5 | def name(): 6 | name= input("Enter your Name:") 7 | print(name,"Welcome to Python 101") 8 | name() 9 | def add(): 10 | number1= int(input("Number 1 is:")) 11 | number2 = int(input("Number 2 is:")) 12 | sum = number1+number2 13 | print("Sum of two numbers is:", sum) 14 | add() 15 | def product(): 16 | number1= int(input("Number 1 is:")) 17 | number2 = int(input("Number 2 is:")) 18 | result = number1*number2 19 | print("Product of two numbers is:", result) 20 | product() 21 | 22 | def difference(): 23 | number1= int(input("Number 1 is:")) 24 | number2 = int(input("Number 2 is:")) 25 | result = number1-number2 26 | print("Difference of two numbers is:", result) 27 | difference() 28 | def division(): 29 | number1= int(input("Number 1 is:")) 30 | number2 = int(input("Number 2 is:")) 31 | result = number1/number2 32 | print("Division of two numbers is:", result) 33 | division() 34 | 35 | def addNumbers(x,y): 36 | sum = x + y 37 | return sum 38 | output = addNumbers(12,9) 39 | print(output) 40 | 41 | def diffNumbers(x,y): 42 | diff = x - y 43 | return diff 44 | output = diffNumbers(12,9) 45 | print(output) 46 | 47 | def productOfNumber(x,y): 48 | product = x * y 49 | return product 50 | output = productOfNumber(12,9) 51 | print(output) 52 | 53 | def divisionOfNumber(x,y): 54 | division = x / y 55 | return division 56 | output = divisionOfNumber(12,3) 57 | print(output) 58 | 59 | def myFruits(f1, f2, f3, f4): 60 | FruitsList = [f1, f2, f3, f4] 61 | return FruitsList 62 | output = myFruits("Apple", "Bannana", "Grapes", "Orange") 63 | print(output) 64 | 65 | def myAnimals(a1,a2,a3): 66 | Animalgroup = {'Kitten':a1,'Puppy':a2,'Pup':a3} 67 | return Animalgroup 68 | 69 | output = myAnimals("Cat","Dog","Rat") 70 | print(output) 71 | 72 | def max_of_two( x, y ): 73 | if x > y: 74 | return x 75 | return y 76 | def max_of_three( x, y, z ): 77 | return max_of_two( x, max_of_two( y, z ) ) 78 | 79 | print(max_of_two(3, 6, -5)) 80 | print(max_of_three(3, 6, -5)) 81 | 82 | def myChocolates(cList): 83 | for i in cList: 84 | print(i) 85 | 86 | chocolateList = ["Dairy Milk","Snickers","Kitkat"] 87 | myChocolates(chocolateList) 88 | 89 | def Calendar(year, month, date=''): 90 | print(year, month, date) 91 | Calendar(2023, 2, 14) 92 | 93 | def SwapTwoNumbers(a, b): 94 | print("Before Swap: ", a, b) 95 | a = a + b 96 | b = a - b 97 | a = a - b 98 | return a, b 99 | a, b = SwapTwoNumbers(17, 24) 100 | print("After Swap: ", a, b) 101 | 102 | def palindromeCheck(num): 103 | temp = num 104 | rev = 0 105 | while (num != 0): 106 | r = num % 10 107 | rev = rev * 10 + r 108 | num = num // 10 109 | if (rev == temp): 110 | print(temp, "is a palindrome number") 111 | else: 112 | print(temp, "is not a palindrome number") 113 | 114 | 115 | palindromeCheck(131) 116 | palindromeCheck(34) 117 | 118 | def factorial(n): 119 | fact = 1 120 | while (n != 0): 121 | fact *= n 122 | n = n - 1 123 | print("The factorial is", fact) 124 | inputNumber = int(input("Enter the number: ")) 125 | factorial(inputNumber) 126 | 127 | function with default argument 128 | def show_employee(name, salary=9000): 129 | print("Name:", name, "salary:", salary) 130 | 131 | show_employee("Ben", 12000) 132 | show_employee("Jessa") 133 | # Python function to sum all the numbers in a list. 134 | def sum(numbers): 135 | total = 0 136 | for x in numbers: 137 | total += x 138 | return total 139 | print(sum((8, 2, 3, 0, 7))) 140 | 141 | def carea(radius): 142 | area = 3.14*radius*radius 143 | print('Area of circle is', area) 144 | 145 | a = 5 146 | carea(a) 147 | 148 | def isPrime(number): 149 | for i in range(2,number): 150 | if number % i == 0: 151 | return False 152 | return True 153 | def main(): 154 | for n in range(100,501): 155 | if isPrime(n): 156 | print(n, end=' ') 157 | main() 158 | 159 | def show_choices(): 160 | print('\nMenu') 161 | print('1. Add') 162 | print('2. Subtract') 163 | print('3. Multiply') 164 | print('4. Divide') 165 | print('5. Exit') 166 | 167 | 168 | def add(a, b): 169 | return a + b 170 | 171 | 172 | def subtract(a, b): 173 | return a - b 174 | 175 | 176 | def multiply(a, b): 177 | return a * b 178 | 179 | 180 | def divide(a, b): 181 | return a / b 182 | 183 | 184 | def main(): 185 | while (True): 186 | show_choices() 187 | choice = input('Enter choice(1-5): ') 188 | if choice == '1': 189 | x = int(input('Enter first number: ')) 190 | y = int(input('Enter second number: ')) 191 | print('Sum =', add(x, y)) 192 | 193 | elif choice == '2': 194 | x = int(input('Enter first number: ')) 195 | y = int(input('Enter second number: ')) 196 | print('Difference =', subtract(x, y)) 197 | 198 | elif choice == '3': 199 | x = int(input('Enter first number: ')) 200 | y = int(input('Enter second number: ')) 201 | print('Product =', multiply(x, y)) 202 | 203 | elif choice == '4': 204 | x = int(input('Enter first number: ')) 205 | y = int(input('Enter second number: ')) 206 | if y == 0: 207 | print('Error!! divide by zero') 208 | else: 209 | print('Quotient =', divide(x, y)) 210 | 211 | elif choice == '5': 212 | break 213 | 214 | else: 215 | print('Invalid input') 216 | 217 | 218 | main() 219 | 220 | -------------------------------------------------------------------------------- /function and classes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Provide a full definition for a Python function called is ODD Digit, which takes a string as an argument and returns 3 | True if the value of the argument is a single-character string with value ‟1‟, ‟3‟, ‟5‟ ,"7"or ‟9‟ and returns False 4 | otherwise. 5 | """ 6 | 7 | 8 | def isOddDigit(s): 9 | if len(s) == 1 and s in ['1', '3', '5', '7', '9']: 10 | return True 11 | else: 12 | return False 13 | 14 | 15 | print(isOddDigit("1")) # True 16 | print(isOddDigit("3")) # True 17 | print(isOddDigit("5")) # True 18 | print(isOddDigit("7")) # True 19 | print(isOddDigit("9")) # True 20 | print(isOddDigit("2")) # False 21 | print(isOddDigit("hello")) # False 22 | 23 | print("----------------------------------------") 24 | print("----------------------------------------") 25 | 26 | 27 | # Find a Prime Number 28 | def is_prime(n): 29 | if n < 2: 30 | return False 31 | i = 2 32 | while i * i <= n: 33 | if n % i == 0: 34 | return False 35 | i += 1 36 | return True 37 | 38 | 39 | print(is_prime(4)) 40 | 41 | 42 | # Second Program 43 | def is_prime(n): 44 | if n < 2: 45 | return False 46 | for i in range(2, int(n ** 0.5) + 1): 47 | if n % i == 0: 48 | return False 49 | return True 50 | 51 | 52 | print(is_prime(2)) # True 53 | print(is_prime(3)) # True 54 | print(is_prime(4)) # False 55 | 56 | print("----------------------------------------") 57 | print("----------------------------------------") 58 | 59 | 60 | # Odd Even Program 61 | def is_odd_even(n): 62 | if n % 2 == 0: 63 | return True 64 | else: 65 | return False 66 | 67 | 68 | print(is_odd_even(2)) # True 69 | print(is_odd_even(3)) # False 70 | print(is_odd_even(4)) # True 71 | 72 | 73 | # Program 2 74 | def is_odd_even(n): 75 | return True if n % 2 == 0 else False 76 | 77 | 78 | print(is_odd_even(3)) 79 | 80 | 81 | # 82 | # # Calculator program using Menus 83 | # def calculator(): 84 | # while True: 85 | # # display menu 86 | # print("--- Calculator Menu ---") 87 | # print("0. Quit") 88 | # print("1. Add two numbers") 89 | # print("2. Subtract two numbers") 90 | # print("3. Multiply two numbers") 91 | # print("4. Divide two numbers") 92 | # choice = int(input("Enter your choice: ")) 93 | # 94 | # # perform requested action 95 | # if choice == 0: 96 | # print("Exiting calculator...") 97 | # break 98 | # elif choice == 1: 99 | # num1 = float(input("Enter the first number: ")) 100 | # num2 = float(input("Enter the second number: ")) 101 | # result = num1 + num2 102 | # print("The result is: ", result) 103 | # elif choice == 2: 104 | # num1 = float(input("Enter the first number: ")) 105 | # num2 = float(input("Enter the second number: ")) 106 | # result = num1 - num2 107 | # print("The result is: ", result) 108 | # elif choice == 3: 109 | # num1 = float(input("Enter the first number: ")) 110 | # num2 = float(input("Enter the second number: ")) 111 | # result = num1 * num2 112 | # print("The result is: ", result) 113 | # elif choice == 4: 114 | # num1 = float(input("Enter the first number: ")) 115 | # num2 = float(input("Enter the second number: ")) 116 | # if num2 != 0: 117 | # result = num1 / num2 118 | # print("The result is: ", result) 119 | # else: 120 | # print("Cannot divide by zero") 121 | # else: 122 | # print("Invalid choice. Please enter a number between 0 and 4.") 123 | # 124 | # 125 | # calculator() 126 | 127 | 128 | # definition of the class starts here 129 | class Person: 130 | # initializing the variables 131 | name = "" 132 | age = 0 133 | 134 | # defining constructor 135 | def __init__(self, personName, personAge): 136 | self.name = personName 137 | self.age = personAge 138 | 139 | # defining class methods 140 | 141 | def showName(self): 142 | print(self.name) 143 | 144 | def showAge(self): 145 | print(self.age) 146 | 147 | # end of the class definition 148 | 149 | 150 | # Create an object of the class 151 | person1 = Person("Abdur Rehman", 23) 152 | # Create another object of the same class 153 | person2 = Person("Asim", 102) 154 | # call member methods of the objects 155 | person1.showAge() 156 | person2.showName() 157 | 158 | 159 | class Animal: 160 | def speak(self): 161 | print("Animal Speaking") 162 | # child class Dog inherits the base class Animal 163 | 164 | 165 | class Dog(Animal): 166 | def bark(self): 167 | print("dog barking") 168 | 169 | 170 | d = Dog() 171 | d.bark() 172 | d.speak() 173 | 174 | 175 | # Inheritance 176 | class Animal: 177 | def speak(self): 178 | print("Animal Speaking") 179 | # The child class Dog inherits the base class Animal 180 | 181 | 182 | class Dog(Animal): 183 | def bark(self): 184 | print("dog barking") 185 | # The child class Dogchild inherits another child class Dog 186 | 187 | 188 | class DogChild(Dog): 189 | def eat(self): 190 | print("Eating bread...") 191 | 192 | 193 | d = DogChild() 194 | d.bark() 195 | d.speak() 196 | d.eat() 197 | # Real Life Example of method overriding 198 | class Bank: 199 | def getroi(self): 200 | return 10; 201 | 202 | 203 | class SBI(Bank): 204 | def getroi(self): 205 | return 7; 206 | 207 | 208 | class ICICI(Bank): 209 | def getroi(self): 210 | return 8; 211 | 212 | 213 | b1 = Bank() 214 | b2 = SBI() 215 | b3 = ICICI() 216 | print("Bank Rate of interest:", b1.getroi()); 217 | print("SBI Rate of interest:", b2.getroi()); 218 | print("ICICI Rate of interest:", b3.getroi()); --------------------------------------------------------------------------------