avatarJ3

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

6686

Abstract

4Step —<b> Open Files; </b>Use <b>open()</b>:</p><div id="6cb1"><pre> <span class="hljs-keyword">def</span> <span class="hljs-title function_">open_file</span>(<span class="hljs-params">filename</span>): <span class="hljs-keyword">try</span>: file = <span class="hljs-built_in">open</span>(filename, <span class="hljs-string">'r'</span>) contents = file.read() <span class="hljs-built_in">print</span>(contents) <span class="hljs-keyword">except</span> FileNotFoundError: <span class="hljs-built_in">print</span>(<span class="hljs-string">f"File '<span class="hljs-subst">{filename}</span>' not found."</span>) <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e: <span class="hljs-built_in">print</span>(<span class="hljs-string">f"An error occurred: <span class="hljs-subst">{e}</span>"</span>) <span class="hljs-keyword">finally</span>: <span class="hljs-keyword">if</span> <span class="hljs-string">'file'</span> <span class="hljs-keyword">in</span> <span class="hljs-built_in">locals</span>(): file.close()</pre></div><p id="d01b">or <b>with open()</b>:</p><div id="e421"><pre><span class="hljs-comment"># prompt: Generating a method to read a file use with open()</span>

<span class="hljs-keyword">def</span> <span class="hljs-title function_">read_file</span>(<span class="hljs-params">filename</span>): <span class="hljs-keyword">try</span>: <span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(filename, <span class="hljs-string">'r'</span>) <span class="hljs-keyword">as</span> file: contents = file.read() <span class="hljs-built_in">print</span>(contents) <span class="hljs-keyword">except</span> FileNotFoundError: <span class="hljs-built_in">print</span>(<span class="hljs-string">f"File '<span class="hljs-subst">{filename}</span>' not found."</span>) <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e: <span class="hljs-built_in">print</span>(<span class="hljs-string">f"An error occurred: <span class="hljs-subst">{e}</span>"</span>) <span class="hljs-keyword">finally</span>: <span class="hljs-keyword">if</span> <span class="hljs-string">'file'</span> <span class="hljs-keyword">in</span> <span class="hljs-built_in">locals</span>(): file.close()</pre></div><div id="f9e4"><pre>read_file(<span class="hljs-string">"sample_data/worksheet.py"</span>)</pre></div><p id="d8b9">It will create a file inside in this directory.</p><p id="d62e">5Step — <b>Input Data:</b></p><div id="d505"><pre> <span class="hljs-keyword">def</span> <span class="hljs-title function_">enter_number</span>(): <span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>: <span class="hljs-keyword">try</span>: number = <span class="hljs-built_in">float</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">f"Enter a number: "</span>))
<span class="hljs-keyword">except</span> ValueError: <span class="hljs-built_in">print</span>(<span class="hljs-string">"Invalid input."</span>)

  <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
    <span class="hljs-built_in">print</span>(<span class="hljs-string">f"An error occurred: <span class="hljs-subst">{e}</span>  "</span>)
    <span class="hljs-keyword">continue</span>
  <span class="hljs-keyword">else</span>:
    <span class="hljs-keyword">return</span> number
    <span class="hljs-keyword">break</span></pre></div><div id="23ba"><pre>  enter_number()</pre></div><div id="d024"><pre>Enter <span class="hljs-keyword">a</span> <span class="hljs-built_in">number</span>: w

Invalid input. Enter <span class="hljs-keyword">a</span> <span class="hljs-built_in">number</span>: <span class="hljs-number">1</span> <span class="hljs-number">1.0</span></pre></div><p id="f109">Another without<b> continue/break</b> :</p><div id="27f9"><pre> <span class="hljs-keyword">def</span> <span class="hljs-title function_">enter_number</span>(): <span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>: <span class="hljs-keyword">try</span>: number = <span class="hljs-built_in">float</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">f"Enter a number: "</span>))
<span class="hljs-keyword">except</span> ValueError: <span class="hljs-built_in">print</span>(<span class="hljs-string">"Invalid input. Enter a number:"</span>) <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e: <span class="hljs-built_in">print</span>(<span class="hljs-string">f"An error occurred: <span class="hljs-subst">{e}</span> "</span>) <span class="hljs-keyword">else</span>: <span class="hljs-keyword">return</span> number</pre></div><div id="6795"><pre>enter_number()</pre></div><div id="e2a6"><pre>Enter <span class="hljs-keyword">a</span> <span class="hljs-built_in">number</span>: w Invalid input. Enter <span class="hljs-keyword">a</span> <span class="hljs-built_in">number</span>: Enter <span class="hljs-keyword">a</span> <span class="hljs-built_in">number</span>: Invalid input. Enter <span class="hljs-keyword">a</span> <span class="hljs-built_in">number</span>: Enter <span class="hljs-keyword">a</span> <span class="hljs-built_in">number</span>: w Invalid input. Enter <span class="hljs-keyword">a</span> <span class="hljs-built_in">number</span>: Enter <span class="hljs-keyword">a</span> <span class="hljs-built_in">number</span>: <span class="hljs-number">1</span> <span class="hljs-number">1.0</span></pre></div><p id="ac24">6Step — <b>Diff Return x Break:</b></p><div id="092e"><pre><span class="hljs-comment"># Difference between Return and Break statements:</span> <span class="hljs-comment"># https://stackoverflow.com/questions/6620949/difference-between-return-and-break-statements</span>

<span class="hljs-comment"># break is used to exit (escape) the for-loop, while-loop, </span> <span class="hljs-comment"># switch-statement that you are currently executing.</span>

<span class="hljs-comment"># return will exit the entire method you are currently executing </span> <span class="hljs-comment"># (and possibly return a value to the caller, optional).</span>

<span class="hljs-keyword">def</span> <span class="hljs-title function_">f</span>(): <span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>: <span class="hljs-keyword">if</span> x == <span class="hljs-number">0</span>: <span c

Options

lass="hljs-keyword">break</span> <span class="hljs-comment"># escape while() and jump to execute code after the loop</span> <span class="hljs-keyword">elif</span> x == <span class="hljs-number">1</span>: <span class="hljs-built_in">print</span>(<span class="hljs-string">"Returning imediatelly"</span>) <span class="hljs-built_in">print</span>(<span class="hljs-string">"Outside the f()"</span>) <span class="hljs-keyword">return</span> <span class="hljs-comment"># will end the function f() immediately</span> <span class="hljs-comment"># no further code inside this method will be executed.</span> <span class="hljs-comment"># ... other code to execute within the loop ...</span>

<span class="hljs-comment"># Code to execute after the loop (if x == 0)</span> <span class="hljs-built_in">print</span>(<span class="hljs-string">"Loop exited from while with break."</span>) <span class="hljs-built_in">print</span>(<span class="hljs-string">"Inside the f()"</span>) <span class="hljs-built_in">print</span>(<span class="hljs-string">"You can now write a function (f()) to define its purpose"</span>)</pre></div><div id="4738"><pre>x = <span class="hljs-number">1</span> f()</pre></div><div id="cd3c"><pre>Returning imediatelly Outside the <span class="hljs-built_in">f</span>()</pre></div><div id="7cfd"><pre>x = <span class="hljs-number">0</span> f()</pre></div><div id="6c7d"><pre><span class="hljs-keyword">Loop</span> exited <span class="hljs-keyword">from</span> <span class="hljs-keyword">while</span> <span class="hljs-keyword">with</span> <span class="hljs-keyword">break</span>. Inside the f() You can now <span class="hljs-keyword">write</span> a <span class="hljs-keyword">function</span> <span class="hljs-params">(f()</span>) <span class="hljs-title function_">to</span> <span class="hljs-title function_">define</span> <span class="hljs-title function_">its</span> <span class="hljs-title function_">purpose</span></pre></div><div id="ff6b"><pre><span class="hljs-built_in">print</span>(<span class="hljs-string">"That's it folks!"</span>)</pre></div><div id="92be"><pre>That<span class="hljs-symbol">'s</span> it folks!</pre></div><figure id="4dd3"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*ki3Ukj4sMV9KnRV1Nwuo9g.png"><figcaption></figcaption></figure><h1 id="6c68">Related Posts</h1><p id="54d4"><b>00</b>#Episode#PurePythonSeries — <a href="https://readmedium.com/lambda-in-python-421b0c18e825"><b>Lambda in Python </b></a>— Python Lambda Desmistification</p><p id="fafa"><b>01</b>#Episode#PurePythonSeries — <a href="https://readmedium.com/send-emails-using-python-jupyter-notebook-94d14a5a5655"><b>Send Email in Python</b></a> — Using Jupyter Notebook — How To Send Gmail In Python</p><p id="4070"><b>02</b>#Episode#PurePythonSeries — <a href="https://readmedium.com/automate-your-email-marketing-with-python-f0d68234b789"><b>Automate Your Email With Python & Outlook</b></a><b> </b>— How To Create An Email Trigger System in Python</p><p id="b99b"><b>03</b>#Episode#PurePythonSeries — <a href="https://readmedium.com/manipulating-files-with-python-3f9a781287e9"><b>Manipulating Files With Python</b></a> — Manage Your Lovely Photos With Python!</p><p id="ae02"><b>04</b>#Episode#PurePythonSeries — <a href="https://readmedium.com/pandas-dataframe-advanced-48f83a5b097f"><b>Pandas DataFrame Advanced </b></a>— A Complete Notebook Review</p><p id="dc99"><b>05</b>#Episode#PurePythonSeries — <a href="https://readmedium.com/is-this-leap-year-python-calendar-3d1a61f2c4a7"><b>Is This Leap Year? Python Calendar</b> </a>— How To Calculate If The Year Is Leap Year and How Many Days Are In The Month</p><p id="4f16"><b>06</b>#Episode#PurePythonSeries — <a href="https://readmedium.com/list-comprehension-in-python-c22c4b0a6a8a"><b>List Comprehension In Python </b></a>— Locked-in Secrets About List Comprehension</p><p id="6ab3"><b>07</b>#Episode#PurePythonSeries — <a href="https://readmedium.com/graphs-in-python-b7d243737b77"><b>Graphs — In Python </b></a>— Extremely Simple Algorithms in Python</p><p id="5a66"><b>08</b>#Episode#PurePythonSeries — <a href="https://readmedium.com/decorator-in-python-62c00f7e818"><b>Decorator in Python</b></a> — How To Simplifying Your Code And Boost Your Function</p><p id="ab4b"><b>10</b>#Episode#PurePythonSeries —<b> <a href="https://readmedium.com/cs50-a-taste-of-python-a4ac87883ff4">CS50</a> — A Taste of Python</b> — Harvard Mario’s Challenge Solver \o/</p><p id="d082"><b>11</b>#Episode#PurePythonSeries — Python — <a href="https://readmedium.com/python-send-email-using-smtp-6ecf0b1dd608"><b>Send Email Using SMTP</b></a> — Send Mail To Any Internet Machine (SMTP or ESMTP)</p><p id="a937"><b>12#</b>Episode#PurePythonSeries — <a href="https://readmedium.com/advanced-python-technologies-d3dbdf1d70cb"><b>Advanced Python Technologies</b> </a><a href="https://readmedium.com/advanced-python-technologies-d3dbdf1d70cb">qrcode, Speech Recognition in Python, Google Speech Recognition</a></p><p id="8fcb"><b>13#</b>Episode#PurePythonSeries — <a href="https://readmedium.com/advanced-python-technologies-ii-33d2d6888583"><b>Advanced Python Technologies II</b></a> — qFace Recognition w/ Jupyter Notebook & Ubuntu</p><p id="7fe7"><b>14#</b>Episode#PurePythonSeries — <a href="https://readmedium.com/advanced-python-technologies-iii-ac92cd677e5e"><b>Advanced Python Technologies III</b> </a>— Face Recognition w/ Colab</p><p id="1309"><b>15#</b>Episode#PurePythonSeries —<a href="https://readmedium.com/iss-tracking-project-python-af4b5fa47a28"><b> ISS Tracking Projec</b></a><b>t </b>— Get an Email alert when International Space Station (ISS) is above of us in the sky, at night</p><p id="acaa"><b>16#</b>Episode#PurePythonSeries —<a href="https://readmedium.com/using-gemini-chat-on-collab-2626fb035176"><b>Using Gemini Chat on Collab</b></a><b> </b>— Random Number Generation, List Manipulation & Rock-Paper-Scissors Game Implementations</p><p id="5a5d"><b>17#</b>Episode#PurePythonSeries — Python — <a href="https://readmedium.com/python-basics-2ce557a80f42"><b>Basics</b> </a>— Functions, OOP, file handling, calculator, loops (this one)</p><p id="d03e"><b>18#</b>Episode#PurePythonSeries — Python — <a href="https://readmedium.com/efficient-file-handling-in-python-0d952971ebc9"><b>Efficient File Handling in Python</b></a><b> </b>— Best Practices and Common Methods</p><p id="12e0"><b>19#</b>Episode#PurePythonSeries — Python — <a href="https://readmedium.com/how-to-securely-save-credentials-in-python-dd5c6983741a"><b>How To Securely Save Credentials in Python</b> </a>— Like API tokens, passwords, or other sensitive data</p></article></body>

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 / b
add(1, 2)
3

2 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.5
calculator = 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.0
worksheet.perform_operations(5, 10)
Addition: 15
Subtraction: -5
Multiplication: 50
Division: 0.5

4Step — 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
        break
  enter_number()
Enter a number: w
Invalid input.
Enter a number: 1
1.0

Another 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 number
enter_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.0

6Step — 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 purpose
print("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

Pure Python
Exception Handling
File Handling In Python
Classes And Objects
Encapsulation
Recommended from ReadMedium