Python — Basics
Functions, OOP, file handling, calculator, loops. #PurePythonSeries — Episode #17
Explore the basics of Python with this tutorial
covering essential functions, object-oriented programming,
and file handling.
Learn how to create a simple calculator class,
integrate it into a worksheet,
and handle common exceptions.
Plus, discover the difference between
return and break in loops.
Perfect for beginners or
those looking to sharpen their Python skills!
Welcome!👉️ Colab nb
1 Step — Functions:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
return a / badd(1, 2)
32 Step — Classes:
# prompt: generating a class from the methods above
class Calculator:
def add(self, a, b):
return a + b
def subtract(self, a, b):
return a - b
def multiply(self, a, b):
return a * b
def divide(self, a, b):
return a / b
if __name__ == "__main__":
calculator = Calculator()
print(calculator.add(1, 2))
print(calculator.subtract(1, 2))
print(calculator.multiply(1, 2))
print(calculator.divide(1, 2))3
-1
2
0.5calculator = Calculator()
calculator.add(1, 2)3
3Step — Objects:
# prompt: Generating a class Worksheet that use Calculator
class Worksheet:
def __init__(self):
self.calculator = Calculator()
def perform_operations(self, a, b):
print("Addition:", self.calculator.add(a, b))
print("Subtraction:", self.calculator.subtract(a, b))
print("Multiplication:", self.calculator.multiply(a, b))
print("Division:", self.calculator.divide(a, b))
# Example usage:
worksheet = Worksheet()
worksheet.perform_operations(10, 5)Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0worksheet.perform_operations(5, 10)Addition: 15
Subtraction: -5
Multiplication: 50
Division: 0.54Step — Open Files; Use open():
def open_file(filename):
try:
file = open(filename, 'r')
contents = file.read()
print(contents)
except FileNotFoundError:
print(f"File '{filename}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
if 'file' in locals():
file.close()or with open():
# prompt: Generating a method to read a file use with open()
def read_file(filename):
try:
with open(filename, 'r') as file:
contents = file.read()
print(contents)
except FileNotFoundError:
print(f"File '{filename}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
if 'file' in locals():
file.close()read_file("sample_data/worksheet.py")It will create a file inside in this directory.
5Step — Input Data:
def enter_number():
while True:
try:
number = float(input(f"Enter a number: "))
except ValueError:
print("Invalid input.")
except Exception as e:
print(f"An error occurred: {e} ")
continue
else:
return number
breakenter_number()
Enter a number: w
Invalid input.
Enter a number: 1
1.0Another without continue/break :
def enter_number():
while True:
try:
number = float(input(f"Enter a number: "))
except ValueError:
print("Invalid input. Enter a number:")
except Exception as e:
print(f"An error occurred: {e} ")
else:
return numberenter_number()
Enter a number: w
Invalid input. Enter a number:
Enter a number:
Invalid input. Enter a number:
Enter a number: w
Invalid input. Enter a number:
Enter a number: 1
1.06Step — Diff Return x Break:
# Difference between Return and Break statements:
# https://stackoverflow.com/questions/6620949/difference-between-return-and-break-statements
# break is used to exit (escape) the for-loop, while-loop,
# switch-statement that you are currently executing.
# return will exit the entire method you are currently executing
# (and possibly return a value to the caller, optional).
def f():
while True:
if x == 0:
break # escape while() and jump to execute code after the loop
elif x == 1:
print("Returning imediatelly")
print("Outside the f()")
return # will end the function f() immediately
# no further code inside this method will be executed.
# ... other code to execute within the loop ...
# Code to execute after the loop (if x == 0)
print("Loop exited from while with break.")
print("Inside the f()")
print("You can now write a function (f()) to define its purpose")x = 1
f()Returning imediatelly
Outside the f()x = 0
f()Loop exited from while with break.
Inside the f()
You can now write a function (f()) to define its purposeprint("That's it folks!")That's it folks!
Related Posts
00#Episode#PurePythonSeries — Lambda in Python — Python Lambda Desmistification
01#Episode#PurePythonSeries — Send Email in Python — Using Jupyter Notebook — How To Send Gmail In Python
02#Episode#PurePythonSeries — Automate Your Email With Python & Outlook — How To Create An Email Trigger System in Python
03#Episode#PurePythonSeries — Manipulating Files With Python — Manage Your Lovely Photos With Python!
04#Episode#PurePythonSeries — Pandas DataFrame Advanced — A Complete Notebook Review
05#Episode#PurePythonSeries — Is This Leap Year? Python Calendar — How To Calculate If The Year Is Leap Year and How Many Days Are In The Month
06#Episode#PurePythonSeries — List Comprehension In Python — Locked-in Secrets About List Comprehension
07#Episode#PurePythonSeries — Graphs — In Python — Extremely Simple Algorithms in Python
08#Episode#PurePythonSeries — Decorator in Python — How To Simplifying Your Code And Boost Your Function
10#Episode#PurePythonSeries — CS50 — A Taste of Python — Harvard Mario’s Challenge Solver \o/
11#Episode#PurePythonSeries — Python — Send Email Using SMTP — Send Mail To Any Internet Machine (SMTP or ESMTP)
12#Episode#PurePythonSeries — Advanced Python Technologies — qrcode, Speech Recognition in Python, Google Speech Recognition
13#Episode#PurePythonSeries — Advanced Python Technologies II — qFace Recognition w/ Jupyter Notebook & Ubuntu
14#Episode#PurePythonSeries — Advanced Python Technologies III — Face Recognition w/ Colab
15#Episode#PurePythonSeries — ISS Tracking Project — Get an Email alert when International Space Station (ISS) is above of us in the sky, at night
16#Episode#PurePythonSeries —Using Gemini Chat on Collab — Random Number Generation, List Manipulation & Rock-Paper-Scissors Game Implementations
17#Episode#PurePythonSeries — Python — Basics — Functions, OOP, file handling, calculator, loops (this one)
18#Episode#PurePythonSeries — Python — Efficient File Handling in Python — Best Practices and Common Methods
19#Episode#PurePythonSeries — Python — How To Securely Save Credentials in Python — Like API tokens, passwords, or other sensitive data





