├── Chapter-03 ├── fah_to_cel.py ├── from_idle.py ├── hello.py ├── no_output.py └── no_output2.py ├── Chapter-05 ├── simple_interest_calculator.py └── simple_interest_calculator_using_format_function.py ├── Chapter-06 └── multiline_statements.py ├── Chapter-07 ├── dollor_at_the_end.py ├── newline_at_the_end.py └── nothing_at_end.py ├── Chapter-09 ├── calculate_circles_area_circumference.py ├── if_and_else_not_aligned.py ├── if_elif_else_statement.py ├── if_statement.py ├── if_statement_block.py ├── nested_if_else_statement.py ├── nested_if_statement.py ├── secret_world.py └── testing_multiple_conditions.py ├── Chapter-10 ├── a_while_loop.py ├── an_infinite_loop.py ├── fahrenheit_to_celsius.py ├── squares_from_1_to_20.py └── sum_from_0_to_10.py ├── Chapter-11 ├── break_and_continue.py ├── break_demo.py ├── break_inside_nested_loop.py ├── continue_demo.py └── prime_or_not.py ├── Chapter-13 ├── call_before_definition.py ├── calling_first_function.py ├── factorial.py ├── first_function.py ├── function_argument.py ├── grade_calculator.py ├── is_even_or_odd.py ├── multiple_arguments.py ├── passing_immutable_objects.py ├── passing_mutable_objects.py ├── pythagorean_triplets.py ├── return_factorial.py ├── returning_multiple_values.py ├── returning_none.py ├── same_global_and_local.py ├── same_variable_names_in_different_functions.py ├── setting_default_values.py ├── test.py ├── transfer_of_control.py ├── two_func_program_control.py ├── using_void_function_as_non_void_function.py ├── variable_scope.py └── void_function.py ├── Chapter-14 ├── __pycache__ │ ├── my_module.cpython-34.pyc │ └── reusing_identifiers.cpython-34.pyc ├── importing_selected_identifiers.py ├── my_module.py ├── reusing_identifiers.py ├── test_module.py └── test_module2.py ├── Chapter-15 ├── __pycache__ │ ├── bank_account.cpython-34.pyc │ ├── circle.cpython-34.pyc │ └── improved_circle.cpython-34.pyc ├── bank_account.py ├── circle.py ├── circle_client.py ├── improved_circle.py ├── multiple_objects.py ├── objects_as_arguments.py └── passing_argument_to_self.py ├── Chapter-16 ├── __str__method.py ├── inheritance.py ├── method_overriding.py ├── method_overriding_2.py ├── multiple_inheritance.py └── overriding__str__method.py ├── Chapter-17 ├── point.py └── special_methods.py ├── Chapter-18 ├── append_data.py ├── read_method_demo.py ├── reading_and_writing_binary_data.py ├── reading_in_chunks.py ├── reading_large_file_demo1.py ├── reading_large_files_using_for_loop.py ├── readline_method_demo.py ├── readlines_method_demo.py ├── source.jpg ├── with_statement.py ├── with_statement2.py ├── with_statement3.py ├── with_statement4.py ├── writing_data_using_print_function.py └── writing_to_file.py ├── Chapter-19 ├── InvalidFactorialArgumentException.py ├── __pycache__ │ └── InvalidFactorialArgumentException.cpython-34.pyc ├── accessing_exception_object.py ├── else_clause_demo.py ├── exception_handling.py ├── exception_handling_while_reading_file.py ├── factorial.py ├── factorialWithCustomException.py ├── finally_clause_demo.py ├── handling_exception_inside_factorial_func.py └── handling_muliple_types_of_exceptions.py ├── Chapter-20 └── operations_on_tuple.py └── README.md /Chapter-03/fah_to_cel.py: -------------------------------------------------------------------------------- 1 | print("20 degree Fahrenheit in degree Celsius is: ") 2 | print(5 / 9 * 20 - 32) -------------------------------------------------------------------------------- /Chapter-03/from_idle.py: -------------------------------------------------------------------------------- 1 | print("Big Python") -------------------------------------------------------------------------------- /Chapter-03/hello.py: -------------------------------------------------------------------------------- 1 | print("Woods are lovely dark and deep") 2 | print("but I have promises to keep") 3 | print("and miles to go before I sleep") -------------------------------------------------------------------------------- /Chapter-03/no_output.py: -------------------------------------------------------------------------------- 1 | 12+8 2 | 75/2 3 | 100*2 4 | 100-24 -------------------------------------------------------------------------------- /Chapter-03/no_output2.py: -------------------------------------------------------------------------------- 1 | print(12+8) 2 | print(75/2) 3 | print(100*2) 4 | print(100-24) -------------------------------------------------------------------------------- /Chapter-05/simple_interest_calculator.py: -------------------------------------------------------------------------------- 1 | # Program to calculate the Simple Interest 2 | # 3 | # The formula for Simple Interest is 4 | # si = p * r * t 5 | # where si is the simple interest 6 | # p is principal 7 | # r is interest rate 8 | # t is number of years 9 | 10 | p = 18819.99 # principal 11 | r = 0.05 # rate of interest 12 | t = 2 # years 13 | 14 | si = p * r * t 15 | print("Simple interest at the end of 2 years $", si) -------------------------------------------------------------------------------- /Chapter-05/simple_interest_calculator_using_format_function.py: -------------------------------------------------------------------------------- 1 | # Program to calculate the Simple Interest 2 | # 3 | # The formula for Simple Interest is 4 | # si = p * r * t 5 | # where si is the simple interest 6 | # p is principal 7 | # r is interest rate 8 | # t is number of years 9 | 10 | p = 18819.99 # principal 11 | r = 0.05 # rate of interest 12 | t = 2 # years 13 | 14 | si = p * r * t 15 | print("Simple interest at the end of 2 years $", format(si, "0.2f")) -------------------------------------------------------------------------------- /Chapter-06/multiline_statements.py: -------------------------------------------------------------------------------- 1 | result = 1111100 + 45 - (88 / 43) + 783 \ 2 | + 10 - 33 * 1000 + \ 3 | 88 + 3772 4 | 5 | print(result) 6 | 7 | print("first line\ 8 | second line\ 9 | third line") -------------------------------------------------------------------------------- /Chapter-07/dollor_at_the_end.py: -------------------------------------------------------------------------------- 1 | print("first string", end="$") 2 | print("second string", end="$") -------------------------------------------------------------------------------- /Chapter-07/newline_at_the_end.py: -------------------------------------------------------------------------------- 1 | print("first line") 2 | print("second line") -------------------------------------------------------------------------------- /Chapter-07/nothing_at_end.py: -------------------------------------------------------------------------------- 1 | print("first", end="") 2 | print("second", end="") 3 | print("third") -------------------------------------------------------------------------------- /Chapter-09/calculate_circles_area_circumference.py: -------------------------------------------------------------------------------- 1 | radius = int(input("Enter radius: ")) 2 | if radius >= 0: 3 | print("Circumference = ", 2 * 3.14 * radius) 4 | print("Area = ", 3.14 * radius ** 2 ) 5 | else: 6 | print("Please enter a positive number") -------------------------------------------------------------------------------- /Chapter-09/if_and_else_not_aligned.py: -------------------------------------------------------------------------------- 1 | radius = int(input("Enter radius: ")) 2 | if radius >= 0: 3 | print("Circumference = ", 2 * 3.14 * radius) 4 | print("Area = ", 3.14 * radius ** 2 ) 5 | 6 | else: 7 | print("Please enter a positive number") -------------------------------------------------------------------------------- /Chapter-09/if_elif_else_statement.py: -------------------------------------------------------------------------------- 1 | score = int(input("Enter your marks: ")) 2 | 3 | if score >= 90: 4 | print("Excellent! Your grade is A") 5 | elif score >= 80: 6 | print("Great! Your grade is B") 7 | elif score >= 70: 8 | print("Good! Your grade is C") 9 | elif score >= 60: 10 | print("Your grade is D. You should work hard on you studies.") 11 | else: 12 | print("You failed in the exam") -------------------------------------------------------------------------------- /Chapter-09/if_statement.py: -------------------------------------------------------------------------------- 1 | number = input("Enter a number: ") 2 | if number > 10: 3 | print("Number is greater than 10") -------------------------------------------------------------------------------- /Chapter-09/if_statement_block.py: -------------------------------------------------------------------------------- 1 | number = int(input("Enter a number")) 2 | if number > 10: 3 | print("statement 1") 4 | print("statement 2") 5 | print("statement 3") 6 | print("Executes every time you run the program") 7 | print("Program ends here") -------------------------------------------------------------------------------- /Chapter-09/nested_if_else_statement.py: -------------------------------------------------------------------------------- 1 | gre_score = int(input("Enter your GRE score: ")) 2 | per_grad = int(input("Enter percent secured in graduation: ")) 3 | 4 | if per_grad > 70: 5 | if gre_score > 150: 6 | print("Congratulations you are eligible for loan.") 7 | else: 8 | print("Your GRE score is no good enough. You should retake the exam.") 9 | else: 10 | print("Sorry, you are not eligible for loan.") -------------------------------------------------------------------------------- /Chapter-09/nested_if_statement.py: -------------------------------------------------------------------------------- 1 | gre_score = int(input("Enter your GRE score: ")) 2 | per_grad = int(input("Enter percent secured in graduation: ")) 3 | 4 | if per_grad > 70: 5 | # outer if block 6 | if gre_score > 150: 7 | # inner if block 8 | print("Congratulations you are eligible for loan") 9 | else: 10 | print("Sorry, you are not eligible for loan") -------------------------------------------------------------------------------- /Chapter-09/secret_world.py: -------------------------------------------------------------------------------- 1 | password = input("Enter a password: ") 2 | if password == "sshh": 3 | print("Welcome to the Secret World") 4 | else: 5 | print("You are not allowed here") -------------------------------------------------------------------------------- /Chapter-09/testing_multiple_conditions.py: -------------------------------------------------------------------------------- 1 | score = int(input("Enter your marks: ")) 2 | 3 | if score >= 90: 4 | print("Excellent ! Your grade is A") 5 | else: 6 | if score >= 80: 7 | print("Great ! Your grade is B") 8 | else: 9 | if score >= 70: 10 | print("Good ! Your grade is C") 11 | else: 12 | if score >= 60: 13 | print("Your grade is D. You should work hard on you subjects.") 14 | else: 15 | print("You failed in the exam") -------------------------------------------------------------------------------- /Chapter-10/a_while_loop.py: -------------------------------------------------------------------------------- 1 | i = 1 2 | while i <= 100: 3 | print("Today is Sunday") 4 | i += 1 -------------------------------------------------------------------------------- /Chapter-10/an_infinite_loop.py: -------------------------------------------------------------------------------- 1 | i = 1 2 | sum = 0 3 | while i < 11: 4 | print(i) 5 | sum += i 6 | i += 1 7 | 8 | print("sum is", sum) 9 | 10 | 1 11 | 1 12 | 1 13 | 1 14 | 1 15 | 1 16 | 1 17 | 1 18 | 1 19 | 1 -------------------------------------------------------------------------------- /Chapter-10/fahrenheit_to_celsius.py: -------------------------------------------------------------------------------- 1 | keep_calculating = 'y' 2 | 3 | while keep_calculating == 'y': 4 | 5 | fah = int(input("Enter temperature in Fahrenheit: ")) 6 | cel = (fah - 32) * 5/9 7 | print(format(fah, "0.2f"), "°F is same as", format(cel, "0.2f"), "°C") 8 | 9 | keep_calculating = input("\nWant to calculate more: ? Press y for Yes, n for N: ") 10 | 11 | 12 | print("Program Ends") -------------------------------------------------------------------------------- /Chapter-10/squares_from_1_to_20.py: -------------------------------------------------------------------------------- 1 | print("Number\t | Square") 2 | print("--------------------") 3 | 4 | for num in range(1, 21): 5 | print(num, "\t\t | ", num*num) -------------------------------------------------------------------------------- /Chapter-10/sum_from_0_to_10.py: -------------------------------------------------------------------------------- 1 | i = 1 2 | sum = 0 3 | while i < 11: 4 | sum += i # same as sum = sum + i 5 | i += 1 6 | 7 | print("sum is", sum) # print the sum -------------------------------------------------------------------------------- /Chapter-11/break_and_continue.py: -------------------------------------------------------------------------------- 1 | while True: 2 | value = input("\nEnter a number: ") 3 | 4 | if value == 'q': # if input is 'q' exit from the while loop 5 | print("Exiting program (break statement executed)...") 6 | break 7 | 8 | if not value.isdigit(): # if input is not a digit move on to the next iteration 9 | print("Enter digits only (continue statement executed)") 10 | continue 11 | 12 | value = int(value) 13 | print("Cube of", value, "is", value**3) # everything is fine, just print the cube -------------------------------------------------------------------------------- /Chapter-11/break_demo.py: -------------------------------------------------------------------------------- 1 | for i in range(1, 10): 2 | if i == 5: # when i is 5 exit the loop 3 | break 4 | print("i =", i) 5 | 6 | print("break out") -------------------------------------------------------------------------------- /Chapter-11/break_inside_nested_loop.py: -------------------------------------------------------------------------------- 1 | for i in range(1, 5): 2 | print("Outer loop i = ", i, end="\n\n") 3 | for j in range (65, 75): 4 | print("\tInner loop chr(j) =", chr(j)) 5 | if chr(j) == 'C': 6 | print("\tbreaking out of inner for loop ...\n") 7 | break 8 | 9 | print('-------------------------------------------------') -------------------------------------------------------------------------------- /Chapter-11/continue_demo.py: -------------------------------------------------------------------------------- 1 | for i in range(1, 10): 2 | if i % 2 != 0: 3 | continue 4 | print("i =", i) -------------------------------------------------------------------------------- /Chapter-11/prime_or_not.py: -------------------------------------------------------------------------------- 1 | num = int(input("Enter a number: ")) 2 | 3 | is_prime = True 4 | 5 | for i in range(2, num): 6 | if num % i == 0: 7 | is_prime = False # number is not prime 8 | break # exit from for loop 9 | 10 | if is_prime: 11 | print(num, "is prime") 12 | else: 13 | print(num, "is not a prime") -------------------------------------------------------------------------------- /Chapter-13/call_before_definition.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | greet() ## ERROR: trying to call greet() before its defined 4 | 5 | def greet(): 6 | print("Hello !") 7 | print("Today is", datetime.datetime.now()) -------------------------------------------------------------------------------- /Chapter-13/calling_first_function.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | def greet(): 4 | print("Hello !") 5 | print("Today is", datetime.datetime.now()) 6 | 7 | greet() -------------------------------------------------------------------------------- /Chapter-13/factorial.py: -------------------------------------------------------------------------------- 1 | def factorial(n): 2 | f = 1 3 | for i in range(n, 0, -1): 4 | f *= n 5 | n -= 1 6 | 7 | print(f) 8 | 9 | num = input("Enter a number: ") 10 | factorial(int(num)) -------------------------------------------------------------------------------- /Chapter-13/first_function.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | def greet(): 4 | print("Hello !") 5 | print("Today is", datetime.datetime.now()) -------------------------------------------------------------------------------- /Chapter-13/function_argument.py: -------------------------------------------------------------------------------- 1 | def add_100(num): # num is a parameter 2 | print("Result =", num+100) 3 | 4 | 5 | x = 100 6 | add_100(x) -------------------------------------------------------------------------------- /Chapter-13/grade_calculator.py: -------------------------------------------------------------------------------- 1 | def calculate_grade(marks): 2 | if marks >= 90: 3 | return 'A' 4 | elif marks >= 80: 5 | return 'B' 6 | elif marks >= 70: 7 | return 'C' 8 | elif marks >= 60: 9 | return 'D' 10 | else: 11 | return 'F' 12 | 13 | 14 | m = int(input("Enter your marks: ")) 15 | print("Your grade is", calculate_grade(m)) -------------------------------------------------------------------------------- /Chapter-13/is_even_or_odd.py: -------------------------------------------------------------------------------- 1 | def is_even(number): 2 | if number % 2 == 0: 3 | return True 4 | else: 5 | return False 6 | 7 | 8 | num = int(input("Enter a number: ")) 9 | 10 | if is_even(num): 11 | print(num, "is even") 12 | else: 13 | print(num, "is odd") -------------------------------------------------------------------------------- /Chapter-13/multiple_arguments.py: -------------------------------------------------------------------------------- 1 | def calc(num1, num2): 2 | print("Sum =", num1 + num2) 3 | print("Difference =", num1 - num2) 4 | print("Multiplication =", num1 * num2) 5 | print("Division =", num1 / num2) 6 | print() # prints a blank line 7 | 8 | calc(10, 20) -------------------------------------------------------------------------------- /Chapter-13/passing_immutable_objects.py: -------------------------------------------------------------------------------- 1 | def func(para1): 2 | para1 += 100 # increment para1 by 100 3 | print("Inside function call, para1 =", para1) 4 | 5 | arg1 = 100 6 | print("Before function call, arg1 =", arg1) 7 | func(arg1) 8 | print("After function call, arg1 =", arg1) -------------------------------------------------------------------------------- /Chapter-13/passing_mutable_objects.py: -------------------------------------------------------------------------------- 1 | def func(para1): 2 | para1.append(4) 3 | print("Inside function call, para1 =", para1) 4 | 5 | arg1 = [1,2,3] 6 | print("Before function call, arg1 =", arg1) 7 | func(arg1) 8 | print("After function call, arg1 =", arg1) -------------------------------------------------------------------------------- /Chapter-13/pythagorean_triplets.py: -------------------------------------------------------------------------------- 1 | def is_pythagorean_triplet(base, height, perpendicular): 2 | if base ** 2 + height ** 2 == perpendicular ** 2: 3 | print("Numbers passed are Pythagorean Triplets") 4 | else: 5 | print("Numbers passed are not Pythagorean Triplets") 6 | -------------------------------------------------------------------------------- /Chapter-13/return_factorial.py: -------------------------------------------------------------------------------- 1 | def factorial(n): 2 | f = 1 3 | for i in range(n, 0, -1): 4 | f *= n 5 | n -= 1 6 | 7 | return f 8 | 9 | 10 | print("Factorial of 4 is", factorial(4)) 11 | print("Factorial of 4 is", factorial(6)) -------------------------------------------------------------------------------- /Chapter-13/returning_multiple_values.py: -------------------------------------------------------------------------------- 1 | def sort_two_num(num1, num2): 2 | if num1 < num2: 3 | return num1, num2 4 | else: 5 | return num2, num1 6 | 7 | 8 | number1, number2 = sort_two_num(100, 15) 9 | print("number1 is", number1) 10 | print("number2 is", number2) -------------------------------------------------------------------------------- /Chapter-13/returning_none.py: -------------------------------------------------------------------------------- 1 | def foo(): 2 | return 3 | 4 | result = foo() 5 | print(result) -------------------------------------------------------------------------------- /Chapter-13/same_global_and_local.py: -------------------------------------------------------------------------------- 1 | num = "global" # global num variable 2 | 3 | def func(): 4 | num = "local" # local num variable, entirely different from global num variable 5 | print(num) 6 | 7 | func() 8 | print(num) -------------------------------------------------------------------------------- /Chapter-13/same_variable_names_in_different_functions.py: -------------------------------------------------------------------------------- 1 | def func_1(): 2 | x = 100 # this x is only visible inside func_1() 3 | print("func_1(): x =", x) 4 | x = 200 5 | print("func_1(): x =", x) 6 | 7 | 8 | def func_2(): 9 | x = "str" # this x is only visible inside func_2() 10 | print("func_2(): x =", x) 11 | x = "complex" 12 | print("func_2(): x =", x) 13 | 14 | # x is not visible in here 15 | 16 | func_1() 17 | func_2() -------------------------------------------------------------------------------- /Chapter-13/setting_default_values.py: -------------------------------------------------------------------------------- 1 | def calc_area(length=2, width=3): 2 | print("length=", length, ", width = ", width) 3 | print("Area of rectangle is", width * length) 4 | print() 5 | 6 | 7 | calc_area() 8 | calc_area(4, 6) 9 | calc_area(width=100, length=23) 10 | calc_area(length=12) -------------------------------------------------------------------------------- /Chapter-13/test.py: -------------------------------------------------------------------------------- 1 | sum = 0 2 | start = 10 3 | end = 30 4 | for i in range(start, end+1): 5 | sum += i 6 | 7 | print("Sum is", sum) -------------------------------------------------------------------------------- /Chapter-13/transfer_of_control.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | def greet(): 4 | print("Hello !") 5 | print("Today is", datetime.datetime.now()) 6 | 7 | print("Before calling greet()") 8 | greet() 9 | print("After calling greet()") -------------------------------------------------------------------------------- /Chapter-13/two_func_program_control.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | def greet(name): 4 | print("Hello", name, "!") 5 | print("Today is", datetime.datetime.now()) 6 | 7 | 8 | def main(): 9 | print("main() function called") 10 | greet("Jon") 11 | print("main() function finished") 12 | 13 | main() -------------------------------------------------------------------------------- /Chapter-13/using_void_function_as_non_void_function.py: -------------------------------------------------------------------------------- 1 | def add(num1, num2): 2 | print("Sum is", num1 + num2) 3 | 4 | 5 | result = add(10, 200) + 100 -------------------------------------------------------------------------------- /Chapter-13/variable_scope.py: -------------------------------------------------------------------------------- 1 | global_var = 200 # a global variable 2 | 3 | def func(): 4 | 5 | # local_var is a local variable 6 | # and is only available inside func() 7 | local_var = 100 8 | 9 | print("Inside func() - local_var =", local_var) 10 | 11 | # accessing a global variable inside a function 12 | print("Inside func() - global_var =", global_var) 13 | 14 | 15 | func() 16 | 17 | print("Outside func() - global_var =", global_var) 18 | 19 | # print("Outside func() - local_var =", local_var) # ERROR: local_var is not available here -------------------------------------------------------------------------------- /Chapter-13/void_function.py: -------------------------------------------------------------------------------- 1 | def add(num1, num2): 2 | print("Sum is", num1 + num2) 3 | 4 | return_val = add(100, 200) 5 | print(return_val) -------------------------------------------------------------------------------- /Chapter-14/__pycache__/my_module.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/overiq/intro-to-python/092c66653c0413e65c3a00c8f75ec4f051c7d883/Chapter-14/__pycache__/my_module.cpython-34.pyc -------------------------------------------------------------------------------- /Chapter-14/__pycache__/reusing_identifiers.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/overiq/intro-to-python/092c66653c0413e65c3a00c8f75ec4f051c7d883/Chapter-14/__pycache__/reusing_identifiers.cpython-34.pyc -------------------------------------------------------------------------------- /Chapter-14/importing_selected_identifiers.py: -------------------------------------------------------------------------------- 1 | from my_module import doo_hickey, name 2 | 3 | doo_hickey('x') 4 | print(name) -------------------------------------------------------------------------------- /Chapter-14/my_module.py: -------------------------------------------------------------------------------- 1 | A_CONSTANT = 100 2 | 3 | name = 'a variable' 4 | 5 | def great_printer(): 6 | print("first great_printer() definition") 7 | 8 | def doo_hickey(arg): 9 | print("doo_hickey() called with argument:", arg) -------------------------------------------------------------------------------- /Chapter-14/reusing_identifiers.py: -------------------------------------------------------------------------------- 1 | A_CONSTANT = 100 2 | 3 | name = 'a variable' 4 | 5 | def great_printer(): 6 | print("first great_printer() definition") 7 | 8 | def doo_hickey(arg): 9 | print("doo_hickey() called with argument:", arg) 10 | 11 | def great_printer(): 12 | print("second great_printer() definition") -------------------------------------------------------------------------------- /Chapter-14/test_module.py: -------------------------------------------------------------------------------- 1 | import my_module 2 | 3 | my_module.doo_hickey('www') 4 | my_module.great_printer() 5 | print(my_module.A_CONSTANT) 6 | print(my_module.name) -------------------------------------------------------------------------------- /Chapter-14/test_module2.py: -------------------------------------------------------------------------------- 1 | import reusing_identifiers 2 | 3 | reusing_identifiers.great_printer() -------------------------------------------------------------------------------- /Chapter-15/__pycache__/bank_account.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/overiq/intro-to-python/092c66653c0413e65c3a00c8f75ec4f051c7d883/Chapter-15/__pycache__/bank_account.cpython-34.pyc -------------------------------------------------------------------------------- /Chapter-15/__pycache__/circle.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/overiq/intro-to-python/092c66653c0413e65c3a00c8f75ec4f051c7d883/Chapter-15/__pycache__/circle.cpython-34.pyc -------------------------------------------------------------------------------- /Chapter-15/__pycache__/improved_circle.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/overiq/intro-to-python/092c66653c0413e65c3a00c8f75ec4f051c7d883/Chapter-15/__pycache__/improved_circle.cpython-34.pyc -------------------------------------------------------------------------------- /Chapter-15/bank_account.py: -------------------------------------------------------------------------------- 1 | class BankAccount: 2 | 3 | def __init__(self, balance): 4 | self.balance = balance 5 | 6 | def make_deposit(self, amount): 7 | self.balance += amount 8 | 9 | def make_withdrawal(self, amount): 10 | if self.balance < amount: 11 | print("Error: Not enough funds") 12 | else: 13 | print("Successfully withdrawn $", amount, sep="") 14 | self.balance -= amount 15 | 16 | def get_balance(self): 17 | return self.balance 18 | 19 | 20 | my_account = BankAccount(5000) # Create my bank account with $5000 21 | print("Current Balance: $", my_account.get_balance(), sep="") 22 | 23 | print("Withdrawing $10000 ...") 24 | my_account.make_withdrawal(10000) 25 | 26 | print("Lets try withdrawing $1000 ...") 27 | my_account.make_withdrawal(1000) 28 | 29 | print("Now Current Balance: $", my_account.get_balance(), sep="") 30 | 31 | print("Depositing $2000 ...") 32 | my_account.make_deposit(2000) 33 | print("Now Current Balance: $", my_account.get_balance(), sep="") -------------------------------------------------------------------------------- /Chapter-15/circle.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | class Circle: 4 | 5 | def __init__(self, radius): 6 | self.radius = radius 7 | 8 | def get_area(self): 9 | return math.pi * self.radius ** 2 10 | 11 | def get_perimeter(self): 12 | return 2 * math.pi * self.radius -------------------------------------------------------------------------------- /Chapter-15/circle_client.py: -------------------------------------------------------------------------------- 1 | from circle import * 2 | 3 | my_circle = Circle(5) 4 | 5 | print("Circle of radius is",my_circle.radius) 6 | print("Area of circle:", format(my_circle.get_area(), ".2f")) 7 | print("Area of perimeter of circle:", format(my_circle.get_perimeter(), ".2f"), end="\n\n") 8 | 9 | -------------------------------------------------------------------------------- /Chapter-15/improved_circle.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | class Circle: 4 | 5 | def __init__(self, radius): 6 | self.__radius = radius # 7 | 8 | def get_area(self): 9 | return math.pi * self.__radius ** 2 10 | 11 | def get_perimeter(self): 12 | return 2 * math.pi * self.__radius 13 | 14 | # getter method for radius attribute 15 | 16 | def get_radius(self): 17 | return self.__radius 18 | 19 | # setter method for radius attribute 20 | 21 | def set_radius(self, radius): 22 | if not isinstance(radius, int): 23 | print("Error: ", radius, "is not an int") 24 | return 25 | self.__radius = radius -------------------------------------------------------------------------------- /Chapter-15/multiple_objects.py: -------------------------------------------------------------------------------- 1 | from circle import * 2 | 3 | my_circle1 = Circle(5) 4 | my_circle2 = Circle(10) 5 | my_circle3 = Circle(15) 6 | 7 | print("Address of Circle objects") 8 | print("my_circle1:", id(my_circle1)) # print the address of Circle object referenced by variable my_circle1 9 | print("my_circle2:", id(my_circle2)) # print the address of Circle object referenced by variable my_circle2 10 | print("my_circle3:", id(my_circle3)) # print the address of Circle object referenced by variable my_circle3 11 | print() 12 | 13 | print("Address of radius attribute") 14 | print("my_circle1:", id(my_circle1.radius)) # print the address of my_circle1's radius attribute 15 | print("my_circle2:", id(my_circle2.radius)) # print the address of my_circle2's radius attribute 16 | print("my_circle3:", id(my_circle3.radius), end="\n\n") # print the address of my_circle3's radius attribute 17 | 18 | print("Initial value of radius attribute: ") 19 | print("my_circle1's radius:", my_circle1.radius) 20 | print("my_circle2's radius:", my_circle2.radius) 21 | print("my_circle3's radius:", my_circle3.radius, end="\n\n") 22 | 23 | # changing radius attribute of circle objects 24 | my_circle1.radius = 50 25 | my_circle2.radius = 100 26 | my_circle3.radius = 150 27 | 28 | print("After changing radius attribute of circle objects", end="\n\n") 29 | 30 | print("Final value of radius attribute: ") 31 | print("my_circle1's radius:", my_circle1.radius) 32 | print("my_circle2's radius:", my_circle2.radius) 33 | print("my_circle3's radius:", my_circle3.radius) -------------------------------------------------------------------------------- /Chapter-15/objects_as_arguments.py: -------------------------------------------------------------------------------- 1 | from improved_circle import Circle 2 | 3 | c1 = Circle(5.4) 4 | c2 = Circle(10.5) 5 | 6 | def print_circle_info(circle_obj): 7 | print("#########################") 8 | print("Radius of circle", format(circle_obj.get_radius(), "0.2f")) 9 | print("Perimeter of circle", format(circle_obj.get_perimeter(), "0.2f")) 10 | print("Area of circle", format(circle_obj.get_area(), "0.2f")) 11 | print("#########################", end="\n\n") 12 | 13 | 14 | print_circle_info(c1) # passing circle object c1 to print_circle_info() 15 | print_circle_info(c2) # passing circle object c2 to print_circle_info() -------------------------------------------------------------------------------- /Chapter-15/passing_argument_to_self.py: -------------------------------------------------------------------------------- 1 | from circle import * 2 | 3 | my_circle = Circle(5) 4 | my_circle.get_area(my_circle) 5 | my_circle.get_perimeter(my_circle) -------------------------------------------------------------------------------- /Chapter-16/__str__method.py: -------------------------------------------------------------------------------- 1 | class Jester: 2 | def laugh(self): 3 | return print("laugh() called") 4 | 5 | obj = Jester() 6 | print(obj) -------------------------------------------------------------------------------- /Chapter-16/inheritance.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | class Shape: 4 | 5 | def __init__(self, color='black', filled=False): 6 | self.__color = color 7 | self.__filled = filled 8 | 9 | def get_color(self): 10 | return self.__color 11 | 12 | def set_color(self, color): 13 | self.__color = color 14 | 15 | def get_filled(self): 16 | return self.__filled 17 | 18 | def set_filled(self, filled): 19 | self.__filled = filled 20 | 21 | 22 | class Rectangle(Shape): 23 | 24 | def __init__(self, length, breadth): 25 | super().__init__() 26 | self.__length = length 27 | self.__breadth = breadth 28 | 29 | def get_length(self): 30 | return self.__length 31 | 32 | def set_length(self, length): 33 | self.__length = length 34 | 35 | def get_breadth(self): 36 | return self.__breadth 37 | 38 | def set_breadth(self, breadth): 39 | self.__breadth = breadth 40 | 41 | def get_area(self): 42 | return self.__length * self.__breadth 43 | 44 | def get_perimeter(self): 45 | return 2 * (self.__length + self.__breadth) 46 | 47 | 48 | class Circle(Shape): 49 | def __init__(self, radius): 50 | super().__init__() 51 | self.__radius = radius 52 | 53 | def get_radius(self): 54 | return self.__radius 55 | 56 | def set_radius(self, radius): 57 | self.__radius = radius 58 | 59 | def get_area(self): 60 | return math.pi * self.__radius ** 2 61 | 62 | def get_perimeter(self): 63 | return 2 * math.pi * self.__radius 64 | 65 | 66 | r1 = Rectangle(10.5, 2.5) 67 | 68 | print("Area of rectangle r1:", r1.get_area()) 69 | print("Perimeter of rectangle r1:", r1.get_perimeter()) 70 | print("Color of rectangle r1:", r1.get_color()) 71 | print("Is rectangle r1 filled ? ", r1.get_filled()) 72 | r1.set_filled(True) 73 | print("Is rectangle r1 filled ? ", r1.get_filled()) 74 | r1.set_color("orange") 75 | print("Color of rectangle r1:", r1.get_color()) 76 | 77 | c1 = Circle(12) 78 | 79 | print("\nArea of circle c1:", format(c1.get_area(), "0.2f")) 80 | print("Perimeter of circle c1:", format(c1.get_perimeter(), "0.2f")) 81 | print("Color of circle c1:", c1.get_color()) 82 | print("Is circle c1 filled ? ", c1.get_filled()) 83 | c1.set_filled(True) 84 | print("Is circle c1 filled ? ", c1.get_filled()) 85 | c1.set_color("blue") 86 | print("Color of circle c1:", c1.get_color()) -------------------------------------------------------------------------------- /Chapter-16/method_overriding.py: -------------------------------------------------------------------------------- 1 | class A: 2 | def explore(self): 3 | print("explore() method from class A") 4 | 5 | class B(A): 6 | def explore(self): 7 | print("explore() method from class B") 8 | 9 | 10 | b_obj = B() 11 | a_obj = A() 12 | 13 | b_obj.explore() # child class object is used to call overridden method, so child class version of the object will be called 14 | a_obj.explore() -------------------------------------------------------------------------------- /Chapter-16/method_overriding_2.py: -------------------------------------------------------------------------------- 1 | class A: 2 | def explore(self): 3 | print("explore() method from class A") 4 | 5 | class B(A): 6 | def explore(self): 7 | super().explore() # calling the parent class explore() method 8 | print("explore() method from class B") 9 | 10 | 11 | b_obj = B() 12 | b_obj.explore() -------------------------------------------------------------------------------- /Chapter-16/multiple_inheritance.py: -------------------------------------------------------------------------------- 1 | class A: 2 | def explore(self): 3 | print("explore() method called") 4 | 5 | class B: 6 | def search(self): 7 | print("search() method called") 8 | 9 | class C: 10 | def discover(self): 11 | print("discover() method called") 12 | 13 | class D(A, B, C): 14 | def test(self): 15 | print("test() method called") 16 | 17 | 18 | d_obj = D() 19 | d_obj.explore() 20 | d_obj.search() 21 | d_obj.discover() 22 | d_obj.test() -------------------------------------------------------------------------------- /Chapter-16/overriding__str__method.py: -------------------------------------------------------------------------------- 1 | class Jester: 2 | def laugh(self): 3 | return "laugh() called" 4 | 5 | def __str__(self): 6 | return "A more helpful description" 7 | 8 | obj = Jester() 9 | print(obj) -------------------------------------------------------------------------------- /Chapter-17/point.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | class Point: 4 | 5 | def __init__(self, x=0, y=0): 6 | self.__x = x 7 | self.__y = y 8 | 9 | # get the x coordinate 10 | def get_x(self): 11 | return self.__x 12 | 13 | # set the x coordinate 14 | def set_x(self, x): 15 | self.__x = x 16 | 17 | # get the y coordinate 18 | def get_y(self): 19 | return self.__y 20 | 21 | # set the y coordinate 22 | def set_y(self, y): 23 | self.__y = y 24 | 25 | # get the current position 26 | def get_position(self): 27 | return self.__x, self.__y 28 | 29 | # change x and y coordinate by a and b 30 | def move(self, a, b): 31 | self.__x += a 32 | self.__y += b 33 | 34 | # overloading + operator 35 | def __add__(self, point_obj): 36 | return Point(self.__x + point_obj.__x, self.__y + point_obj.__y) 37 | 38 | # overloading - operator 39 | def __sub__(self, point_obj): 40 | return Point(self.__x - point_obj.__x, self.__y - point_obj.__y) 41 | 42 | # overloading < operator 43 | def __lt__(self, point_obj): 44 | return math.sqrt(self.__x ** 2 + self.__y ** 2) < math.sqrt(point_obj.__x ** 2 + point_obj.__y ** 2) 45 | 46 | # overloading <= operator 47 | def __le__(self, point_obj): 48 | return math.sqrt(self.__x ** 2 + self.__y ** 2) <= math.sqrt(point_obj.__x ** 2 + point_obj.__y ** 2) 49 | 50 | # overloading > operator 51 | def __gt__(self, point_obj): 52 | return math.sqrt(self.__x ** 2 + self.__y ** 2) > math.sqrt(point_obj.__x ** 2 + point_obj.__y ** 2) 53 | 54 | # overloading >= operator 55 | def __ge__(self, point_obj): 56 | return math.sqrt(self.__x ** 2 + self.__y ** 2) >= math.sqrt(point_obj.__x ** 2 + point_obj.__y ** 2) 57 | 58 | # overloading == operator 59 | def __eq__(self, point_obj): 60 | return math.sqrt(self.__x ** 2 + self.__y ** 2) == math.sqrt(point_obj.__x ** 2 + point_obj.__y ** 2) 61 | 62 | ## overriding __str__ function 63 | def __str__(self): 64 | return "Point object is at: (" + str(self.__x) + ", " + str(self.__y) + ")" 65 | 66 | 67 | p1 = Point(4, 6) 68 | p2 = Point(10, 6) 69 | 70 | print("Is p1 < p2 ?", p1 < p2) # p1 < p2 is equivalent to p1.__lt__(p2) 71 | print("Is p1 <= p2 ?", p1 <= p2) # p1 <= p2 is equivalent to p1.__le__(p2) 72 | print("Is p1 > p2 ?", p1 > p2) # p1 > p2 is equivalent to p1.__gt__(p2) 73 | print("Is p1 >= p2 ?", p1 >= p2) # p1 >= p2 is equivalent to p1.__ge__(p2) 74 | print("Is p1 == p2 ?", p1 == p2) # p1 < p2 is equivalent to p1.__eq__(p2) 75 | 76 | p3 = p1 + p2 # p1 + p2 is equivalent to p1.__add__(p2) 77 | p4 = p1 - p2 # p1 - p2 is equivalent to p1.__sub__(p2) 78 | 79 | print() # print an empty line 80 | print(p1) # print(p1) is equivalent to print(p1.__str__()) 81 | print(p2) # print(p2) is equivalent to print(p2.__str__()) 82 | print(p3) # print(p3) is equivalent to print(p3.__str__()) 83 | print(p4) # print(p4) is equivalent to print(p4.__str__()) -------------------------------------------------------------------------------- /Chapter-17/special_methods.py: -------------------------------------------------------------------------------- 1 | x, y = 2, 4 2 | 3 | print("x = ", x, ", y =", y) 4 | 5 | print("\nx + y =", x + y) 6 | print("x.__add__(y) =", x.__add__(y)) # same as x + y 7 | 8 | print("\nx * y = ", x * y) 9 | print("x.__mul__(y) = ", x.__mul__(y)) # same as x * y 10 | 11 | print("\nx / y = ", x / y) 12 | print("x.__truediv__(y) = ", x.__truediv__(y)) # same as x / y 13 | 14 | print("\nx ** y = ", x ** y) 15 | print("x.__pow__(y) = ", x.__pow__(y)) # same as x ** y 16 | 17 | print("\nx % y = ", x % y) 18 | print("x.__mod__(y) = ", x.__mod__(y)) # same as x % y 19 | 20 | print("\nx == y = ", x == y) 21 | print("x.__eq__(y) = ", x.__eq__(y)) # same as x == y 22 | 23 | print("\nx != y = ", x != y) 24 | print("x.__ne__(y) = ", x.__ne__(y)) # same as x != y 25 | 26 | print("\nx >= y = ", x >= y) 27 | print("x.__ge__(y) = ", x.__ge__(y)) # same as x >= y 28 | 29 | print("\nx <= y = ", x <= y) 30 | print("x.__le__(y) = ", x.__le__(y)) # same as x <= y 31 | print("------------------------------------------") 32 | 33 | str1 = "special methods" 34 | 35 | print("\nstr1 =", str1) 36 | 37 | print("\n'ods' in str1 =", "ods" in str1) 38 | print("str1.__contains__('ods') =", str1.__contains__("ods")) # same as "ods" in str1 39 | 40 | print("\nlen(str1) =", len(str1)) 41 | print("str1.__len__() =", str1.__len__()) # same as len(str1) 42 | print("------------------------------------------") 43 | 44 | list1 = [11,33, 55] 45 | 46 | print("\nlist1 =", list1) 47 | 48 | print("\nlist1[1] =", list1[1]) 49 | print("list1.__getitem(1) =", list1.__getitem__(1)) # same as list1[1] 50 | print("str(list1) =",str(list1)) # same as list1.__str__() -------------------------------------------------------------------------------- /Chapter-18/append_data.py: -------------------------------------------------------------------------------- 1 | f = open("readme.md", "a") 2 | 3 | print("Appending data to the end of the file ...") 4 | f.write("Fourth Line\n") 5 | f.write("Fifth Line\n") 6 | 7 | print("Done!") 8 | 9 | f.close() 10 | 11 | ## open the file again 12 | 13 | print("\nOpening the file again to read the data ...\n") 14 | 15 | f = open("readme.md", "r") 16 | 17 | for line in f: 18 | print(line, end="") 19 | 20 | f.close() -------------------------------------------------------------------------------- /Chapter-18/read_method_demo.py: -------------------------------------------------------------------------------- 1 | f = open("readme.md", "r") 2 | 3 | print(f.read()) # read all content at once 4 | 5 | f.close() -------------------------------------------------------------------------------- /Chapter-18/reading_and_writing_binary_data.py: -------------------------------------------------------------------------------- 1 | f_source = open("source.jpg", "rb") 2 | f_dest = open("dest.jpg", "wb") 3 | 4 | char_count = 0 5 | 6 | for line in f_source: 7 | char_count += len(line) 8 | f_dest.write(line) 9 | 10 | print(char_count, "characters copied successfully") 11 | 12 | f_source.close() 13 | f_dest.close() -------------------------------------------------------------------------------- /Chapter-18/reading_in_chunks.py: -------------------------------------------------------------------------------- 1 | f = open("readme.md", "r") 2 | 3 | print("First chunk:", f.read(4), end="\n\n") # read the first 4 character 4 | print("Second chunk:", f.read(10), end="\n\n") # read the next 10 character 5 | print("Third chunk:", f.read(), end="\n\n") # read the remaining characters in the file 6 | 7 | f.close() -------------------------------------------------------------------------------- /Chapter-18/reading_large_file_demo1.py: -------------------------------------------------------------------------------- 1 | f = open("readme.md", "r") 2 | 3 | chunk = 10 # specify chunk size 4 | data = "" 5 | 6 | # keep looping until there is data in the file 7 | while True: 8 | data = f.read(chunk) 9 | print(data, end="") 10 | 11 | # if end of file is reached, break out of the while loop 12 | if data == "": 13 | break 14 | 15 | 16 | f.close() -------------------------------------------------------------------------------- /Chapter-18/reading_large_files_using_for_loop.py: -------------------------------------------------------------------------------- 1 | f = open("readme.md", "r") 2 | 3 | for line in f: 4 | print(line, end="") 5 | 6 | f.close() -------------------------------------------------------------------------------- /Chapter-18/readline_method_demo.py: -------------------------------------------------------------------------------- 1 | f = open("readme.md", "r") 2 | 3 | # read first line 4 | print("Ist line:", f.readline()) 5 | 6 | # read the fist two characters in the second line 7 | print("The first two characters in the 2nd line:", f.read(2), end="\n\n") 8 | 9 | # read the remaining characters int the second line 10 | print("Remaining characters in the 2nd line:", f.readline()) 11 | 12 | # read the next line 13 | print("3rd line:", f.readline()) 14 | 15 | # end of the file reached, so readline returns an empty string "" 16 | print("After end of file :", f.readline()) 17 | 18 | f.close() -------------------------------------------------------------------------------- /Chapter-18/readlines_method_demo.py: -------------------------------------------------------------------------------- 1 | f = open("readme.md", "r") 2 | 3 | # read all the line as return and them as a list of strings 4 | print(f.readlines()) 5 | 6 | f.close() -------------------------------------------------------------------------------- /Chapter-18/source.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/overiq/intro-to-python/092c66653c0413e65c3a00c8f75ec4f051c7d883/Chapter-18/source.jpg -------------------------------------------------------------------------------- /Chapter-18/with_statement.py: -------------------------------------------------------------------------------- 1 | with open("readme.md", "r") as f: 2 | for line in f: 3 | print(line, end="") -------------------------------------------------------------------------------- /Chapter-18/with_statement2.py: -------------------------------------------------------------------------------- 1 | with open("readme.md", "r") as f: 2 | print(f.read()) -------------------------------------------------------------------------------- /Chapter-18/with_statement3.py: -------------------------------------------------------------------------------- 1 | with open("readme.md", "r") as f: 2 | chunk = 10 # specify chunk size 3 | data = "" 4 | 5 | # keep looping until there is data in the file 6 | while True: 7 | data = f.read(chunk) 8 | print(data, end="") 9 | 10 | # if end of file is reached, break out of the while loop 11 | if data == "": 12 | break -------------------------------------------------------------------------------- /Chapter-18/with_statement4.py: -------------------------------------------------------------------------------- 1 | with open("random.txt", "w") as f: 2 | f.write("ONE D\n") 3 | f.write("TWO D\n") 4 | f.write("THREE D\n") 5 | f.write("FOUR D\n") -------------------------------------------------------------------------------- /Chapter-18/writing_data_using_print_function.py: -------------------------------------------------------------------------------- 1 | f = open("readme.md", "w") 2 | 3 | print("First Line", file=f) 4 | print("Second Line", file=f) 5 | print("Third Line", file=f) 6 | 7 | f.close() -------------------------------------------------------------------------------- /Chapter-18/writing_to_file.py: -------------------------------------------------------------------------------- 1 | f = open("readme.md", "w") 2 | 3 | f.write("First Line\n") 4 | f.write("Second Line\n") 5 | f.write("Third Line\n") 6 | 7 | f.close() -------------------------------------------------------------------------------- /Chapter-19/InvalidFactorialArgumentException.py: -------------------------------------------------------------------------------- 1 | class InvalidFactorialArgumentException(Exception): 2 | def __init__(self, message): 3 | super().__init__() 4 | self.message = message 5 | 6 | def __str__(self): 7 | return self.message -------------------------------------------------------------------------------- /Chapter-19/__pycache__/InvalidFactorialArgumentException.cpython-34.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/overiq/intro-to-python/092c66653c0413e65c3a00c8f75ec4f051c7d883/Chapter-19/__pycache__/InvalidFactorialArgumentException.cpython-34.pyc -------------------------------------------------------------------------------- /Chapter-19/accessing_exception_object.py: -------------------------------------------------------------------------------- 1 | def factorial(n): 2 | if not isinstance(n, int): 3 | raise RuntimeError("Argument must be int") 4 | 5 | if n < 0: 6 | raise RuntimeError("Argument must be >= 0") 7 | 8 | f = 1 9 | for i in range(n): 10 | f *= n 11 | n -= 1 12 | 13 | return f 14 | 15 | 16 | try: 17 | print("Factorial of 4 is:", factorial(4)) 18 | print("Factorial of 12 is:", factorial("12")) 19 | 20 | except RuntimeError as e: 21 | print("Error:", e) -------------------------------------------------------------------------------- /Chapter-19/else_clause_demo.py: -------------------------------------------------------------------------------- 1 | import os 2 | filename = input("Enter file name: ") 3 | 4 | try: 5 | f = open(filename, "r") 6 | 7 | for line in f: 8 | print(line, end="") 9 | 10 | f.close() 11 | 12 | except FileNotFoundError: 13 | print("File not found") 14 | 15 | except PermissionError: 16 | print("You don't have the permission to read the file") 17 | 18 | except FileExistsError: 19 | print("You don't have the permission to read the file") 20 | 21 | except: 22 | print("Unexpected error while reading the file") 23 | else: 24 | print("Program ran without any problem") -------------------------------------------------------------------------------- /Chapter-19/exception_handling.py: -------------------------------------------------------------------------------- 1 | try: 2 | num = int(input("Enter a number: ")) 3 | result = 10/num 4 | print("Result: ", result) 5 | 6 | except ZeroDivisionError: 7 | print("Exception Handler for ZeroDivisionError") 8 | print("We cant divide a number by 0") -------------------------------------------------------------------------------- /Chapter-19/exception_handling_while_reading_file.py: -------------------------------------------------------------------------------- 1 | filename = input("Enter file name: ") 2 | 3 | try: 4 | f = open(filename, "r") 5 | 6 | for line in f: 7 | print(line, end="") 8 | 9 | f.close() 10 | 11 | except FileNotFoundError: 12 | print("File not found") 13 | 14 | except PermissionError: 15 | print("You don't have the permission to read the file") 16 | 17 | except: 18 | print("Unexpected error while reading the file") -------------------------------------------------------------------------------- /Chapter-19/factorial.py: -------------------------------------------------------------------------------- 1 | def factorial(n): 2 | if not isinstance(n, int): 3 | raise RuntimeError("Argument must be int") 4 | 5 | if n < 0: 6 | raise RuntimeError("Argument must be >= 0") 7 | 8 | f = 1 9 | for i in range(n): 10 | f *= n 11 | n -= 1 12 | 13 | return f 14 | 15 | try: 16 | print("Factorial of 4 is:", factorial(4)) 17 | print("Factorial of 12 is:", factorial("12")) 18 | except RuntimeError: 19 | print("Invalid Input") -------------------------------------------------------------------------------- /Chapter-19/factorialWithCustomException.py: -------------------------------------------------------------------------------- 1 | from InvalidFactorialArgumentException import * 2 | 3 | def factorial(n): 4 | if not isinstance(n, int): 5 | raise InvalidFactorialArgumentException("Argument must be int") 6 | 7 | if n < 0: 8 | raise InvalidFactorialArgumentException("Argument must be >= 0") 9 | 10 | f = 1 11 | for i in range(n): 12 | f *= n 13 | n -= 1 14 | 15 | return f 16 | 17 | 18 | try: 19 | print("Factorial of 4 is:", factorial(4)) 20 | print("Factorial of 12 is:", factorial("12")) 21 | 22 | except InvalidFactorialArgumentException as e: 23 | print("Error:", e) -------------------------------------------------------------------------------- /Chapter-19/finally_clause_demo.py: -------------------------------------------------------------------------------- 1 | import os 2 | filename = input("Enter file name: ") 3 | 4 | try: 5 | f = open(filename, "r") 6 | 7 | for line in f: 8 | print(line, end="") 9 | 10 | f.close() 11 | 12 | except FileNotFoundError: 13 | print("File not found") 14 | 15 | except PermissionError: 16 | print("You don't have the permission to read the file") 17 | 18 | except FileExistsError: 19 | print("You don't have the permission to read the file") 20 | 21 | except: 22 | print("Unexpected error while reading the file") 23 | 24 | else: 25 | print("\nProgram ran without any problem") 26 | 27 | finally: 28 | print("finally clause: This will always execute") -------------------------------------------------------------------------------- /Chapter-19/handling_exception_inside_factorial_func.py: -------------------------------------------------------------------------------- 1 | def factorial(n): 2 | 3 | try: 4 | if not isinstance(n, int): 5 | raise RuntimeError("Argument must be int") 6 | 7 | if n < 0: 8 | raise RuntimeError("Argument must be >= 0") 9 | 10 | f = 1 11 | for i in range(n): 12 | f *= n 13 | n -= 1 14 | 15 | return f 16 | 17 | except RuntimeError: 18 | return "Invalid Input" 19 | 20 | print("Factorial of 4 is:", factorial(4)) 21 | print("Factorial of 12 is:", factorial("12")) -------------------------------------------------------------------------------- /Chapter-19/handling_muliple_types_of_exceptions.py: -------------------------------------------------------------------------------- 1 | try: 2 | num1 = int(input("Enter a num1: ")) 3 | num2 = int(input("Enter a num2: ")) 4 | 5 | result = num1 / num2 6 | print("Result: ", result) 7 | 8 | except ZeroDivisionError: 9 | print("\nException Handler for ZeroDivisionError") 10 | print("We cant divide a number by 0") 11 | 12 | except ValueError: 13 | print("\nException Handler for ValueError") 14 | print("Invalid input: Only integers are allowed") 15 | 16 | except: 17 | print("\nSome unexpected error occurred") -------------------------------------------------------------------------------- /Chapter-20/operations_on_tuple.py: -------------------------------------------------------------------------------- 1 | tuple_a = ("alpha", "beta", "gamma") 2 | print("tuple_a:", tuple_a) 3 | print("Length of tuple_a:", len(tuple_a)) # len() function on tuple 4 | 5 | tuple_b = tuple(range(1,20, 2)) # i.e tuple_b = (1, 3, 5, 7, 9, 11, 13, 15, 17, 19) 6 | print("\ntuple_b:", tuple_b) 7 | print("Highest value in tuple_b:", max(tuple_b)) # max() function on tuple 8 | print("Lowest value in tuple_b:",min(tuple_b)) # min() function on tuple 9 | print("Sum of elements in tuple_b:",sum(tuple_b)) # sum() function on tuple 10 | 11 | print("\nIndex operator ([]) and Slicing operator ([:]) : ") 12 | print("tuple_a[1]:", tuple_a[1]) 13 | print("tuple_b[len(tuple_b)-1]:", tuple_b[len(tuple_b)-1]) 14 | print("tuple_a[1:]:", tuple_a[1:]) 15 | 16 | print("\nMembership operators with tuples: ") 17 | print("'kappa' in tuple_a: ",'kappa' in tuple_a) 18 | print("'kappa' not in tuple_b: ",'kappa' not in tuple_b) 19 | 20 | print("\nIterating though elements using for loop") 21 | print("tuple_a: ", end="") 22 | for i in tuple_a: 23 | print(i, end=" ") 24 | 25 | print("\ntuple_b: ", end="") 26 | for i in tuple_b: 27 | print(i, end=" ") 28 | 29 | 30 | print("\n\nComparing tuples: ") 31 | print("tuple_a == tuple_b:", tuple_a == tuple_b) 32 | print("tuple_a != tuple_b:", tuple_a != tuple_b) 33 | 34 | print("\nMultiplication and addition operators on tuples: ") 35 | print("tuple * 2:", tuple_a * 2) 36 | print("tuple_b + (10000, 20000): ", tuple_b + (10000, 20000)) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## OverIQ Learn Python 2 | 3 | This repository contains the source code of the tutorial available at https://overiq.com/python/3.4/intro-to-python --------------------------------------------------------------------------------