├── Contributing.md ├── Cover_short_PythonBookcamp.JPG ├── LICENSE.txt ├── README.md ├── chapter1 ├── hello_world.py ├── sum.py └── triangle.py ├── chapter11 ├── chap11_exercise.py ├── class_object_demo_1.py ├── class_object_demo_2.py ├── class_object_demo_3.py ├── class_object_demo_4.py ├── class_object_demo_5.py ├── constructor_example_1.py ├── cs_8.1_implementation.py ├── importing_all_classes_from_a_module.py ├── importing_entire_module.py ├── importing_multiple_classes.py ├── importing_single_class.py ├── inheritance_ex1.py ├── inheritance_ex2.py ├── parent_constructor_called.py ├── private_variable_and_method.py ├── use_of_identity_operator.py └── using_static_method.py ├── chapter12 ├── chapter12_ex12_dot_1.py ├── chapter12_ex12_dot_2.py ├── my_library_functions.py ├── run_multiple_tests.py ├── run_single_test.py └── testing_employee_class.py ├── chapter2 ├── chapter2_exercise_solutions.py ├── hello_world_modified.py └── using_comments.py ├── chapter3 ├── chap3_exercise.py ├── cs_1.1_implementation.py ├── numbers_usage_file_1.py ├── numbers_usages_file_2.py ├── string_usage_file_1.py ├── string_usage_file_2.py └── taking_user_input.py ├── chapter4 ├── conditional_expressions.py ├── cs_2.1_implementation.py ├── decision_making_exercises_solutions.py ├── demo5b_not_recommended.py ├── demo7_not_recommened.py └── using_if_statments.py ├── chapter5 ├── assignment_5_dot_1.py ├── assignment_5_dot_2.py ├── assignment_5_dot_3_dot_4_dot_5.py ├── break_statement_example1.py ├── continue_statement_example.py ├── cs_3.1_implementation.py ├── for_loop_example.py ├── infinite_loop_example.py ├── nested_loop_ex_1.py ├── print_upto_3.py ├── printing_employee_names_using_for_loop.py └── while_loop_ex_1.py ├── chapter6 ├── cs_4.1_implementation.py ├── dictionary_usage_file.py ├── exercise_solutions.py ├── list_usage_file_2.py ├── list_usages_file_1.py ├── set_usage_file.py └── tuple_usage_file.py ├── chapter7 ├── chap7_exercise.py ├── cs_5.1_implementation.py ├── cs_5.2_implementation.py ├── global_variable_example.py ├── importing_entire_module.py ├── lambda_functions_examples.py ├── using_function_alias.py ├── using_functions.py ├── using_functions_part2.py ├── using_module_alias.py └── using_molules_example_1.py ├── chapter8 ├── cs_6.1_implementation.py ├── custom_exception.py ├── exception_handling_case_study_1.py ├── exercise8.1.py ├── exercise8.3.py ├── exercise8.4.py ├── try_except_example_1.py ├── try_with_multiple_except_example2.py ├── use_of_pass.py ├── use_of_try_except_and_else.py └── using_assert.py ├── chapter9 ├── OriginalFile.txt ├── cs_7.1_implementation.py ├── ex_9_dot_1.py ├── ex_9_dot_5.py ├── ex_9_dot_6.py ├── get_current_working_directory.py ├── handling_file_not_found_error.py ├── reading_text_file_example_1.py ├── reading_writing_using_buffer_size.py ├── rename_and_remove_file.py ├── using_with_keyword.py ├── working_with_binary_files.py └── writing_to_file.py ├── employee_module.py └── my_library.py /Contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing to Python Bookcamp 2 | 3 | Copyright for this book's source code belongs to the author. However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers. 4 | 5 | ## How to Contribute 6 | 7 | 1. Make sure you have a GitHub account. 8 | 2. Fork the repository for this book. 9 | 3. Create a new branch on which to make your change, e.g. 10 | `git checkout -b my_code_contribution` 11 | 4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted. 12 | 5. Submit a pull request. 13 | 14 | Thank you for your contribution! 15 | -------------------------------------------------------------------------------- /Cover_short_PythonBookcamp.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vaskaran/PythonBookcamp/d41fca839f9e37251d5e9fe230b4539fede49cc1/Cover_short_PythonBookcamp.JPG -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Freeware License, some rights reserved 2 | 3 | Copyright (c) 2020 Vaskaran Sarcar 4 | 5 | Permission is hereby granted, free of charge, to anyone obtaining a copy 6 | of this software and associated documentation files (the "Software"), 7 | to work with the Software within the limits of freeware distribution and fair use. 8 | This includes the rights to use, copy, and modify the Software for personal use. 9 | Users are also allowed and encouraged to submit corrections and modifications 10 | to the Software for the benefit of other users. 11 | 12 | It is not allowed to reuse, modify, or redistribute the Software for 13 | commercial use in any way, or for a user’s educational materials such as books 14 | or blog articles without prior permission from the copyright holder. 15 | 16 | The above copyright notice and this permission notice need to be included 17 | in all copies or substantial portions of the software. 18 | 19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | AUTHORS OR COPYRIGHT HOLDERS OR APRESS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 25 | SOFTWARE. 26 | 27 | 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Bookcamp Source Code 2 | 3 | This repository accompanies [*Python Bookcamp*](https://www.amazon.com/Python-Bookcamp-Exercises-Hands-Projects-ebook/dp/B08FTD48NF/ref=sr_1_1?dchild=1&keywords=Python+Bookcamp%3A+Exercises+and+Hands-on+Projects&qid=1605020741&sr=8-1) by Vaskaran Sarcar (2020). 4 | 5 | [comment]: #cover 6 | ![Cover image](Cover_short_PythonBookcamp.JPG) 7 | 8 | Download the files as a zip using the green button, or clone the repository to your machine using Git. 9 | 10 | ## Releases 11 | 12 | Release v1.0 corresponds to the code in the published book, without corrections or updates. 13 | 14 | ## Contributions 15 | 16 | See the file Contributing.md for more information on how you can contribute to this repository. 17 | -------------------------------------------------------------------------------- /chapter1/hello_world.py: -------------------------------------------------------------------------------- 1 | print("Hello World!") 2 | 3 | -------------------------------------------------------------------------------- /chapter1/sum.py: -------------------------------------------------------------------------------- 1 | print("The sum of 12 and 5.7 are as follows:") 2 | print(12+5.7) 3 | -------------------------------------------------------------------------------- /chapter1/triangle.py: -------------------------------------------------------------------------------- 1 | print("*") 2 | print("**") 3 | print("***") 4 | print("****") 5 | print("*****") 6 | -------------------------------------------------------------------------------- /chapter11/chap11_exercise.py: -------------------------------------------------------------------------------- 1 | print("Exercise-11.1 and Exercise -11.2") 2 | 3 | 4 | class Student: 5 | class_name = "Student" 6 | 7 | def __init__(self,roll_number): 8 | self.roll_number = roll_number 9 | 10 | def about_me(self,name): 11 | """ A simple method """ 12 | print(f"Hello,{name}!") 13 | print(f"You belong to {self.class_name} class!") 14 | print(f"Your roll number is:{self.roll_number}") 15 | 16 | 17 | #Creating an object from Student class 18 | student_1 = Student(25) #correct.Ex-11.1 19 | #student_1 = Student() #error. Ex-11.2 20 | #Invoking the method 21 | student_1.about_me("Mike") 22 | 23 | print("-" * 30) 24 | print("Exercise-11.3") 25 | 26 | 27 | class College: 28 | college = "Abc" 29 | 30 | def __init__(self, name, stud_name, roll_number): 31 | self.college = name 32 | self.stud_name = stud_name 33 | self.roll_number = roll_number 34 | 35 | def about_me(self): 36 | print(f"College name is: {self.college}") 37 | print(f"The student name is: {self.stud_name}") 38 | print(f"The roll number is: {self.roll_number}") 39 | 40 | 41 | student_1 = College("St. Stephen", "Bob", 2) 42 | student_1.about_me() 43 | 44 | print("-" * 30) 45 | print("Exercise-11.4") 46 | 47 | 48 | class Student: 49 | def __init__(self, roll_number, name="Mike"): 50 | self.name = name 51 | self.roll_number = roll_number 52 | 53 | def about_me(self): 54 | print(f"Name is: {self.name}") 55 | print(f"The roll number is: {self.roll_number}") 56 | 57 | 58 | student_1 = Student("Bob",1) 59 | print("\nStudent-1 detail:") 60 | student_1.about_me() 61 | 62 | print("\nStudent-2 detail:") 63 | student_2 = Student(2) 64 | student_2.about_me() 65 | 66 | #student_3 = Student() # Error: passing a roll number is a must now 67 | 68 | 69 | print("-" * 30) 70 | print("Exercise-11.5") 71 | 72 | 73 | class Parent: 74 | @staticmethod 75 | def static_method(): 76 | print("Static method inside Parent is called.") 77 | 78 | @classmethod 79 | def class_method(cls): 80 | print(f"Class method is called.Invoker type:{cls}") 81 | 82 | 83 | class Child(Parent): 84 | """ This is a Child class.""" 85 | 86 | @staticmethod 87 | def static_method(): 88 | print("The static method inside Child is called.") 89 | 90 | 91 | parent_ob = Parent() 92 | child_ob = Child() 93 | parent_ob.class_method() 94 | child_ob.class_method() 95 | parent_ob.static_method() 96 | child_ob.static_method() 97 | 98 | print("-" * 30) 99 | print("Exercise-11.6") 100 | 101 | 102 | class ParentClass: 103 | @staticmethod 104 | def static_method(): 105 | print("Static method inside Parent is called.") 106 | 107 | 108 | class ChildClass(Parent): 109 | pass 110 | 111 | 112 | ParentClass.static_method() 113 | ChildClass.static_method() 114 | 115 | print("-" * 30) 116 | 117 | -------------------------------------------------------------------------------- /chapter11/class_object_demo_1.py: -------------------------------------------------------------------------------- 1 | # Demonstration-1 2 | # The class definition 3 | 4 | 5 | class Student: 6 | """ This is a simple Student class.""" 7 | name = "Student class" 8 | 9 | def say_hi(self, student_name): 10 | """ A simple method to say hello to a student.""" 11 | print(f"Hello {student_name}!") 12 | print(f"You are using the {self.name} now.") 13 | 14 | 15 | #Creating an object from Student class 16 | object1 = Student() 17 | #Invoking the method 18 | object1.say_hi("John") 19 | 20 | #Creating another object from Student class 21 | object2 = Student() 22 | #Invoking the method 23 | object2.say_hi("Kate") 24 | 25 | #print(type(object1)) # 26 | #print(type(object2)) # 27 | -------------------------------------------------------------------------------- /chapter11/class_object_demo_2.py: -------------------------------------------------------------------------------- 1 | # Demonstration-2 2 | 3 | """ 4 | If you do not supply any constructor for your class, 5 | Python will call the superclass constructor for you. 6 | To understand ‘Superclass’, you need to learn inheritance 7 | which I discuss later in this chapter. 8 | In Python 3.x , object is the root of all classes. 9 | Once you learn inheritance, you’ll see that in 10 | this demonstration,class Student and 11 | class Student(object) are same. 12 | """ 13 | 14 | 15 | #class Student(object): 16 | 17 | class Student: 18 | """ This is a Student class with a constructor.""" 19 | 20 | def __init__(self, name, roll_no): 21 | """ 22 | The name and roll_no is used to 23 | identify a student properly. 24 | """ 25 | print(f"The student name is: {name}") 26 | print(f"The student roll number is: {roll_no}") 27 | 28 | 29 | # Creating an object from Student class. 30 | # Using the constructor which has two parameters. 31 | student_robin = Student("Robin", 2) 32 | # Another object 33 | #student_kate = Student("Kate", 4) 34 | 35 | -------------------------------------------------------------------------------- /chapter11/class_object_demo_3.py: -------------------------------------------------------------------------------- 1 | class Student: 2 | """ This is a Student class with a constructor.""" 3 | def __init__(self, name, roll_no): 4 | """ 5 | The name and roll_no is used to 6 | identify a student properly. 7 | """ 8 | print("This constructor has two parameters.") 9 | #initialize name 10 | self.name = name 11 | #initialize roll_no 12 | self.roll_no = roll_no 13 | print(f"The student name is: {self.name}") 14 | print(f"The student roll number is: {self.roll_no}") 15 | 16 | 17 | # Creating an object from Student class. 18 | # Using the constructor that accepts two parameters. 19 | student_jack = Student("Jack", 3) 20 | 21 | 22 | # Changing the attribute values of student_jack 23 | student_jack .name = "Bob" 24 | student_jack .roll_no = 5 25 | print("Now student_jack has the following details:") 26 | print(f"Student name= {student_jack.name}") 27 | print(f"Student roll number= {student_jack.roll_no}") 28 | -------------------------------------------------------------------------------- /chapter11/class_object_demo_4.py: -------------------------------------------------------------------------------- 1 | class Student: 2 | """ This is a Student class with a constructor.""" 3 | 4 | def __init__(self, name, roll_no): 5 | """ 6 | The name and roll_no is used to 7 | identify a student properly. 8 | """ 9 | #initialize name 10 | self.name = name 11 | #initialize roll_no 12 | self.roll_no = roll_no 13 | 14 | def get_details(self): 15 | """ 16 | This method prints the detail of a student. 17 | """ 18 | print("The current student's detail is:") 19 | print(f"Name: {self.name}") 20 | print(f"Roll number: {self.roll_no}") 21 | 22 | def update_student_details(self, new_name, new_roll_no): 23 | """ 24 | This method is used to update a student's detail. 25 | :param new_name: Updated student name. 26 | :param new_roll_no: Updated student roll_no 27 | :return: None 28 | """ 29 | self.name = new_name 30 | self.roll_no = new_roll_no 31 | 32 | 33 | # Creating an object from Student class. 34 | student_1 = Student("Jack", 3) 35 | #printing the details 36 | student_1.get_details() 37 | # Changing the attribute values of student_1 38 | student_1.name = "Bob" 39 | student_1.roll_no = 5 40 | print("---After the first update.---") 41 | student_1.get_details() 42 | 43 | #Second update using the method 'update_student_details' 44 | student_1.update_student_details("Harry", 6) 45 | print("---After the second update.---") 46 | student_1.get_details() 47 | -------------------------------------------------------------------------------- /chapter11/class_object_demo_5.py: -------------------------------------------------------------------------------- 1 | class Student: 2 | def __init__(self,name,roll_no): 3 | #initialize name 4 | self.name = name 5 | #initialize roll_no 6 | self.roll_no = roll_no 7 | self.college = "St.Stephen" 8 | 9 | def get_details(self): 10 | print("The current student's detail is:") 11 | # Formatting the output using f-string 12 | # This syntax is available from Python 3.6 onwards) 13 | print(f"Name: {self.name}") 14 | print(f"Roll number: {self.roll_no}") 15 | print(f"College: {self.college}") 16 | 17 | 18 | # Creating an object from Student class. 19 | student_1 = Student("Jack", 3) 20 | #printing the details 21 | student_1.get_details() 22 | 23 | # Creating another object from Student class. 24 | student_1 = Student("Kate", 4) 25 | #printing the details 26 | student_1.get_details() 27 | -------------------------------------------------------------------------------- /chapter11/constructor_example_1.py: -------------------------------------------------------------------------------- 1 | class Student: 2 | #name = "Student class" 3 | #rollno=10 4 | 5 | #def __init__(self): 6 | #print("You do not need to supply any parameter.") 7 | 8 | def __init__(self, name): 9 | print("You need to supply a name.") 10 | #print(f"You've supplied the name:{name}") 11 | 12 | #def __init__(self, name, roll_no): 13 | #print("Supply a name and a roll number.") 14 | 15 | 16 | # Creating an object from Student class. 17 | # Using the non-parameterised constructor. 18 | #object1 = Student() 19 | # Using the constructor that has one parameter. 20 | object2 = Student("John") 21 | # Using the constructor that accepts two parameters. 22 | # object3 = Student("Robin",2) 23 | -------------------------------------------------------------------------------- /chapter11/cs_8.1_implementation.py: -------------------------------------------------------------------------------- 1 | class Engineering: 2 | """Engineering is the parent class.""" 3 | 4 | def __init__(self, college_name): 5 | # Initialize name 6 | self.college = college_name 7 | self.subject_1 = "Mathematics." 8 | self.subject_2 = "Soft-skills." 9 | 10 | 11 | class ComputerScience(Engineering): 12 | """ 13 | ComputerScience class inherits from Engineering. 14 | Default institution is St.Stephen. 15 | """ 16 | 17 | def __init__(self, college_name=" St. Stephen", 18 | special_subject="Compiler design."): 19 | """ Initialize starts from parent class.""" 20 | super().__init__(college_name) 21 | self.subject_3 = special_subject 22 | 23 | def course_details(self): 24 | """Prints the course details of an institution.""" 25 | print(f"Institution name:{self.college} college.") 26 | print("Computer science course includes:") 27 | print(f"1:{self.subject_1}") 28 | print(f"2:{self.subject_2}") 29 | print(f"3:{self.subject_3}") 30 | print("-" * 10) 31 | 32 | 33 | # Computer science course at Presidency College 34 | cs_course1 = ComputerScience(" Presidency", 35 | "Python Programming") 36 | cs_course1.course_details() 37 | 38 | # Computer science course at St.Stephen College 39 | cs_course2 = ComputerScience() 40 | cs_course2.course_details() 41 | 42 | 43 | -------------------------------------------------------------------------------- /chapter11/importing_all_classes_from_a_module.py: -------------------------------------------------------------------------------- 1 | import employee_module 2 | 3 | 4 | #from employee_module import * # NOT a recommended practice 5 | 6 | 7 | class Employee: 8 | """ This employee class stays in the current file.""" 9 | def __init__(self): 10 | print("Inside the constructor of the Employee class") 11 | 12 | 13 | # Creating an object from the Employee class. 14 | #emp_1 = Employee("Jack", 3) #Name collision 15 | emp_1 = employee_module.Employee("Jack", 3) 16 | # Setting background details for emp_1 17 | #emp_1_details = PersonalDetails( 18 | emp_1_details = employee_module.PersonalDetails( 19 | emp_1.name, 20 | emp_1.company, 21 | 10.2, 22 | 39, 23 | "21,Abc Road,USA") 24 | # Printing the details 25 | emp_1.get_details() 26 | emp_1_details.background_details() 27 | 28 | emp_2 = Employee() # Uses current file’s Employee class 29 | -------------------------------------------------------------------------------- /chapter11/importing_entire_module.py: -------------------------------------------------------------------------------- 1 | import employee_module 2 | 3 | # Creating an object from the Employee class. 4 | emp_1 = employee_module.Employee("Jack", 3) 5 | # Setting background details for emp_1 6 | emp_1_details= employee_module.PersonalDetails( 7 | emp_1.name, 8 | emp_1.company, 9 | 10.2, 10 | 39, 11 | "21,Abc Road,USA") 12 | # Printing the details 13 | emp_1.get_details() 14 | emp_1_details.background_details() 15 | -------------------------------------------------------------------------------- /chapter11/importing_multiple_classes.py: -------------------------------------------------------------------------------- 1 | from employee_module import Employee, PersonalDetails 2 | 3 | # Creating an object from Employee class. 4 | emp_1 = Employee("Jack", 3) 5 | # Setting background details for emp_1 6 | emp_1_details = PersonalDetails(emp_1.name, 7 | emp_1.company, 8 | 10.2, 9 | 39, 10 | "21,Abc Road,USA") 11 | # Printing the details 12 | emp_1.get_details() 13 | emp_1_details.background_details() 14 | -------------------------------------------------------------------------------- /chapter11/importing_single_class.py: -------------------------------------------------------------------------------- 1 | from employee_module import Employee 2 | 3 | # Creating an object from the Employee class. 4 | emp_1 = Employee("Jack", 3) 5 | # Printing the details 6 | emp_1.get_details() 7 | 8 | # Creating another object from the Employee class. 9 | emp_2 = Employee("Kate", 4) 10 | # Printing the details 11 | emp_2.get_details() 12 | -------------------------------------------------------------------------------- /chapter11/inheritance_ex1.py: -------------------------------------------------------------------------------- 1 | class Shape: 2 | """ 3 | It is the Shape class. 4 | It is the parent class of Rectangle 5 | in this example. 6 | """ 7 | 8 | def __init__(self): 9 | self.type = "Shape" 10 | 11 | def about_me(self): 12 | print(f"I am a {self.type}.") 13 | 14 | 15 | class Rectangle(Shape): 16 | """ 17 | This is the Rectangle class which 18 | inherits from the Shape class 19 | """ 20 | 21 | def __init__(self): 22 | self.type = "Rectangle" 23 | 24 | def about_me(self): 25 | print(f"I am a {self.type}.") 26 | 27 | 28 | print("***Simple inheritance example.***") 29 | shape_ob = Shape() 30 | print(f"The shape_ob.type={ shape_ob.type}") 31 | shape_ob.about_me() 32 | 33 | rectangle_ob = Rectangle() 34 | print(f"The rectangle_ob.type={ rectangle_ob.type}") 35 | rectangle_ob.about_me() 36 | -------------------------------------------------------------------------------- /chapter11/inheritance_ex2.py: -------------------------------------------------------------------------------- 1 | class Employee: 2 | """Employee class is the parent class.""" 3 | 4 | def __init__(self, name, emp_id): 5 | # Initialize name 6 | self.name = name 7 | # Initialize emp_id 8 | self.emp_id = emp_id 9 | self.company = "Abc Ltd." 10 | 11 | 12 | class Developer(Employee): 13 | """Developer class inherits from Employee""" 14 | 15 | def __init__(self, name, emp_id): 16 | """ Initialize starts from parent class.""" 17 | super().__init__(name, emp_id) 18 | # Employee.__init__(self, name, emp_id) #Also works 19 | # This is a class-specific attribute 20 | self.designation = "Developer" 21 | 22 | def developer_details(self): 23 | """Prints the developer details.""" 24 | print(f"Name: {self.name}") 25 | print(f"Id= {self.emp_id}") 26 | print(f"Designation= {self.designation}") 27 | print("-" * 10) 28 | 29 | 30 | # Creating an instance of the Developer class 31 | john = Developer("John S", "E001") 32 | john.developer_details() 33 | kate = Developer("Kate W", "E002") 34 | kate.developer_details() 35 | -------------------------------------------------------------------------------- /chapter11/parent_constructor_called.py: -------------------------------------------------------------------------------- 1 | class Parent: 2 | def __init__(self): 3 | print(f"The Parent constructor is called.") 4 | 5 | 6 | class Student(Parent): 7 | """ This is a Student class with a constructor.""" 8 | ''' 9 | def __init__(self,name,roll_no): 10 | """ 11 | The name and roll_no is used to 12 | identify a student properly. 13 | """ 14 | print(f"The student name is:{name}") 15 | print(f"The student roll no is:{roll_no}") 16 | 17 | ''' 18 | # Creating an object from Student class. 19 | # Using the constructor that accepts two parameters. 20 | #student_robin = Student("Robin",2) 21 | student_robin = Student() 22 | 23 | print(type(student_robin)) # 24 | -------------------------------------------------------------------------------- /chapter11/private_variable_and_method.py: -------------------------------------------------------------------------------- 1 | class Parent: 2 | """ This is the parent class""" 3 | 4 | def __init__(self): 5 | self.i = 1 #public variable 6 | self.__j = 10 #private variable 7 | 8 | def __private_show_me(self): 9 | print(f"i={self.i}") 10 | print(f"__j={self.j}") 11 | 12 | def about_me(self): 13 | print(f"i={self.i}") 14 | print(f"__j={self.__j}") 15 | 16 | 17 | parent_ob = Parent() 18 | print(f"parent_ob.i={parent_ob.i}") 19 | #print(parent_ob.__j)#will cause error 20 | print("Calling about_me() now:") 21 | parent_ob.about_me() 22 | #print("Calling __private_show_me() now:") 23 | #parent_ob.__private_show_me() #will cause error 24 | 25 | #print(parent_ob._Parent__j)#it works and prints 10 26 | 27 | 28 | -------------------------------------------------------------------------------- /chapter11/use_of_identity_operator.py: -------------------------------------------------------------------------------- 1 | class Student: 2 | """ This is a Student class with a constructor.""" 3 | def __init__(self, name, roll_no): 4 | """ 5 | The name and roll_no is used to 6 | identify a student properly. 7 | """ 8 | self.name = name 9 | #initialize roll_no 10 | self.roll_no = roll_no 11 | print(f"Name: {self.name}") 12 | print(f"Roll number is: {self.roll_no}") 13 | 14 | 15 | # Creating an object from Student class. 16 | # Using the constructor that accepts two parameters. 17 | print("Creating jack object:") 18 | jack = Student("Jack", 3) 19 | print("\nCreating jack_2 object:") 20 | jack_2 = Student("Jack", 3) 21 | 22 | print("\nUse of identity operator:") 23 | print("jack is jack_2?", jack is jack_2) # False 24 | 25 | print("Introducing jack_3 object") 26 | jack_3 = jack 27 | print("jack_3 is jack?", jack_3 is jack) # True 28 | print("jack_3 is jack_2?", jack_3 is jack_2) # False 29 | 30 | print("-"*15) 31 | # You append the following lines to test further 32 | print("The type(jack) is Student?") 33 | print(type(jack) is Student) # True 34 | 35 | print("The type(jack) is int?") 36 | print(type(jack) is int) #False 37 | 38 | print("The type(jack) is NOT int?") 39 | print(type(jack) is not int) # True 40 | -------------------------------------------------------------------------------- /chapter11/using_static_method.py: -------------------------------------------------------------------------------- 1 | class Color: 2 | """ This is the parent class""" 3 | fav_color = "Green" 4 | 5 | def __init__(self, color): 6 | self.fav_color = color 7 | 8 | def instance_method(self): 9 | print("I am an instance method.") 10 | print("Call me with an instance and a dot operator.") 11 | print(f"My favorite color is: {self.fav_color}") 12 | print("+" * 15) 13 | 14 | @staticmethod 15 | def static_method(): 16 | print("I am a static method.") 17 | print("You can call me without a class instance.") 18 | print(f"My favorite color is: {Color.fav_color}") 19 | print("+" * 15) 20 | 21 | @classmethod 22 | def class_method(cls): 23 | print("I am a class method.") 24 | print("You can call me without a class instance.") 25 | print("In general, you use cls as the class parameter.") 26 | print(f"My favourite color is: {cls.fav_color}") 27 | print("+" * 15) 28 | 29 | 30 | #Creating an object from Student class 31 | my_color = Color("Blue") 32 | print("Calling the instance_method() now.") 33 | my_color.instance_method() 34 | 35 | print("Calling the static_method() now.") 36 | Color.static_method() 37 | 38 | print("Calling the class_method() now.") 39 | Color.class_method() 40 | 41 | print("Changing the color inside the instance now.") 42 | my_color.fav_color = "Red" 43 | 44 | print("Calling the instance_method() now.") 45 | my_color.instance_method() 46 | 47 | print("Calling the static_method() now.") 48 | Color.static_method() 49 | 50 | print("Calling the class_method() now.") 51 | Color.class_method() 52 | 53 | 54 | ''' 55 | print("Alternative way of calling the static and class method.") 56 | #Also works 57 | my_color.static_method() 58 | my_color.class_method() 59 | ''' 60 | -------------------------------------------------------------------------------- /chapter12/chapter12_ex12_dot_1.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from employee_module import Employee 3 | 4 | 5 | class TestEmployeeMethod(unittest.TestCase): 6 | def test_get_details_modified(self): 7 | """ Does the get_details() work correctly? """ 8 | emp_kate = Employee('Kate', 'E002') 9 | self.assertTrue('Kate' in emp_kate.get_details_modified(), 'The employee name is not found.') 10 | self.assertTrue('E002' in emp_kate.get_details_modified(), 'The employee id is not found.') 11 | self.assertTrue('Abc Ltd.' in emp_kate.get_details_modified(), 'The company information is not found.') 12 | 13 | 14 | if __name__ == '__main__': 15 | unittest.main() 16 | -------------------------------------------------------------------------------- /chapter12/chapter12_ex12_dot_2.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from math import sqrt, floor, gcd 3 | 4 | 5 | class TestEmployeeMethod(unittest.TestCase): 6 | def test_inbuilt_functions(self): 7 | """ Do the methods sqrt(),floor(), and gcd() correctly? """ 8 | self.assertEqual(5.0, sqrt(25), 'The sqrt(25) does not give the expected result.') 9 | self.assertEqual(100, floor(100.2), 'The floor(100.2) does not give the expected result.') 10 | self.assertEqual(2, gcd(4, 10), 'The gcd(4,10) does not give the expected result.') 11 | 12 | 13 | if __name__ == '__main__': 14 | unittest.main() 15 | -------------------------------------------------------------------------------- /chapter12/my_library_functions.py: -------------------------------------------------------------------------------- 1 | # I write test cases to verify the following functions. 2 | 3 | """ Support to use custom functions. 4 | 5 | Functions 6 | --------- 7 | make_total_double() 8 | This function takes two numbers and returns the double. 9 | 10 | make_total_double() 11 | This function takes three numbers and returns the average. 12 | The third number is optional. 13 | 14 | """ 15 | 16 | 17 | def make_total_double(first,second): 18 | """ 19 | This function takes two numbers and returns the double. 20 | """ 21 | total = first + second 22 | return total * 2 23 | 24 | 25 | def make_average(first,second,third=0): 26 | """ 27 | This function takes three numbers and returns the average. 28 | The third number is optional. 29 | """ 30 | total = first + second + third 31 | return total / 3 32 | -------------------------------------------------------------------------------- /chapter12/run_multiple_tests.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import my_library_functions as ml # importing everything from the module 3 | 4 | 5 | class LibraryFunctionsTestCases(unittest.TestCase): 6 | """ Tests for my_library_functions """ 7 | 8 | def test_make_total_double(self): 9 | """ Can we make the average of 10 | the numbers 25,75.3 """ 11 | resultant_value = ml.make_total_double(25,75.2) 12 | self.assertEqual(200.4,resultant_value) #test passes 13 | 14 | def test_make_average_two_numbers(self): 15 | """ Can we make the the average of the 16 | numbers 25,75.8,and 0(optional)?""" 17 | resultant_value = ml.make_average(25,75.8) 18 | self.assertEqual(33.6,resultant_value) # test passes 19 | #self.assertEqual(40, resultant_value) # test fails 20 | 21 | def test_make_average_three_numbers(self): 22 | """ Can we make the average of the 23 | numbers 10,20.9 and 30 ?""" 24 | resultant_value = ml.make_average(10,20.9,30) 25 | self.assertEqual(20.3,resultant_value) 26 | 27 | 28 | if __name__ == '__main__': 29 | unittest.main() 30 | -------------------------------------------------------------------------------- /chapter12/run_single_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from my_library_functions import make_total_double 3 | 4 | 5 | class LibraryFunctionsTestCases(unittest.TestCase): 6 | """ Tests for my_library_functions """ 7 | 8 | def test_make_total_double(self): 9 | """ Can we make the total double for the numbers 25,75.3 """ 10 | resultant_value = make_total_double(25, 75.3) 11 | self.assertEqual(200.6, resultant_value) #test passes 12 | #self.assertEqual(200.6+1,resultant_value) #test fails 13 | #self.assertEqual(200.6+1, resultant_value,"The actual value and expected value does not match") #test fails 14 | #self.assertEqual(200.6, resultant_value, "The actual value and expected value does not match") #test passes 15 | 16 | 17 | if __name__ == '__main__': 18 | unittest.main() 19 | -------------------------------------------------------------------------------- /chapter12/testing_employee_class.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from employee_module import Employee 3 | 4 | 5 | class TestEmployee(unittest.TestCase): 6 | """ Tests for Employee class in employee_module """ 7 | 8 | def test_employee_creation(self): 9 | """ Can we store the Employee details correctly? """ 10 | emp_john = Employee('John', 'E001') 11 | self.assertEqual(emp_john.name, 'John', 'Employee name does not match.') 12 | self.assertEqual(emp_john.emp_id, 'E001', 'Employee ID does not match.') 13 | self.assertEqual(emp_john.company, 'Abc Ltd.', 'The company information is not found.') 14 | 15 | 16 | if __name__ == '__main__': 17 | unittest.main() 18 | -------------------------------------------------------------------------------- /chapter2/chapter2_exercise_solutions.py: -------------------------------------------------------------------------------- 1 | print("Exercise-2.1") 2 | x = '12.2' 3 | print('x') 4 | print(x) 5 | print("-"*10) 6 | 7 | print("Exercise-2.2") 8 | x = 23 9 | y = 0 10 | print(x) 11 | print(y) 12 | #print(z) #error 13 | print("-"*10) 14 | 15 | print("Exercise-2.3") 16 | x, y, z = 1, 2, 3 17 | print("-"*10) 18 | 19 | print(x) 20 | print(y) 21 | print(z) 22 | print("-"*10) 23 | 24 | print("Exercise-2.4") 25 | abc=1 #ok 26 | #if=2 #error 27 | # $fi=3 #error 28 | _public = 4 # will work , but not recommended 29 | #abc$=5 #error 30 | #bob's=6 #error 31 | emp_id=7 #ok 32 | #emp id=8 #error 33 | print("-"*10) 34 | 35 | print("Exercise-2.5") 36 | name = "John" 37 | print("Welcome our favorite hero:") 38 | print(name) 39 | name = "Sam" 40 | print("He is changing his name to:") 41 | print(name) 42 | print("-"*10) 43 | 44 | print("Exercise-2.6") 45 | x = 2+3*(36/9+1)**2-1 46 | print(x) 47 | print("-"*10) 48 | 49 | print("Exercise-2.7") 50 | x = 3+2 & 4 | 2 51 | print(x) 52 | print("-"*10) 53 | 54 | print("Exercise-2.9") 55 | print("Here is my preferred shape:") 56 | print(" * ") 57 | print(" * * ") 58 | print(" * * ") 59 | print("*-------------------* ") 60 | -------------------------------------------------------------------------------- /chapter2/hello_world_modified.py: -------------------------------------------------------------------------------- 1 | print("*** This program shows the use of a variable. ***") 2 | # my_text is holding the value "Hello World!" 3 | my_text = "Hello World!" 4 | print(my_text) 5 | # my_text is holding a new value 6 | my_text = "Dear Reader, how are you?" 7 | print(my_text) 8 | -------------------------------------------------------------------------------- /chapter2/using_comments.py: -------------------------------------------------------------------------------- 1 | # Testing whether 2 is greater than 1 2 | print(2 > 1) 3 | ''' 4 | I’m using these as multi-line comments. 5 | I use these lines for your reference only. 6 | These are common in class,functions, or modules. 7 | ''' 8 | 9 | """ 10 | I’m trying to use multi-line comments using three double-quotes. 11 | I use these lines for your reference only. 12 | These are common in class,functions, or modules. 13 | """ 14 | 15 | # Now I'm showing multiple single-line comments 16 | # Multiplying 2 with 3 17 | # And printing the result 18 | print(2*3) 19 | -------------------------------------------------------------------------------- /chapter3/chap3_exercise.py: -------------------------------------------------------------------------------- 1 | #Solution to Exercise 3.1 2 | #First user input 3 | first_input = input("Enter first number:") 4 | #Converting it to float 5 | first_number = float(first_input) 6 | #Second user input 7 | second_input = input("Enter second number:") 8 | #Converting it to float 9 | second_number = float(second_input) 10 | #Calculating the average 11 | average = (first_number + second_number) / 2 12 | print("Average is :",average) 13 | print("--------End of Exercise 3.1----------------") 14 | 15 | #Solution to Exercise 3.2 16 | print("Hello,\nReader!") 17 | print("--------End of Exercise 3.2----------------") 18 | 19 | #Exercise 3.3 20 | print('The height of Andrew is 6\'9" ') 21 | #Alternative: 22 | print("The height of Andrew is 6'9\" ") 23 | print("--------End of Exercise 3.3----------------") 24 | 25 | #Exercise 3.4 26 | x, y = 10, 2.5 27 | print(x + y) #12.5 28 | print(x / y) #4.0 29 | print("Difference of x and y is:", x - y) #7.5 30 | #print("x*y=:"+ x*y) #Error: can only concatenate str (not "float") to str 31 | #print(x+ "is stored in x.") #Error: unsupported operand type(s) for +: 'int' and 'str' 32 | print("--------End of Exercise 3.4----------------") 33 | 34 | #Exercise 3.5 35 | x = 12 36 | #print("x= "+12)# Prints nothing as it is inside a commented line 37 | print("--------End of Exercise 3.5----------------") 38 | 39 | #Exercise 3.6 40 | 41 | #Get the radius from the user and converting it into a float 42 | radius = float(input("Enter the radius of the circle:")) 43 | #Area of a circle=(22/7)*r*r where r is the radius 44 | area = (22/7)*radius*radius 45 | print(f"The area of the circle is:{area} square unit.") 46 | print("--------End of Exercise 3.6----------------") 47 | -------------------------------------------------------------------------------- /chapter3/cs_1.1_implementation.py: -------------------------------------------------------------------------------- 1 | # Seller information 2 | seller_name = " Spencer Retail" 3 | seller_address = " 136, Garia Station Road,\n Kolkata:700084" 4 | seller_contact = "123-456-789" 5 | 6 | #Decorating top segment 7 | print("-" * 50) 8 | print(f"{seller_name}") 9 | print(f"{seller_address}") 10 | 11 | print("-" * 50) 12 | apricot_price = 300 13 | dates_price = 400 14 | almonds_price = 500 15 | apri_dates_combo = (apricot_price + dates_price) * .9 # 10% discount 16 | dates_almon_combo = (dates_price + almonds_price) * .9 # 10% discount 17 | almon_apri_combo = (almonds_price + apricot_price) * .9 # 10% discount 18 | gift_pack = (apricot_price + dates_price + almonds_price) * .75 # 25% discount 19 | print("Product(s) \tPrice (per pack)") 20 | print(f"Apricot\t\t{apricot_price}") 21 | print(f"Dates\t\t{dates_price}") 22 | print(f"Almond\t\t{almonds_price}") 23 | print(f"Combo-1\t\t{apri_dates_combo}") 24 | print(f"Combo-2\t\t{dates_almon_combo}") 25 | print(f"Combo-3\t\t{almon_apri_combo}") 26 | print(f"GiftBox\t\t{gift_pack}") 27 | 28 | # Decorating the bottom segment. 29 | # It contains the contact information. 30 | print("*" * 50) 31 | print(f"For free delivery, contact {seller_contact} ") 32 | print("*" * 50) 33 | -------------------------------------------------------------------------------- /chapter3/numbers_usage_file_1.py: -------------------------------------------------------------------------------- 1 | print(1) # Prints 1 2 | print(5.7) # Prints 5.7 3 | print(-6.789) # Prints -6.789 4 | 5 | print("-"*10) 6 | 7 | # Performing some basic arithmetic operations 8 | print(1 + 2) # Prints 3 9 | print(10 - 3) # Prints 7 10 | print(25 * 3) # Prints 75 11 | print(12.88 / 4) # Prints 3.22 12 | # You can perform complex mathematical 13 | # operations too inside the print function 14 | print(1 + 2 * 3) # Prints 7 15 | print((1 + 2) * 3) # Prints 9 16 | 17 | print("-"*10) 18 | # You can get a closer value 19 | print(10.5 - 2.1) # prints 8.4 20 | print(10.2 - 3) # prints 7.199999999999999 21 | 22 | print("-"*10) 23 | 24 | # Using variables 25 | my_int = 125 26 | print(my_int) # Prints 125 27 | my_float = 25.763 28 | print(my_float) # Prints 25.763 29 | 30 | # Difference between number and strings 31 | print("1" + "2") # Prints 12 32 | print(1 + 2) # Prints 3 33 | 34 | my_string1 = "10" 35 | my_string2 = "22" 36 | my_int1 = 10 37 | my_int2 = 22 38 | print(my_string1 + my_string2) # Prints 1022 39 | print(my_int1 + my_int2) # Prints 32 40 | 41 | print("-"*10) 42 | 43 | print("The value inside my_int1 is :", my_int1) # This is ok,Prints 10 44 | #print("The value inside my_int1 is :" + my_int1) # error 45 | # print(my_int1 + " is my first number") #error 46 | 47 | print("The value inside my_int1 is :" + str(my_int1)) # Ok 48 | 49 | print("-"*10) 50 | 51 | my_string1 = "12" 52 | # Converting string to an int 53 | print(int(my_string1, 10)) # prints 12 54 | 55 | # All strings are NOT convertible to an int 56 | my_string2 = "abc" 57 | # print(int(my_string2, 10)) # Error 58 | 59 | my_string1 = "25" 60 | my_string2 = "abc" 61 | print(my_string1.isdigit()) # True 62 | print(my_string2.isdigit()) # False 63 | 64 | print("-"*10) 65 | 66 | # using f-strings 67 | user_name="John" 68 | print(f"Hello,{user_name}!") 69 | 70 | print("-"*10) 71 | # Rounding a number 72 | print(round(2.7)) # Prints 2 73 | print(round(5.32)) # Prints 5 74 | 75 | print("-"*10) 76 | 77 | # Finding the maximum 78 | print(max(1, 2, 3, 4, 5)) # Prints 5 79 | # Finding the minimum 80 | print(min(1, 2, 3, 4, 5)) # Prints 1 81 | print("-"*10) -------------------------------------------------------------------------------- /chapter3/numbers_usages_file_2.py: -------------------------------------------------------------------------------- 1 | # importing math functions 2 | from math import *; 3 | 4 | # Printing the square root of 25 5 | print(f"Square root of 25 is :{sqrt(25)}") # 5.0 6 | # Printing the square root of 6.25 7 | print(f"Square root of 6.25 is :{sqrt(6.25)}") # 2.5 8 | 9 | print("-" * 10) 10 | 11 | # Printing the ceiling value 12 | # This is the smallest integer less than the number 13 | # you defined. 14 | 15 | print(f"The ceiling value of 39.3 is :{ceil(39.3)}") # 40 16 | # Printing the floor value 17 | # This is the biggest integer NOT greater than the number 18 | # you defined. 19 | print(f"The floor value of 39.3 is : {floor(39.3)}") # 39 20 | 21 | print("-" * 10) 22 | 23 | # Finding the gcd of 4 and 14 24 | print(f"The gcd of 4 and 14 is : {gcd(4,14)}") # prints 2 25 | # Finding the gcd of 14 and 63 26 | print(f"The gcd of 63 and 14 is : {gcd(63,14)}") # prints 7 27 | 28 | print("-" * 10) 29 | 30 | # Finding the factorial of 5 31 | print(f"The factorial of 5 is : {factorial(5)}") # prints 120 32 | # Finding the factorial of 7 33 | print(f"The factorial of 7 is : {factorial(7)}") # prints 5040 34 | 35 | print("-" * 10) 36 | 37 | 38 | #Supply a name 39 | user_name = input("Enter your name:") 40 | #Enter the age 41 | user_age = input("Enter your age:") 42 | # Printing using commas 43 | print("Hello,", user_name, "! you are now ", user_age) 44 | # Printing using string concatenation 45 | print("Hello," + user_name + "! you are now " + str(user_age)) 46 | # Printing using f-strings 47 | print(f"Hello,{user_name}! you are now {user_age}") 48 | 49 | 50 | -------------------------------------------------------------------------------- /chapter3/string_usage_file_1.py: -------------------------------------------------------------------------------- 1 | 2 | # Printing Hello world 3 | print("Hello World!") 4 | 5 | print("-"*10) 6 | 7 | # Inserting a new line between strings 8 | print("Hello\nWorld!") 9 | 10 | print("-"*10) 11 | 12 | # Printing HelloWorld! inside single quotes 13 | print("'HelloWorld!'") 14 | 15 | print("-"*10) 16 | 17 | # Printing a particular character, say * 10 times. 18 | print("*" * 10) 19 | 20 | print("-"*10) 21 | 22 | print("Abc\bd") #Prints Abd, but in IDLE the output is different. 23 | 24 | print("-"*10) 25 | 26 | # Trying to print HelloWorld! inside double quotes 27 | # print(""HelloWorld""); #Error 28 | # Using the escape characters 29 | print(" \"Hello World! \" ") 30 | # Printing the text message using a string variable. 31 | my_text = "Hello World!" 32 | print(my_text) 33 | 34 | print("-"*10) 35 | # Concatenation example 36 | text1 = "Hello, Reader!" 37 | text2 = " How are you?" 38 | text3 = " Hope everything is fine." 39 | print(text1+text2+text3) 40 | 41 | print("-"*10) 42 | 43 | # Use of functions 44 | text1 = " Hello, Reader!" 45 | print("The original string is:" + text1) 46 | # Printing text1 in uppercase 47 | print(text1.upper()) 48 | # Printing text1 in lowercase 49 | print(text1.lower()) 50 | 51 | print("-"*10) 52 | # Using multiple functions together 53 | text1 = " Hello, Reader!" 54 | print("The original string is:"+ text1) 55 | print(text1.upper().islower()) #False 56 | print(text1.upper().isupper()) #True 57 | 58 | print("-"*10) 59 | text1 = "Python" 60 | text2 = "Hello, Jon!" 61 | print("The text1 is: " + text1) 62 | print("Length of text1 is as follows:") 63 | #Length of text1 64 | print(len(text1)) 65 | print("The text2 is: " + text2) 66 | print("Length of text2 is as follows:") 67 | #Length of text2 68 | print(len(text2)) 69 | 70 | print("-"*10) 71 | 72 | text1 = "Python" 73 | print("The text1 is: " + text1) 74 | # Printing individual characters inside the string 75 | print(text1[0]) 76 | print(text1[1]) 77 | print(text1[2]) 78 | print(text1[3]) 79 | print(text1[4]) 80 | print(text1[5]) 81 | 82 | print("-"*10) 83 | 84 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /chapter3/string_usage_file_2.py: -------------------------------------------------------------------------------- 1 | text = "abcABc" 2 | print("The text is: " + text) 3 | # Printing individual characters inside the string 4 | print("The first occurrence of 'A' is at index:") 5 | print(text.index("A")) 6 | print("The first occurrence of 'c' is at index:") 7 | print(text.index("c")) 8 | print("The first occurrence of 'bcA' is at index:") 9 | print(text.index("bcA")) 10 | 11 | print("-"*10) 12 | 13 | # I want to examine what happens if the intended character 14 | # is NOT present inside the string. 15 | text = " Hello, John!" 16 | #print(text.index("y")) #error now 17 | 18 | # I want to examine a function that accepts multiple parameters 19 | # Using the replace() function for this example. 20 | text = "Hello, John!" 21 | print("Initial text is :" + text) 22 | print("Replacing the name 'John' with 'Bob' now.") 23 | text = text.replace("John", "Bob") 24 | print("The changed text is :" + text) 25 | -------------------------------------------------------------------------------- /chapter3/taking_user_input.py: -------------------------------------------------------------------------------- 1 | # Supply a name 2 | user_name = input("Enter your name:") 3 | # Enter the age 4 | user_age = input("Enter your age:") 5 | # Using commas 6 | print("Welcome,", user_name, "! you are now ", user_age) 7 | # Using f-strings(Python 3.6 onwards) 8 | print(f"Welcome,{user_name}! you are now {user_age}") 9 | # Printing using string concatenation 10 | print("Welcome," + user_name + "! you are now " + str(user_age)) 11 | 12 | #user_name="John" 13 | #print(f"Hello, {user_name}!") -------------------------------------------------------------------------------- /chapter4/conditional_expressions.py: -------------------------------------------------------------------------------- 1 | a = input("Enter a valid integer for the dividend:") 2 | b = input("Enter a valid integer for the divisor:") 3 | # Skipping the input validation... 4 | dividend = int(a) 5 | divisor = int(b) 6 | 7 | if divisor != 0: 8 | result = dividend / divisor 9 | print(f"Division successful.The result is:{result}") 10 | else: 11 | print("You cannot proceed when the divisor is 0.") 12 | 13 | # Alternative version 14 | result = 0 # some initial value 15 | result = dividend / divisor if divisor != 0 else print("You cannot set the divisor to 0.") 16 | print(f"The result is:{result}") 17 | 18 | b = 0 19 | #Example:inline -if 20 | a = 5 if b != 0 else 1 21 | print(a) 22 | -------------------------------------------------------------------------------- /chapter4/cs_2.1_implementation.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | x = randint(10, 12) 4 | #First question with initial data 5 | question1 = "2*3-4" 6 | # Replacing 2 in question1 with x 7 | question1 = question1.replace("2", str(x)) 8 | 9 | #Second question with initial data 10 | question2 = "1+(2*3)/4" 11 | # Replacing 1 in question2 with x 12 | question2 = question2.replace("1", str(x)) 13 | 14 | #Third question with initial data 15 | question3 = "5*8%3" 16 | # Replacing 5 in question3 with x 17 | question3 = question3.replace("5", str(x)) 18 | 19 | # The randint(1,3) function returns a number 20 | # between 1 and 3 (both included) 21 | pick_question = randint(1,3) 22 | if pick_question == 1: 23 | quiz = question1 24 | elif pick_question == 2: 25 | quiz = question2 26 | else: 27 | quiz = question3 28 | 29 | print(f"Predict the value of the following expression:{quiz}") 30 | # User's input 31 | user_input = input("Enter your answer:") 32 | # Converting it to float 33 | predicted_value = float(user_input) 34 | actual_value = eval(quiz) 35 | if predicted_value == actual_value: 36 | print("Correct answer.") 37 | else: 38 | print("Your answer is wrong.") 39 | print(f"The correct answer is:{actual_value}") 40 | -------------------------------------------------------------------------------- /chapter4/decision_making_exercises_solutions.py: -------------------------------------------------------------------------------- 1 | #Exercise-4.1 2 | a = 5 3 | if a > 10: 4 | print("The number is greater than 10.") 5 | elif a == 10: 6 | print("The number is equal to 10.") 7 | print("--------End of Exercise 4.1----------------") 8 | 9 | #Exercise-4.2 10 | a = 5 11 | #if a < 7 and a > 9: # Wrong logic.This condition cannot be satisfied. 12 | if a < 7 or a > 9: # ok. 13 | print("The condition is satisfied.") 14 | else: 15 | print("The condition will never be satisfied.") 16 | print("--------End of Exercise 4.2----------------") 17 | 18 | #Exercise-4.3 19 | number = 0 20 | #number = -34 21 | if number: 22 | print(f"The condition is satisfied.number={number}") 23 | else: 24 | print(f"The condition is not satisfied.number={number}") 25 | 26 | print("--------End of Exercise 4.3----------------") 27 | -------------------------------------------------------------------------------- /chapter4/demo5b_not_recommended.py: -------------------------------------------------------------------------------- 1 | print("Demo5b-Not recommended.") 2 | user_input = input("Enter a valid numbers only:") 3 | # For simplicity, skipping the validation of user's input 4 | a = float(user_input) 5 | if a < 0: 6 | print("The number is less than 0.") 7 | else: 8 | if a < 1: 9 | print("The number is greater than 0 but less than 1.") 10 | else: 11 | if a == 1: 12 | print("The number is equal to 1.") 13 | else: 14 | if a == 2: 15 | print("The number is equal to 2.") 16 | else: 17 | if a == 3: 18 | print("The number is equal to 3.") 19 | else: 20 | print("The number is greater than 3.") 21 | -------------------------------------------------------------------------------- /chapter4/demo7_not_recommened.py: -------------------------------------------------------------------------------- 1 | # Demo7 2 | print("Demo7-Not recommended") 3 | user_input = input("Enter a valid number only:") 4 | # For simplicity, skipping the validation of user's input 5 | a = float(user_input) 6 | if a > 10: 7 | print("The number is greater than 10.") 8 | else: 9 | if a == 10: 10 | print("The number is equal to 10.") 11 | else: 12 | print("The number is less than 10.") 13 | -------------------------------------------------------------------------------- /chapter4/using_if_statments.py: -------------------------------------------------------------------------------- 1 | # Demo1 2 | a = 11 3 | print("Demo1") 4 | if a > 10: 5 | print("The current value inside a is greater than 10.") 6 | # Demo2 7 | print("Demo2") 8 | a = 5 9 | if a > 10: 10 | print("The current value inside a is greater than 10.") 11 | else: 12 | print("The current value of a is less than or equal to 10.") 13 | 14 | # Demo3 15 | print("Demo3") 16 | a = 5 17 | if a == 5: 18 | print("a is equal to 5.") 19 | else: 20 | print("a is NOT equal to 5.") 21 | 22 | # Demo4 23 | print("Demo4") 24 | a = 25 25 | if a != 7: 26 | print("a is NOT equal to 7.") 27 | else: 28 | print("a is equal to 7.") 29 | 30 | # Demo5 31 | print("Demo5") 32 | user_input = input("Enter a valid number only:") 33 | # Skipping the validation of user's input 34 | a = float(user_input) 35 | if a > 10: 36 | print("The number is greater than 10.") 37 | elif a == 10: 38 | print("The number is equal to 10.") 39 | else: 40 | print("The number is less than 10.") 41 | 42 | # Demo6 43 | print("Demo6") 44 | user_input = input("Enter your age:") 45 | # Skipping the validation of user's input 46 | age = float(user_input) 47 | if age < 10: 48 | print("Hi Dear.You can use the product for free.") 49 | elif age>= 10 and age <20: 50 | print("Please donate 1$ for the product.") 51 | elif age >= 20 and age < 30: 52 | print("Please donate 2$ for the product.") 53 | elif age >= 30 and age < 40: 54 | print("Please donate 3$ for the product.") 55 | else: 56 | print("Please donate 4$ for the product.") 57 | 58 | # Demo6.1-Improvement to demo6 59 | print("Demo6.1") 60 | user_input = input("Enter your age :") 61 | # For simplicity, skipping the validation of user's input 62 | age = float(user_input) 63 | if age < 10: 64 | print("Hi Dear.You can use the product for free.") 65 | #I’m simplifying the expression 66 | elif 10 <= age < 20: 67 | print("Please donate 1$ for the product.") 68 | #Using brackets for better readability 69 | elif (age >= 20) and (age < 30): 70 | print("Please donate 2$ for the product.") 71 | # Using brackets for better readability 72 | elif (age >= 30) and (age < 40): 73 | print("Please donate 3$ for the product.") 74 | else: 75 | print("Please donate 4$ for the product.") 76 | -------------------------------------------------------------------------------- /chapter5/assignment_5_dot_1.py: -------------------------------------------------------------------------------- 1 | # Solution to Assignment 5.1 2 | # Initially flag contains an empty string. 3 | # We need a string other than quit to enter 4 | # into the while loop and 5 | # to proceed further. 6 | flag = "" 7 | while flag != 'quit': 8 | user_input = input("Enter a valid number(Type quit to end the program): ") 9 | # If the user does not type 'quit' 10 | # we can convert valid user input to float 11 | if user_input != 'quit': 12 | user_input = float(user_input) 13 | else: 14 | flag = 'quit' 15 | break; # exit from the loop 16 | if user_input > 0: 17 | print("You have supplied is a positive number.") 18 | elif user_input < 0: 19 | print("The supplied number is a negative number.") 20 | else: 21 | print("You've entered 0.") 22 | 23 | print("Thank you. It is the end of the program.") 24 | -------------------------------------------------------------------------------- /chapter5/assignment_5_dot_2.py: -------------------------------------------------------------------------------- 1 | # Solution to Assignment 5.2 2 | # A list of numbers 3 | number_list = [1, 2.2, 4.4, 5, 6, 9.3, 102] 4 | print("Printing the numbers inside number_list using a 'for' loop:") 5 | for number in number_list: 6 | print(number) 7 | 8 | print("Now printing the numbers which have the index between 2 and 5:") 9 | for index in range(2, 6): 10 | print(number_list[index]) -------------------------------------------------------------------------------- /chapter5/assignment_5_dot_3_dot_4_dot_5.py: -------------------------------------------------------------------------------- 1 | # Assignment 5.3 2 | for i in range(10, 20, 5): 3 | print(i) 4 | print("--"*10) 5 | # Assignment 5.4 6 | for i in range(20, 9, -5): 7 | print(i) 8 | print("--"*10) 9 | 10 | # Assignment 5.5 11 | for i in range(10, -10, -5): 12 | #print(i) 13 | print("*") 14 | -------------------------------------------------------------------------------- /chapter5/break_statement_example1.py: -------------------------------------------------------------------------------- 1 | print("***Using a break statement inside a while loop.***" ) 2 | current_value = 1 3 | print(f"Initially, current_value={current_value}") 4 | print("Exit the loop when current_value becomes 3.") 5 | while current_value < 5: 6 | # incrementing the value 7 | current_value += 1 8 | print(f"The current value={current_value}") 9 | if current_value == 3: 10 | break 11 | print("I'm still inside the while loop.") 12 | # This statement is placed outside the while loop 13 | print("Job done.I've exited from the while loop.") 14 | -------------------------------------------------------------------------------- /chapter5/continue_statement_example.py: -------------------------------------------------------------------------------- 1 | print("***Using a continue statement inside a while loop.***") 2 | current_value = 1 3 | print(f"Initially, current_value={current_value}") 4 | print("I skip the code when current_value becomes 3.") 5 | while current_value < 5: 6 | # incrementing the value 7 | current_value += 1 8 | print(f"The current value={current_value}") 9 | if current_value == 3: 10 | continue 11 | print("I'm still inside the while loop.") 12 | # This statement is placed outside the while loop 13 | print("Job has been done. Exit from the while loop.") 14 | 15 | -------------------------------------------------------------------------------- /chapter5/cs_3.1_implementation.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | picked_number = randint(1, 15) 4 | print("The computer has picked a random number for you.") 5 | print("Clue: It is between 1 and 15 (both inclusive).") 6 | print("Can you guess it within 3 attempts? Make a try.") 7 | no_of_attempt = 0 8 | guess = False 9 | user_input = 0 # an initial value 10 | while no_of_attempt < 3: 11 | #User's input 12 | user_input = int(input("Enter your answer:")) 13 | no_of_attempt += 1 14 | if user_input == picked_number: 15 | guess = True 16 | break 17 | elif user_input > picked_number: 18 | print("It is high. Try again!") 19 | else: 20 | print("It is low. Try again!") 21 | if guess: 22 | print("Excellent. You have guessed it right.") 23 | print(f"you've taken {no_of_attempt} attempt(s).") 24 | else: 25 | print(f"The computer picked the number:{picked_number}.") 26 | print("You have lost the game now!") 27 | -------------------------------------------------------------------------------- /chapter5/for_loop_example.py: -------------------------------------------------------------------------------- 1 | # Printing 1 to 10 using for loop 2 | print("Printing 1 to 10 using a 'for' loop:") 3 | # I use the range(1,11) function to print 4 | # values 1 to 11-1=10 5 | for current_value in range(1, 11): 6 | print(current_value) 7 | # This statement is placed outside the for loop 8 | print("Job has been done. Exit from the 'for' loop.") 9 | 10 | -------------------------------------------------------------------------------- /chapter5/infinite_loop_example.py: -------------------------------------------------------------------------------- 1 | # An incorrect implementation of while loop. 2 | # It creates an infinite loop. 3 | i = 0 4 | while i != 1: 5 | print(f"I cannot come out from the loop.i={i}.") 6 | -------------------------------------------------------------------------------- /chapter5/nested_loop_ex_1.py: -------------------------------------------------------------------------------- 1 | print("*** Nested loop example.***") 2 | colors = ["Red", "Green", "Yellow"] 3 | fruits = ["Mango", "Banana"] 4 | for color in colors: 5 | for fruit in fruits: 6 | print(color, fruit, end=" ") 7 | print() 8 | -------------------------------------------------------------------------------- /chapter5/print_upto_3.py: -------------------------------------------------------------------------------- 1 | # Need for iteration 2 | print(1) 3 | print(2) 4 | print(3) 5 | print("----------------") 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /chapter5/printing_employee_names_using_for_loop.py: -------------------------------------------------------------------------------- 1 | # Printing employee names using for loop 2 | employee_names = ["Sam", "Bob", "George", "Kate", "Julie"] 3 | print("Printing employee names using a 'for' loop:") 4 | for employee in employee_names: 5 | print(employee) 6 | 7 | #for i in employee_names: 8 | # print(i) 9 | -------------------------------------------------------------------------------- /chapter5/while_loop_ex_1.py: -------------------------------------------------------------------------------- 1 | # Printing 1 to 10 using while loop 2 | print("Printing 1 to 10 using while loop:") 3 | current_value = 1 4 | while current_value <= 10: 5 | print(current_value) 6 | # incrementing the value 7 | # Following line is a shortcut for : 8 | # current_value=Current_value+1 9 | current_value += 1 10 | # This statement is placed outside the while loop 11 | print("Job has done. Exit from the while loop.") -------------------------------------------------------------------------------- /chapter6/cs_4.1_implementation.py: -------------------------------------------------------------------------------- 1 | # All questions 2 | question1 = "Q1.What is the value of the expression:2*3-4?" \ 3 | "\n(a)1" \ 4 | "\n(b)2" \ 5 | "\n(c)3" \ 6 | "\n(d)None." 7 | question2 = "\nQ2.What is the value of the expression:1+(2*3)/4?" \ 8 | "\n(a)1.5" \ 9 | "\n(b)3" \ 10 | "\n(c)3.5" \ 11 | "\n(d)None." 12 | question3 = "\nQ3.The set data type can hold duplicate values." \ 13 | "The statement is:" \ 14 | "\n(a)False" \ 15 | "\n(b)True" \ 16 | "\n(c)Partially correct." \ 17 | "\n(d)None." 18 | 19 | # Storing the questions with answer keys 20 | # inside the following dictionary. 21 | question_bank = {question1: "b", question2: "c", question3: "a"} 22 | print("Welcome to the MCQ test.") 23 | print("="*25) 24 | score = 0 # initial value 25 | for key in question_bank: 26 | print(key) 27 | user_input = input("Type your answer(a/b/c/d):") 28 | if user_input == question_bank[key]: 29 | score += 1 30 | print(f"\nYour Score:{score} out of {len(question_bank)}") 31 | -------------------------------------------------------------------------------- /chapter6/dictionary_usage_file.py: -------------------------------------------------------------------------------- 1 | # A dictionary with with 5 key-value pair 2 | my_dictionary = {1: "John", 2: 12, 3: "Sam", 4: True, 5: 50.7} 3 | print("The my_dictionary contains:") 4 | print(my_dictionary) 5 | print("----------------") 6 | 7 | # A dictionary with 5 key-value pair 8 | # Choosing different types of keys in the same dictionary 9 | my_dictionary = {1: "John", 2: 12, 3: "Sam", 'fourth': True, 'fifth': 50.7} 10 | print("The my_dictionary contains:") 11 | print(my_dictionary) 12 | print("----------------") 13 | 14 | # I want to print values for particular keys 15 | my_dictionary = {1: "John", 2: 12, 3: "Sam", 'fourth': True, 'fifth': 50.7} 16 | print("The my_dictionary contains:") 17 | print(my_dictionary) 18 | print("Value at key 1:", my_dictionary[1]) 19 | print("Value at key 2:", my_dictionary[2]) 20 | print("Value at key 3:", my_dictionary[3]) 21 | print("Value at key 'fourth':", my_dictionary['fourth']) 22 | print("Value at key 'fifth'::", my_dictionary['fifth']) 23 | print("----------------") 24 | 25 | # If you assign different values for the same keys 26 | # last assigned value will be kept 27 | my_dictionary = {1: "John", 2: "Sam", 3: "Jack",1: "Bob"} 28 | print("The my_dictionary contains:") 29 | print(my_dictionary) 30 | print("Value at key 1:", my_dictionary[1]) 31 | print(f"Number of contents:{len(my_dictionary)}") 32 | print("----------------") 33 | -------------------------------------------------------------------------------- /chapter6/exercise_solutions.py: -------------------------------------------------------------------------------- 1 | print("Exercise 6.1") 2 | print("-"*15) 3 | my_list = ["John", 12, 25, 12, "Sam", True, 50.7] 4 | print("The original list is:") 5 | print(my_list) 6 | #Removing the last two elements from the list 7 | del(my_list[-2:]) 8 | print("Now the list is:") 9 | print(my_list) 10 | 11 | print("-"*15) 12 | 13 | print("Exercise 6.2") 14 | print("-"*15) 15 | my_tuple = ("John", 12, 25, 12, "Sam", True, 50.7) 16 | print("The original tuple is:") 17 | print(my_tuple) 18 | #Printing the 3 element 19 | print("The third element:") 20 | print(my_tuple[2]) 21 | print("The third element from last:") 22 | print(my_tuple[-3]) 23 | print("-"*15) 24 | 25 | print("Exercise 6.3") 26 | print("-"*15) 27 | my_tuple = (1, 2, 2, 3, 4, 4, 4, 5) 28 | print("The original tuple is:") 29 | print(my_tuple) 30 | 31 | print("The reversed tuple is:") 32 | rev_tuple = tuple(reversed(my_tuple)) 33 | print(rev_tuple) 34 | 35 | print(f"The number of 4 in this tuple:{rev_tuple.count(4)}") 36 | 37 | print("Exercise 6.5") 38 | print("-"*15) 39 | my_tuple = (1, 2, 2, 3, 4, 4, 5) 40 | my_set = set(my_tuple) 41 | print("The my_set is:") 42 | print(my_set) 43 | 44 | print("Exercise 6.6") 45 | print("-"*15) 46 | my_list=["red", "blue"] 47 | my_set = set(my_list) 48 | print("The my_set is:") 49 | print(my_set) 50 | my_set.discard("green") 51 | 52 | -------------------------------------------------------------------------------- /chapter6/list_usage_file_2.py: -------------------------------------------------------------------------------- 1 | 2 | # Finding the maximum and minimum from a list 3 | # This list contains the numbers only 4 | my_list = [1, 23, 56.2, -3.7, 999] 5 | print("The original list is:") 6 | print(my_list) 7 | print(f"The largest number is:{max(my_list)}") # 999 8 | print(f"The smallest number is:{min(my_list)}") # -3.7 9 | print("----------------") 10 | 11 | 12 | #For this segment, you'll receive error 13 | #my_list = [1, 23, 56.2, -3.7, 999, "abc", "bob"] 14 | #print("The original list is: ") 15 | #print(my_list) 16 | #print(f"The largest number is:{max(my_list)}") 17 | #print(f"The smallest number is:{min(my_list)}") 18 | 19 | 20 | # Testing booleans with max() and min() 21 | my_list = [0.75, True, False, 0.5, 0.6, 1, 0] 22 | print("The original list is:") 23 | print(my_list) 24 | print(f"The largest number is:{max(my_list)}") # True 25 | print(f"The smallest number is:{min(my_list)}") # False 26 | print("----------------") 27 | 28 | 29 | # have interchanged the positions of True and 1 in this list. 30 | #Also, at the same time, I have interchanged the position of False and 0 here) 31 | 32 | # Testing booleans with max() and min() 33 | my_list = [0.75, 1, 0, 0.5, 0.6, True, False] 34 | print("The original list is:") 35 | print(my_list) 36 | print(f"The largest number is:{max(my_list)}") # 1 37 | print(f"The smallest number is:{min(my_list)}") # 0 38 | print("----------------") 39 | 40 | # I want to add an element at the end of a list 41 | my_list = ["John", 12, "Sam", True, 50.7] 42 | print("The original list is:") 43 | print(my_list) 44 | print("Appending 25 at the end of list.") 45 | my_list.append(25) 46 | print("Now the list is:") 47 | print(my_list) 48 | print("Appending another element 'Bob' now.") 49 | my_list.append("Bob") 50 | print("The modified list:") 51 | print(my_list) 52 | #Using append(), at a time, you can add one element only. 53 | #my_list.append(10,20) #error 54 | 55 | print("----------------") 56 | ''' 57 | You have just that using append(), you can add a single element only. 58 | But this function allows you to add a list that contains multiple elements. 59 | Let’s see how it looks after this addition. 60 | ''' 61 | 62 | my_list = ["John", 12, "Sam", True, 50.7] 63 | print("The initial list is:") 64 | print(my_list) 65 | print("Appending [10,'Bob',100.2] at the end of the list:") 66 | my_list.append([10, 'Bob', 100.2]) 67 | print("The modified list:") 68 | print(my_list) 69 | print("----------------") 70 | 71 | # You can add multiple elements to a list 72 | # using extend() function. 73 | # Here is an example. 74 | my_list = ["John", 12, "Sam", True, 50.7] 75 | print("The original list is as follows") 76 | print(my_list) 77 | print("Adding 10,'Bob', and 100.2 at the list end.") 78 | my_list.extend([10, 'Bob', 100.2]) 79 | print("Now the list is as follows:") 80 | print(my_list) 81 | print("----------------") 82 | 83 | #Till now, you saw that I’m adding the elements at the end of a list. 84 | #But you have the option to add an element in a particular position. 85 | my_list = ["John", 12, "Sam", True, 50.7] 86 | print("The original list is:") 87 | print(my_list) 88 | print("Adding the element 'Jack' at index 3.") 89 | my_list.insert(3, "Jack") 90 | print("Now the list is as follows:") 91 | print(my_list) 92 | print("----------------") 93 | 94 | 95 | #Using sort() 96 | my_list = [33, 11, 555, 77, 111, 333] 97 | print("The initial list is:") 98 | print(my_list) 99 | print("Using sort() on my_list now.") 100 | my_list.sort() 101 | print("Now the list is:") 102 | print(my_list) 103 | print("----------------") 104 | 105 | #Using sorted() 106 | my_list = [33, 11, 555, 77, 111, 333] 107 | print("Initially, my_list is:") 108 | print(my_list) 109 | print("Printing the sorted list now.") 110 | print(sorted(my_list)) 111 | print("The my_list now:") 112 | print(my_list) 113 | print("----------------") 114 | -------------------------------------------------------------------------------- /chapter6/list_usages_file_1.py: -------------------------------------------------------------------------------- 1 | # A list with three strings 2 | my_list1 = ["John","Bob","Sam"] 3 | print("The my_list1 is as follows:") 4 | print(my_list1) 5 | 6 | # A list with five numbers 7 | my_list2 = [1,2,3.7,4,5.2] 8 | print("The my_list2 is as follows:") 9 | print(my_list2) 10 | 11 | print("----------------") 12 | 13 | # A list can store mixed data types 14 | my_list = ["John",12,"Sam",True,50.7] 15 | print(my_list) 16 | print("----------------") 17 | 18 | # You can use list index.The usage is similar to strings. 19 | my_list = ["John",12,"Sam",True,50.7] 20 | print(my_list[0]) # John 21 | print(my_list[1]) # 12 22 | print(my_list[2]) # Sam 23 | print(my_list[3]) # True 24 | print(my_list[4]) # 50.7 25 | # Error: List index out of range 26 | # print(my_list[5]) 27 | print("----------------") 28 | 29 | # You can use list indexing from the right end. 30 | # In this case, it starts from -1 31 | my_list = ["John",12,"Sam",True,50.7] 32 | print(my_list[-1]) # 50.7 33 | print(my_list[-2]) # True 34 | print(my_list[-3]) # Sam 35 | print(my_list[-4]) # 12 36 | print(my_list[-5]) # John 37 | # Error: List index out of range 38 | # print(my_list[-6]) 39 | print("----------------") 40 | 41 | # Printing list elements starting from a particular position 42 | my_list = ["John",12,"Sam",True,50.7] 43 | print("The original list is as follows:") 44 | print(my_list) 45 | print("Printing the elements starting from index position 2 to end:") 46 | print(my_list[2:]) 47 | print("Printing the elements starting from index position 1 to 3(i.e.4-1):") 48 | print(my_list[1:4]) 49 | print("----------------") 50 | 51 | # You can reassign a new value inside the list 52 | my_list = ["John",12,"Sam",True,50.7] 53 | print("The original list is as follows:") 54 | print(my_list) 55 | print("Changing the element at index 2.") 56 | my_list[2] = "Bob" 57 | print("Now the list is as follows:") 58 | print(my_list) 59 | print("----------------") 60 | 61 | # Concatenation example 62 | my_list1 = ["John",12,50.7] 63 | my_list2 = ["Sam",25,"John",False,100.2] 64 | print("Original lists are :") 65 | print(my_list1) 66 | print(my_list2) 67 | print("After concatenating the lists, you get the following list:") 68 | print(my_list1 + my_list2) 69 | print("----------------") 70 | 71 | # Printing specific number of elements of a list from end. 72 | my_list = ["John",12,"Sam",True,50.7] 73 | print("The original list is:") 74 | print(my_list) 75 | print("The last 3 elements of the list are:") 76 | print(my_list[-3:]) 77 | print("The last 2 elements of the list are:") 78 | print(my_list[-2:]) 79 | print("The last element of the list is:") 80 | print(my_list[-1]) 81 | print("----------------") 82 | 83 | # Removing an element using del() 84 | my_list = ["John", 12, "Sam", True, 50.7] 85 | print("The original list is:") 86 | print(my_list) 87 | print("Removing the element at index 2.") 88 | del (my_list[2]) 89 | print("Now the list is:") 90 | print(my_list) 91 | print("Removing the element at index 3 from this updated list.") 92 | del (my_list[3]) 93 | print("The updated list is:") 94 | print(my_list) 95 | print("----------------") 96 | 97 | # Removing an element using remove() function 98 | my_list = ["John", 12, 25, 12, "Sam", True, 50.7] 99 | print("The original list is:") 100 | print(my_list) 101 | print("Removing the first occurrence of 12 inside the list.") 102 | my_list.remove(12) 103 | print("Now the list is:") 104 | print(my_list) 105 | print("----------------") 106 | 107 | # Elements are case-sensitive 108 | my_list = ["John", 12, "sam", 25.7, "Sam", True] 109 | print("The original list is:") 110 | print(my_list) 111 | print("Removing the first occurrence of 'Sam' inside the list.") 112 | my_list.remove('Sam') 113 | print("Now the list is:") 114 | print(my_list) 115 | print("----------------") 116 | 117 | # Removing an element using pop() 118 | my_list = ["John", 12, 25, 12, "Sam", True, 50.7] 119 | print("The original list is:") 120 | print(my_list) 121 | print("Removing an element inside the list at index 3 using pop().") 122 | my_list.pop(3) 123 | print("Now the list is:") 124 | print(my_list) 125 | print("----------------") 126 | 127 | # Checking whether an element is present inside a list 128 | my_list = ["John", "Bob", "Sam", "Ester", 1, 2, 3, 4] 129 | print("Is 'Sam' present inside the list?") 130 | print('Sam' in my_list) # True 131 | print("Is 'Jeniffer' present inside the list?") 132 | print('Jennifer' in my_list) # False 133 | print("Is 3 present inside the list?") 134 | print(3 in my_list) # True 135 | print("Is 5 present inside the list?") 136 | print(5 in my_list) # False 137 | 138 | # Checking whether an element is absent inside a list 139 | print("Is 'Jeniffer' NOT present inside the list?") 140 | print('Jennifer' not in my_list) # True 141 | 142 | -------------------------------------------------------------------------------- /chapter6/set_usage_file.py: -------------------------------------------------------------------------------- 1 | # Creating a set 2 | my_set = {1, 2, 3, "Jack", "Bob"} 3 | print("The my_set contains:") 4 | print(my_set) 5 | print("----------------") 6 | 7 | # Alternative way to create a set 8 | # my_set=set(iterable_element) 9 | # Using a list now to create a set 10 | my_set = set([1, 2, 3, "Jack", "Bob"]) 11 | print("The my_set contains:") 12 | print(my_set) 13 | print("----------------") 14 | 15 | # Using a tuple to create a set 16 | my_set = set((1, 2, 3, "Jack", "Bob")) 17 | print("The my_set contains:") 18 | print(my_set) 19 | print("----------------") 20 | 21 | # A set does not contain duplicates 22 | my_set1 = {1, 2, 3, "Jack", 2, "Bob", 3, 1} 23 | print("The my_set1 contains:") 24 | print(my_set1) 25 | 26 | my_set2 = {"Sam", "Bob", "Jack", "Sam", "Jack", "Ester"} 27 | print("The my_set2 contains:") 28 | print(my_set2) 29 | print("----------------") 30 | 31 | # Sets are mutable 32 | my_set = {1, 2, 3, 4, 5} 33 | #my_set = {}#it is treated as empty dictionary 34 | #my_set=set()#this is ok for an empty set 35 | print("The my_set contains:") 36 | print(my_set) 37 | print("Adding 6 to the set now.") 38 | my_set.add(6) 39 | print("Now the set is:") 40 | print(my_set) 41 | print("Removing 2 from the set now.") 42 | my_set.remove(2) 43 | print("Now, the my_set is:") 44 | print(my_set) 45 | print("----------------") 46 | 47 | # Strings are iterables.So, you can use strings to set(). 48 | my_str = "vaskaran" 49 | my_set = set(my_str) 50 | print("The my_set contains:") 51 | print(my_set) 52 | 53 | print("----------------") 54 | # Sets are unordered.You cannot access the elements by referring an index 55 | my_set = set([2,"hello",1,5]) 56 | print("The my_set contains:") 57 | print(my_set) 58 | print("Trying to access the 0th element.") 59 | #print(my_set[0])#error 60 | 61 | # You cannot access set elements by referring an index. 62 | # But You can loop through the elements. 63 | my_set = set([2,"abc",1,5]) 64 | print("The my_set contains:") 65 | for item in my_set: 66 | print(item) 67 | 68 | print("----------------") 69 | # Remove an element from a set 70 | my_set = set([1,2,3,4,5]) 71 | print("The my_set contains:") 72 | print(my_set) 73 | print("Removing 5 using remove().") 74 | my_set.remove(5) 75 | print("Now the my_set contains:") 76 | print(my_set) 77 | print("Removing 4 now using discard().") 78 | my_set.discard(4) 79 | print("Now the my_set contains:") 80 | print(my_set) 81 | 82 | # Trying to remove 4 when it is absent in the set. 83 | #my_set.discard(4) # no error is raised 84 | #my_set.remove(4) # error is raised 85 | print("----------------") 86 | 87 | -------------------------------------------------------------------------------- /chapter6/tuple_usage_file.py: -------------------------------------------------------------------------------- 1 | # A tuple with 5 elements 2 | my_tuple = ("John", 12, "Sam", True, 50.7) 3 | print("The content of my_tuple is:") 4 | print(my_tuple) 5 | #my_tuple.remove(12) #error 6 | #my_tuple.append("Jack") #error 7 | print("----------------") 8 | 9 | # Indexing is similar to lists 10 | my_tuple = ("John", 12, "Sam", True, 50.7) 11 | print("The content of my_tuple is:") 12 | print(my_tuple) 13 | # Printing the first element 14 | print("The first element is:") 15 | print(my_tuple[0]) 16 | print("The last element is:") 17 | print(my_tuple[-1]) 18 | print("Printing the elements from index 1 to index 3.") 19 | print(my_tuple[1:4]) 20 | print("Printing the elements from index 2 to end.") 21 | print(my_tuple[2:]) 22 | print("----------------") 23 | 24 | # You cannot reassign the value inside a tuple. 25 | my_tuple = ("John", 12, "Sam", True, 50.7) 26 | print("The content of my_tuple is:") 27 | print(my_tuple) 28 | print("Trying to replace 'Sam' with 'Bob':") 29 | #my_tuple[2]= 'Bob' #error 30 | print("----------------") 31 | 32 | my_list = ["John", 12, "Sam", True, 50.7] 33 | print("The content of my_list is:") 34 | print(my_list) 35 | # Converting the list to a tuple 36 | my_tuple = tuple(my_list) 37 | print("The content of my_tuple is:") 38 | print(my_tuple) 39 | 40 | print("----------------") 41 | 42 | # Reversing a tuple 43 | my_tuple = (1, 2, 3, 4, 5) 44 | print("The content of my_tuple is:") 45 | print(my_tuple) 46 | 47 | print("Reversing the tuple:") 48 | rev_tuple = tuple(reversed(my_tuple)) 49 | print("The content of rev_tuple is:") 50 | print(rev_tuple) 51 | 52 | 53 | -------------------------------------------------------------------------------- /chapter7/chap7_exercise.py: -------------------------------------------------------------------------------- 1 | print("Exercise-7.1") 2 | 3 | 4 | def print_x(x): 5 | print(x) 6 | 7 | 8 | def print_y(y): 9 | print(y) 10 | 11 | 12 | def main(): 13 | print_x(10) 14 | print_y(20) 15 | 16 | 17 | main() 18 | print("-" * 30) 19 | 20 | print("Exercise-7.2") 21 | 22 | 23 | def print_me(x): 24 | x += 2 25 | print(x) 26 | 27 | 28 | def print_me(x): 29 | x += 3 30 | print(x) 31 | 32 | 33 | print_me(5) 34 | print("-" * 30) 35 | 36 | print("Exercise-7.3") 37 | 38 | 39 | def print_me(x): 40 | x += 2 41 | print(x) 42 | 43 | 44 | def print_me(y): 45 | y += 3 46 | print(y) 47 | 48 | 49 | print_me(5) 50 | print("-" * 30) 51 | 52 | print("Exercise-7.4") 53 | 54 | x = 10 55 | print(f"x={x}") 56 | 57 | 58 | def print_me(x): 59 | x += 2 60 | print(f"Now x={x}") 61 | 62 | 63 | print_me(x) 64 | print(f"Here x={x}") 65 | print("-" * 30) 66 | 67 | print("Exercise-7.5") 68 | 69 | 70 | def print_me(x): 71 | print(x) 72 | 73 | 74 | def print_me(x, y): 75 | print(x) 76 | print(y) 77 | 78 | 79 | #print_me(5) # error now 80 | print_me(5,7) # ok 81 | print("-" * 30) 82 | 83 | print("Exercise-7.6") 84 | original_list = [100, 200, 300, 400, 500] 85 | # Adds 2 to each item in the list 86 | new_list = list(map(lambda x: x * 1.05, original_list)) 87 | print("The original list is as follows:") 88 | print(original_list) 89 | print("The updated list is as follows:") 90 | print(new_list) 91 | -------------------------------------------------------------------------------- /chapter7/cs_5.1_implementation.py: -------------------------------------------------------------------------------- 1 | print("=" * 25) 2 | print("This is a simple calculator.") 3 | print("It supports the following operations:") 4 | print("i)Addition" 5 | "\nii)Subtraction" 6 | "\niii)Multiplication and " 7 | "\niv)Division.") 8 | print("=" * 25) 9 | valid_operators = ["+", "-", "*", "/"] 10 | 11 | 12 | def add_numbers(num1, num2): 13 | """ 14 | Adds the numbers. 15 | """ 16 | return num1 + num2 17 | 18 | 19 | def subtract_numbers(num1, num2): 20 | """ 21 | Subtracts the numbers. 22 | """ 23 | return num1 - num2 24 | 25 | 26 | def multiply_numbers(num1, num2): 27 | """ 28 | Multiplies the numbers. 29 | """ 30 | return num1 * num2 31 | 32 | 33 | def divide_numbers(num1, num2): 34 | """ 35 | Divide num1 by num2. 36 | """ 37 | return num1 / num2 38 | 39 | 40 | def compute(num1, operator, num2): 41 | """ 42 | This function computes the final result. 43 | """ 44 | result = 0 #default value 45 | 46 | if operator == '+': 47 | result = add_numbers(num1,num2) 48 | elif operator == '-': 49 | result = subtract_numbers(num1,num2) 50 | elif operator == '*': 51 | result = multiply_numbers(num1,num2) 52 | else: 53 | result = divide_numbers(num1, num2) 54 | print(f"The final result is:{result}") 55 | 56 | 57 | def main(): 58 | """ 59 | This is the top-level function. 60 | It calls the compute() function. 61 | """ 62 | usr_input1 = input("Enter the first number:") 63 | first_number = float(usr_input1) 64 | usr_input2 = input("Enter the next number:") 65 | second_number = float(usr_input2) 66 | usr_opr = input("Enter an operator(+,-,*,/): ") 67 | if usr_opr in valid_operators: 68 | compute(first_number, usr_opr, second_number) 69 | else: 70 | print("Invalid operator. Cannot compute the result.") 71 | 72 | 73 | main() 74 | -------------------------------------------------------------------------------- /chapter7/cs_5.2_implementation.py: -------------------------------------------------------------------------------- 1 | # All questions 2 | question1 = "Q1.What is the value of the expression:2*3-4?" \ 3 | "\n(a)1" \ 4 | "\n(b)2" \ 5 | "\n(c)3" \ 6 | "\n(d)None." 7 | question2 = "\nQ2.What is the value of the expression:1+(2*3)/4?" \ 8 | "\n(a)1.5" \ 9 | "\n(b)3" \ 10 | "\n(c)3.5" \ 11 | "\n(d)None." 12 | question3 = "\nQ3.The set data type can hold duplicate values." \ 13 | "The statement is:" \ 14 | "\n(a)False" \ 15 | "\n(b)True" \ 16 | "\n(c)Partially correct." \ 17 | "\n(d)None." 18 | 19 | # Storing the questions with answer keys 20 | # inside the following dictionary. 21 | question_bank = {question1: "b", 22 | question2: "c", 23 | question3: "a"} 24 | 25 | 26 | def run_test(questions): 27 | """ 28 | This function takes the question bank as a parameter. 29 | You can supply the question bank with answer keys 30 | in this function. 31 | """ 32 | print("Welcome to the MCQ test.") 33 | print("=" * 25) 34 | score = 0 # initial value 35 | for key in questions: 36 | print(key) 37 | user_input = input("Type your answer(a/b/c/d):") 38 | if user_input == question_bank[key]: 39 | score += 1 40 | print(f"\nYour Score:{score} out of {len(questions)}") 41 | 42 | 43 | run_test(question_bank) 44 | -------------------------------------------------------------------------------- /chapter7/global_variable_example.py: -------------------------------------------------------------------------------- 1 | print("Example of a global variable.") 2 | x = 10 3 | print(f"x={x}") 4 | 5 | 6 | def print_me(): 7 | global x 8 | x += 2 9 | print(f"Now x={x}") 10 | 11 | 12 | print_me() 13 | print(f"Here x={x}") 14 | print("-" * 30) 15 | -------------------------------------------------------------------------------- /chapter7/importing_entire_module.py: -------------------------------------------------------------------------------- 1 | import my_library # imports the whole module. 2 | print("Accessing some list elements:") 3 | print(f"my_list[0]={my_library.my_list[0]}") 4 | print(f"my_list[3]={my_library.my_list[3]}") 5 | 6 | print("\nAccessing some dictionary elements:") 7 | print(f"my_dictionary[1]={my_library.my_dictionary[1]}") 8 | print(f"my_dictionary[2]={my_library.my_dictionary[2]}") 9 | 10 | print("\nUsing the make_total_double function now.") 11 | result = my_library.make_total_double(20, 30.5) 12 | print(result) 13 | -------------------------------------------------------------------------------- /chapter7/lambda_functions_examples.py: -------------------------------------------------------------------------------- 1 | print("***Demo6***") 2 | print("***Lambda function example-1.***") 3 | say_hello = lambda: print("Hello, Reader!") 4 | say_hello() 5 | 6 | print("***Lambda function example-2.***") 7 | make_double = lambda x:x * 2 8 | print(f"Double of 10 is:{make_double(10)}") 9 | print(f"Double of 25.35 is:{make_double(25.35)}") 10 | 11 | print("\n***Demo7***") 12 | original_list = [1, 2, 3, 4, 5] 13 | # Adds 2 to each item in the list 14 | new_list = list(map(lambda x: x + 2, original_list)) 15 | print("The original list is as follows:") 16 | print(original_list) 17 | print("The updated list is as follows:") 18 | print(new_list) 19 | 20 | -------------------------------------------------------------------------------- /chapter7/using_function_alias.py: -------------------------------------------------------------------------------- 1 | from my_library import make_total_double as mtd 2 | 3 | print("\nUsing the make_total_double function now.") 4 | print("Here mtd is an alias for make_total_double(...)") 5 | result = mtd(20, 30.5) 6 | print(result) 7 | -------------------------------------------------------------------------------- /chapter7/using_functions.py: -------------------------------------------------------------------------------- 1 | #Function example-1 2 | print("***Function example-1.***") 3 | 4 | 5 | def print_hello(): 6 | print("Hello") 7 | 8 | 9 | print_hello() 10 | 11 | #Function example-2 12 | print("\n***Function example-2.***") 13 | 14 | 15 | def print_details(name, age): 16 | """ 17 | This function takes two parameters. 18 | You can supply the name and age of the user 19 | in this function. 20 | """ 21 | print(f"Hello {name}! How are you?") 22 | print(f"You are now {age}.") 23 | 24 | 25 | print_details("Bob", 20) 26 | #You can repeat function calls. 27 | print_details("Bob", 20) 28 | # You can vary the arguments of the functions 29 | print_details("Sam", 35) 30 | 31 | #The following will print the function documentation 32 | #print(print_details.__doc__) 33 | 34 | #Use of positional arguments are important 35 | #print_details("Bob",20) #Ok,expected outcome 36 | print_details(20, "Bob") # Unexpected outcome 37 | 38 | #Use of keyword arguments 39 | print("\n**Using Keyword arguments.**") # Expected outcome 40 | print_details(age=20, name="Bob") # Expected outcome 41 | print_details(name="Bob", age=20) # Again expected outcome 42 | -------------------------------------------------------------------------------- /chapter7/using_functions_part2.py: -------------------------------------------------------------------------------- 1 | print("***Demo2***") 2 | 3 | 4 | #Using default values in a function 5 | def print_details(name="Sam",age=35): 6 | """ 7 | This function takes two parameters. 8 | You can supply the name and age of the user 9 | in this function. 10 | By default, the name is 'Sam' and the age is 35. 11 | """ 12 | print(f"Hello {name}! How are you?") 13 | print(f"You are now {age}.") 14 | 15 | 16 | print_details() #Will take both the default values 17 | print_details(name="Jack") #Will take age=35 as default 18 | print_details(age=45) #Will take name="Sam" as default 19 | #None of the default values are considered 20 | print_details("Bob",20) 21 | 22 | print("\n***Demo3***") 23 | 24 | 25 | def calculate_sum(x,y): 26 | return x + y 27 | 28 | 29 | total = calculate_sum(12,15) 30 | print(f"The sum of 12 and 15 is:{total}") 31 | 32 | total = calculate_sum(20.5,37) 33 | print(f"The sum of 20.5 and 37 is:{total}") 34 | 35 | total = calculate_sum('10','20') #1020 36 | print(f"The sum of '10'' and '20' is:{total}") 37 | 38 | print("\n***Demo4***") 39 | #Demonstration-4 40 | initial_list = [1,2,3,4,5] 41 | double_list = [] 42 | 43 | 44 | def make_double(input_list): 45 | """ 46 | It is function that can return multiple values. 47 | Each element in the list will be doubled 48 | by this function. 49 | """ 50 | for element in input_list: 51 | double_list.append(2 * element) 52 | 53 | 54 | print("The initial_list is :") 55 | print(initial_list) 56 | print("Calling the function make_double() now.") 57 | make_double(initial_list) 58 | print("The double_list is :") 59 | print(double_list) 60 | print("The initial_list at present :") 61 | print(initial_list) #unchanged initial list 62 | 63 | print("***Demo5***") 64 | initial_list = [10, 20, 30, 40, 50] 65 | double_list = [] 66 | 67 | 68 | def make_double(input_list): 69 | """ 70 | It is function that can return multiple values. 71 | Each element in the list will be doubled 72 | by this function. 73 | """ 74 | while input_list: 75 | element = initial_list.pop() 76 | #print(element) 77 | double_list.append(2 * element) 78 | 79 | 80 | print("The initial_list is:") 81 | print(initial_list) 82 | print("Calling the function make_double() now.") 83 | make_double(initial_list) 84 | print("The double_list is:") 85 | print(double_list) 86 | print("The initial_list at present :") 87 | print(initial_list) 88 | -------------------------------------------------------------------------------- /chapter7/using_module_alias.py: -------------------------------------------------------------------------------- 1 | import my_library as ml # imports the whole module. 2 | print("Accessing a list element:") 3 | print(f"my_list[0]={ml.my_list[0]}") 4 | 5 | print("\nAccessing a dictionary element:") 6 | print(f"my_dictionary[1]={ml.my_dictionary[1]}") 7 | 8 | print("\nUsing the make_total_double function now.") 9 | result = ml.make_total_double(20, 30.5) 10 | print(result) 11 | -------------------------------------------------------------------------------- /chapter7/using_molules_example_1.py: -------------------------------------------------------------------------------- 1 | from my_library import my_list, my_dictionary, make_total_double 2 | print("Accessing some list elements:") 3 | print(f"my_list[0]={my_list[0]}") 4 | print(f"my_list[3]={my_list[3]}") 5 | 6 | print("\nAccessing some dictionary elements:") 7 | print(f"my_dictionary[1]={my_dictionary[1]}") 8 | print(f"my_dictionary[2]={my_dictionary[2]}") 9 | 10 | print("\nUsing the make_total_double function now.") 11 | result = make_total_double(20, 30.5) 12 | print(result) 13 | 14 | 15 | -------------------------------------------------------------------------------- /chapter8/cs_6.1_implementation.py: -------------------------------------------------------------------------------- 1 | print("=" * 25) 2 | print("This is a simple calculator.") 3 | print("It supports the following operations:") 4 | print("i)Addition" 5 | "\nii)Subtraction" 6 | "\niii)Multiplication and " 7 | "\niv)Division.") 8 | print("=" * 25) 9 | valid_operators = ["+", "-", "*", "/"] 10 | 11 | 12 | def add_numbers(num1, num2): 13 | """ 14 | Adds the numbers. 15 | """ 16 | return num1 + num2 17 | 18 | 19 | def subtract_numbers(num1, num2): 20 | """ 21 | Subtracts the numbers. 22 | """ 23 | return num1 - num2 24 | 25 | 26 | def multiply_numbers(num1, num2): 27 | """ 28 | Multiplies the numbers. 29 | """ 30 | return num1 * num2 31 | 32 | 33 | def divide_numbers(num1, num2): 34 | """ 35 | Divide num1 by num2. 36 | """ 37 | return num1 / num2 38 | 39 | 40 | def compute(num1, operator, num2): 41 | """ 42 | This function computes the final result. 43 | """ 44 | result = 0 #default value 45 | 46 | if operator == '+': 47 | result = add_numbers(num1, num2) 48 | elif operator == '-': 49 | result = subtract_numbers(num1, num2) 50 | elif operator == '*': 51 | result = multiply_numbers(num1, num2) 52 | #elif operator == "/": 53 | else: 54 | result = divide_numbers(num1, num2) 55 | print(f"The final result is:{result}") 56 | 57 | 58 | def main(): 59 | """ 60 | This is the top-level function. 61 | It calls the compute() function. 62 | """ 63 | try: 64 | usr_input1 = input("Enter the first number:") 65 | first_number = float(usr_input1) 66 | usr_input2 = input("Enter the next number:") 67 | second_number = float(usr_input2) 68 | usr_opr = input("Enter an operator(+,-,*,/): ") 69 | if usr_opr not in valid_operators: 70 | raise Exception("Invalid operator.") 71 | compute(first_number, usr_opr, second_number) 72 | except ZeroDivisionError as e: 73 | print(f"Invalid Operation.Details: {e}") 74 | except ValueError as e: 75 | print(f"Invalid input.Details: {e}") 76 | except Exception as e: 77 | print(f"Error details: {e}") 78 | 79 | 80 | main() 81 | -------------------------------------------------------------------------------- /chapter8/custom_exception.py: -------------------------------------------------------------------------------- 1 | #Following example uses a custom exception 2 | class MyException(Exception): 3 | """ This is a custom exception.""" 4 | pass 5 | 6 | 7 | try: 8 | user_input = int(input("Enter an integer which is not greater than 100:")) 9 | if user_input > 100: 10 | raise MyException("You have made the integer greater than 100.") 11 | print(f"Well done.You have entered:{user_input}") 12 | except MyException as e: 13 | print(f"Custom exception is raised.Error Details:{e}") 14 | except ValueError as e: 15 | print(f"Here is the error Details:{e}") 16 | 17 | 18 | -------------------------------------------------------------------------------- /chapter8/exception_handling_case_study_1.py: -------------------------------------------------------------------------------- 1 | a = input("Enter a valid integer:") 2 | b = input("Enter another valid integer:") 3 | c = int(a)/int(b) 4 | print(f"The result of a/b is:{c}") 5 | print("The program completes successfully.") -------------------------------------------------------------------------------- /chapter8/exercise8.1.py: -------------------------------------------------------------------------------- 1 | # Exercise 8.1 2 | try: 3 | result = 15/0 4 | except ArithmeticError: 5 | print("Caught the ArithmeticError.Your divisor is zero.") 6 | except ZeroDivisionError: 7 | print("Caught ZeroDivisionError.Correct the divisor which is zero at present.") 8 | 9 | 10 | -------------------------------------------------------------------------------- /chapter8/exercise8.3.py: -------------------------------------------------------------------------------- 1 | try: 2 | raise BaseException('BaseException raised.') 3 | except Exception as e: 4 | print(f"Error Details:{e}") 5 | 6 | -------------------------------------------------------------------------------- /chapter8/exercise8.4.py: -------------------------------------------------------------------------------- 1 | print("Exercise-8.4") 2 | print("*" * 20) 3 | 4 | 5 | def test_me(): 6 | flag = True 7 | 8 | while flag: 9 | user_input = input("Keep entering a valid integer.(Type q to quit):") 10 | if user_input == 'q': 11 | break 12 | try: 13 | display_me = int(user_input) 14 | print(f"Correct.You entered:{display_me}") 15 | except Exception as e: 16 | print(f"Error:{e}") 17 | 18 | #This statement is placed outside the while loop 19 | print("End of the exercise.") 20 | 21 | 22 | test_me() 23 | -------------------------------------------------------------------------------- /chapter8/try_except_example_1.py: -------------------------------------------------------------------------------- 1 | print("The following program can handle the ZeroDivisionError and ValueError both.") 2 | a = input("Enter a valid integer:") 3 | b = input("Enter another valid integer:") 4 | try: 5 | result = int(a) / int(b) 6 | print(f"The result of the division is: {result}") 7 | except ZeroDivisionError as e: 8 | print("Invalid input! Your divisor becomes zero!") 9 | print(f"Error details: {e}") 10 | except ValueError as e: 11 | print("Invalid input! Provide correct input next time!") 12 | print(f"Error details: {e}") 13 | print("The program completes successfully.") 14 | -------------------------------------------------------------------------------- /chapter8/try_with_multiple_except_example2.py: -------------------------------------------------------------------------------- 1 | print("***The following program can handle the non-system-exiting exceptions.***") 2 | a = input("Enter a valid integer:") 3 | b = input("Enter another valid integer:") 4 | try: 5 | result = int(a) / int(b) 6 | #except Exception as e: 7 | #print("An unknown error occurred.") 8 | #print(f"Error details:{e}") 9 | except ZeroDivisionError as e: 10 | print("Invalid input! Your divisor becomes zero!") 11 | print(f"Error details: {e}") 12 | except ValueError as e: 13 | print("Invalid input! Provide a correct input next time!") 14 | print(f"Error details: {e}") 15 | except Exception as e: 16 | print("An unknown error occurred.") 17 | else: 18 | print(f"Result of the division is : {result}") 19 | print("The program completes successfully.") 20 | 21 | -------------------------------------------------------------------------------- /chapter8/use_of_pass.py: -------------------------------------------------------------------------------- 1 | print("This program prints the sum of two valid integers.") 2 | first_input = input("Enter a valid integer:") 3 | second_input = input("Enter another valid integer:") 4 | total = 0 #default value 5 | try: 6 | a = int(first_input) 7 | b = int(second_input) 8 | except ValueError as e: 9 | # print("Provide a correct input next time!") 10 | pass 11 | else: 12 | total = a + b 13 | print(f"Sum of numbers:{total}") 14 | 15 | print("The program completes successfully.") 16 | -------------------------------------------------------------------------------- /chapter8/use_of_try_except_and_else.py: -------------------------------------------------------------------------------- 1 | print("The following program can handle the ZeroDivisionError and ValueError both.") 2 | a = input("Enter a valid integer:") 3 | b = input("Enter another valid integer:") 4 | try: 5 | result = int(a) / int(b) 6 | #print(f"Result of the division is : {result}") 7 | except ZeroDivisionError as e: 8 | print("Invalid input! Your divisor becomes zero!") 9 | print(f"Error details: {e}") 10 | except ValueError as e: 11 | print("Invalid input! Provide correct input next time!") 12 | print(f"Error details:{e}") 13 | else: 14 | print(f"The result of the division is: {result}") 15 | print("The program completes successfully.") 16 | -------------------------------------------------------------------------------- /chapter8/using_assert.py: -------------------------------------------------------------------------------- 1 | my_list = [1, 2, 3, 4] 2 | #If condition is False, AssertionError is raised. 3 | # assert len(my_list) >= 5, "List length is less than 5." 4 | 5 | try: 6 | assert len(my_list) >= 5, "List length is less than 5." 7 | except AssertionError as e: 8 | print(f"Error details:{e}") 9 | 10 | -------------------------------------------------------------------------------- /chapter9/OriginalFile.txt: -------------------------------------------------------------------------------- 1 | Dear Reader, this is my test file. 2 | It is originally stored at C:\TestData in my system. 3 | I hope you'll enjoy learning. 4 | -------------------------------------------------------------------------------- /chapter9/cs_7.1_implementation.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | class ScoreExceedsError(Exception): 5 | """ This is a custom exception.""" 6 | pass 7 | 8 | 9 | def calculate_grade(a1_score, 10 | a2_score, 11 | e_score): 12 | """ 13 | This function calculates the final score. 14 | Here is the consideration: 15 | 25% of the total marks in assignment and 16 | 75% of the total marks make the grade card. 17 | """ 18 | final_score = (a1_score + a2_score) * .25\ 19 | + e_score * .75 20 | return final_score 21 | 22 | 23 | def make_grade(score): 24 | """ This function makes the grade.""" 25 | grade = "" 26 | if score > 90: 27 | grade = "A+(Outstanding)" 28 | elif score > 80: 29 | grade = "A(Very Good)" 30 | elif score >= 70: 31 | grade = "B(Good)" 32 | else: 33 | grade = "F(Fail)" 34 | return grade 35 | 36 | 37 | def save_scores(name, 38 | assign1, 39 | assign2, 40 | exam, 41 | score, 42 | grade): 43 | """ 44 | This function stores the result in a text file. 45 | It picks the current working directory.Then create a 46 | directory(if it does not exist),called GradeScores. 47 | All records are stored as test files inside 48 | this directory. 49 | """ 50 | try: 51 | # Retrieve the current working directory 52 | current_path = os.getcwd() 53 | print("The current working directory:") 54 | print(current_path) 55 | # Adding a relative path to the current path 56 | relative_path = "GradeScores" 57 | new_path = os.path.join(current_path, 58 | relative_path) 59 | # Making the directory if it does not exist 60 | if not os.path.exists(new_path): 61 | os.makedirs(new_path) 62 | new_path = new_path + '\\' + name + '.txt' 63 | print("Get the report card at:") 64 | print(new_path) 65 | with open(new_path,'w') as file_object: 66 | file_object.write("***Report Card***") 67 | file_object.write("\n***Course name: Python for Beginners***\n") 68 | file_object.write("=" * 50) 69 | file_object.write(f"\nStudent Name: {name}") 70 | file_object.write(f"\nAssignment-1 Score:{assign1}") 71 | file_object.write(f"\nAssignment-2 Score:{assign2}") 72 | file_object.write(f"\nExam Score:{exam}") 73 | file_object.write(f"\nFinal score:{score}") 74 | file_object.write(f"\nGrade/Remark: {grade}") 75 | except FileNotFoundError as e: 76 | print(f"The file is missing.Details:{e}") 77 | except Exception as e: 78 | print(f"Error details: {e}") 79 | 80 | 81 | def main(): 82 | """ 83 | It is the top level function for 84 | this application. 85 | """ 86 | 87 | try: 88 | student_name = input("Enter the student name:") 89 | assign1 = float(input("Assignment-1 score:")) 90 | if assign1 > 50: 91 | raise ScoreExceedsError("Assignment1 score cannot be greater than 50.") 92 | assign2 = float(input("Assignment-2 score:")) 93 | if assign2 > 50: 94 | raise ScoreExceedsError("Assignment2 score cannot be greater than 50.") 95 | exam = float(input("Exam score:")) 96 | if exam > 100: 97 | raise ScoreExceedsError("Final exam score cannot be greater than 100.") 98 | except ValueError as e: 99 | print(f"Invalid input.Details:{e}") 100 | except ScoreExceedsError as e: 101 | print(f"Error: {e}") 102 | print("Provide the correct input next time!") 103 | except Exception as e: 104 | print(f"Error details: {e}") 105 | else: 106 | final_score = calculate_grade(assign1,assign2,exam) 107 | print(f"Final score:{final_score}") 108 | grade_score = make_grade(final_score) 109 | print(f"Grade: {grade_score}") 110 | save_scores(student_name, 111 | assign1, 112 | assign2, 113 | exam, 114 | final_score, 115 | grade_score) 116 | 117 | 118 | main() 119 | -------------------------------------------------------------------------------- /chapter9/ex_9_dot_1.py: -------------------------------------------------------------------------------- 1 | def print_file_content(input_file): 2 | """ This function can print the content of a text file.""" 3 | try: 4 | with open(input_file,"r") as file_object: 5 | file_content = file_object.read() 6 | except FileNotFoundError as e: 7 | print(f"The file {input_file} is not found.") 8 | print(f"Error details:{e}") 9 | else: 10 | print(file_content) 11 | 12 | 13 | print_file_content('C:\\TestData\\OriginalFile.txt') 14 | -------------------------------------------------------------------------------- /chapter9/ex_9_dot_5.py: -------------------------------------------------------------------------------- 1 | def count_words(input_file): 2 | """ 3 | This function counts approximate number 4 | of words in a text file. 5 | """ 6 | try: 7 | with open(input_file,"r") as file_object: 8 | file_content = file_object.read() 9 | 10 | except FileNotFoundError as e: 11 | print(f"The file {input_file} is not found.") 12 | print(f"Error details:{e}") 13 | else: 14 | separate_words = file_content.split() 15 | #word_count = len(separate_words) 16 | # Alternative solution 17 | word_count = 0 18 | for word in separate_words: 19 | word_count += 1 20 | print("The content of the file:") 21 | print("-" * 20) 22 | print(file_content) 23 | print("-" * 20) 24 | print(f" The file has {word_count} words (approx).") 25 | 26 | 27 | count_words('C:\\TestData\\sample_text_file.txt') 28 | -------------------------------------------------------------------------------- /chapter9/ex_9_dot_6.py: -------------------------------------------------------------------------------- 1 | def print_lines(input_file, lines): 2 | """ This function prints first ‘n’ lines from a text file.""" 3 | try: 4 | with open(input_file, "r") as file_object: 5 | count = 0 6 | while count < lines: 7 | line_content = file_object.readline() 8 | print(line_content,end='') 9 | count += 1 10 | except FileNotFoundError as ex: 11 | print(f"The file {input_file} is not found.") 12 | print(f"Error details:{ex}") 13 | 14 | 15 | try: 16 | user_input = input('Enter how many lines you want to print from the file? ') 17 | number_of_lines = int(user_input) 18 | print_lines('C:\\TestData\\OriginalFile.txt',number_of_lines) 19 | except ValueError as e: 20 | print("Invalid input! Provide a correct input next time!") 21 | print(f"Error details:{e}") 22 | except Exception as e: 23 | print("An unknown error occurred.") 24 | print(f"Error details:{e}") 25 | -------------------------------------------------------------------------------- /chapter9/get_current_working_directory.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | current_path = os.getcwd() 4 | print("The current working directory is as follows:") 5 | print(current_path) 6 | 7 | relative_path = "AnotherDirectory\\SubDirectory" 8 | new_path = os.path.join(os.getcwd(), relative_path) 9 | print("The new path is as follows:") 10 | print(new_path) 11 | -------------------------------------------------------------------------------- /chapter9/handling_file_not_found_error.py: -------------------------------------------------------------------------------- 1 | # Using try-except to handle FileNotFoundError 2 | try: 3 | my_file = 'C:\\TestData\\OriginalFile_1.txt' 4 | with open(my_file, 'r') as file_object: 5 | print("Using the read() method.") 6 | file_content = file_object.read() 7 | print(file_content) 8 | except FileNotFoundError as e: 9 | print(f"The file {my_file} is not found.") 10 | print(f"Error details:{e}") 11 | -------------------------------------------------------------------------------- /chapter9/reading_text_file_example_1.py: -------------------------------------------------------------------------------- 1 | #reading_text_file_example_1.py 2 | 3 | file_object = open('C:\\TestData\\OriginalFile.txt', 'r') 4 | print("---Approach:1---") 5 | print("Reading each line one by one:") 6 | first_line = file_object.readline() 7 | second_line = file_object.readline() 8 | third_line = file_object.readline() 9 | print(first_line) 10 | print(second_line) 11 | print(third_line) 12 | #print(first_line, end='') 13 | #print(second_line, end='') 14 | #print(third_line, end='') 15 | file_object.close() 16 | 17 | print("---Approach:2---") 18 | print("Reading entire file using for loop:") 19 | file_object = open('C:\\TestData\\OriginalFile.txt', 'r') 20 | for current_line in file_object: 21 | print(current_line, end='') 22 | file_object.close() 23 | 24 | print("\n---Approach:3---") 25 | file_object = open('C:\\TestData\\OriginalFile.txt', 'r') 26 | print("Using the read() method.") 27 | file_content = file_object.read() 28 | print(file_content) 29 | 30 | print("------------") 31 | #file_object = open('C:\\TestData\\OriginalFile.txt', 'r') 32 | #for current_line in file_object: 33 | #print(current_line, end='**') 34 | -------------------------------------------------------------------------------- /chapter9/reading_writing_using_buffer_size.py: -------------------------------------------------------------------------------- 1 | # Opening two files-one for reading and one for writing 2 | input_file = open('C:\\TestData\\OriginalFile.txt', 'r') 3 | # Will NOT work if the file does not exist 4 | output_file = open('C:\\TestData\\OutputFile.txt', 'r+') 5 | # Will work even if the file does not exist 6 | #output_file = open('C:\\TestData\\OutputFile.txt', 'w') 7 | content = input_file.read(15) 8 | while len(content): 9 | output_file.write(content) 10 | #output_file.write(content + "\n") 11 | content = input_file.read(15) 12 | input_file.close() 13 | output_file.close() 14 | -------------------------------------------------------------------------------- /chapter9/rename_and_remove_file.py: -------------------------------------------------------------------------------- 1 | from os import rename,remove 2 | 3 | #Renaming the image 4 | rename("C:\\TestData\\OutputImage.png", "C:\\TestData\\OutputImage1.png") 5 | #Deleting the file 6 | remove("C:\\TestData\\OutputImage1.png") 7 | #remove("C://TestData//OutputImage1.png") # Also works 8 | 9 | -------------------------------------------------------------------------------- /chapter9/using_with_keyword.py: -------------------------------------------------------------------------------- 1 | # Using the 'with' keyword in this example. 2 | # Python closes the file when it is no longer needed. 3 | with open('C:\\TestData\\OriginalFile.txt', 'r') as file_object: 4 | ''' 5 | print("---Approach:1---") 6 | print("Reading each lines one by one:") 7 | first_line = file_object.readline() 8 | second_line = file_object.readline() 9 | third_line = file_object.readline() 10 | #print(first_line) 11 | #print(second_line) 12 | #print(third_line) 13 | print(first_line, end='') 14 | print(second_line, end='') 15 | print(third_line, end='') 16 | 17 | #myfile.close() 18 | ''' 19 | ''' 20 | print("---Approach:2---") 21 | print("Reading entire file using for loop:") 22 | #myfile = open('C:\\TestData\\OriginalFile.txt','r') 23 | for current_line in file_object: 24 | print(current_line, end='') 25 | 26 | #file_object.close() 27 | ''' 28 | print("---Approach:3---") 29 | print("Using the read() method.") 30 | file_content = file_object.read() 31 | print(file_content) 32 | 33 | 34 | -------------------------------------------------------------------------------- /chapter9/working_with_binary_files.py: -------------------------------------------------------------------------------- 1 | # Opening two files-one for reading and one for writing 2 | input_file = open("C:\\TestData\\MyImage.png", "rb") 3 | output_file = open("C:\\TestData\\OutputImage.png", "wb") 4 | content = input_file.read(15) 5 | while len(content): 6 | output_file.write(content) 7 | content = input_file.read(15) 8 | input_file.close() 9 | output_file.close() 10 | -------------------------------------------------------------------------------- /chapter9/writing_to_file.py: -------------------------------------------------------------------------------- 1 | # Opening the file in 'a' mode 2 | my_file = open("C:\\TestData\\OriginalFile.txt", "a") 3 | my_file.write("This is a new line.") 4 | my_file.write("\nThis is another new line.I append this too.") 5 | my_file.close() 6 | 7 | -------------------------------------------------------------------------------- /employee_module.py: -------------------------------------------------------------------------------- 1 | # This is an Employee class where you can 2 | # find the name, employee id, and company details. 3 | # It is used in chapter11. 4 | 5 | """ 6 | 7 | Classes 8 | --------- 9 | Employee 10 | This is a simple class. In the constructor, 11 | you can store employee name, employee id and 12 | company information. It has a method, called 13 | get_details() to print these information. 14 | 15 | PersonalDetails 16 | This class has a method to show 17 | an employee with background details. 18 | """ 19 | 20 | 21 | class Employee: 22 | """ 23 | It is a simple class to store 24 | basic employee information. 25 | """ 26 | def __init__(self, name, emp_id): 27 | # Initialize name 28 | self.name = name 29 | # Initialize emp_id 30 | self.emp_id = emp_id 31 | self.company = "Abc Ltd." 32 | 33 | def get_details(self): 34 | print("\nThe current employee details are:") 35 | # Formatting the output using f-string 36 | print(f"Name: {self.name}") 37 | print(f"Id: {self.emp_id}") 38 | print(f"Company: {self.company}") 39 | 40 | def get_details_modified(self): 41 | """ 42 | Modifying this method with return 43 | value for testing in Chapter-12 44 | """ 45 | #print("The current employee details are as follows:") 46 | #Formating the output using f-string 47 | #print(f"Name:{self.name},Id:{self.emp_id},Company:{self.company}") 48 | return f"Name:{self.name},Id:{self.emp_id},Company:{self.company}" 49 | 50 | 51 | class PersonalDetails: 52 | """ 53 | This class is used to show the 54 | background details of an employee. 55 | """ 56 | def __init__(self, name, current_company, 57 | work_experience, age, address): 58 | # Initialize department 59 | self.name = name 60 | self.current_company = current_company 61 | self.work_experience = work_experience 62 | # Initialize age 63 | self.age = age 64 | self.address = address 65 | 66 | def background_details(self): 67 | print("-" * 10) 68 | print("Here are the background details:") 69 | #Formating the output using f-string 70 | print(f"Name: {self.name}") 71 | print(f"Current company: {self.current_company}") 72 | print(f"Age: {self.age},Address: {self.address}") 73 | print(f"Experience: {self.work_experience} yrs.") 74 | print("-" * 10) 75 | 76 | -------------------------------------------------------------------------------- /my_library.py: -------------------------------------------------------------------------------- 1 | # A simple list 2 | my_list = [1, 2, 3, 4, 5] 3 | 4 | # A simple dictionary 5 | my_dictionary = {1: "Jack", 2: "Kate", 3: "Bob"} 6 | 7 | 8 | def make_total_double(first, second): 9 | """ 10 | This function takes two numbers 11 | and returns the double. 12 | """ 13 | total = first + second 14 | return total * 2 15 | 16 | 17 | def make_average(first, second, third=0): 18 | """ 19 | This function takes three numbers and 20 | returns the average. 21 | The third number is optional. 22 | """ 23 | total = first + second + third 24 | return total / 3 25 | --------------------------------------------------------------------------------