STEM with Python – Part 17: Python Fundamentals Ⅳ(Exponent Function, Try/Catch, Reading/Writing files, and Modules/Pip)

A lot to cover…

Since Python offers a lot of fun stuff to toy around with, I’m so excited to learn more about the remarkable language!

Okay, so this is the 17th part of STEM with Python and the fourth part of the Python fundamentals. Here, what we cover includes the exponent function, try/catch, reading/writing files, and modules/pip.

Exponent Function:

In Python, the exponential function is a mathematical function that is used to calculate the value of a number raised to a power, which is typically denoted as “e to the power of x” or “exp(x)”. This function is part of the math module in Python, meaning you need to import the module before you can use the function in your code.

First of all, Sample 1 is the exponent function itself. As I’ve been working on the Algebra series in this blog, you might already have been familiar with the term if you’re my blog’s follower lol

Sample 1:

print(2**3) #2^3

Output:

8

And Sample 2 is the recreation of Sample 1 without using Exponent Function but taking advantage of for-loop.

Sample 2:

def raise_to_power(base_num, power_num):
    result = 1
    for index in range(power_num):
        result = result * base_num
    return result

print(raise_to_power(2, 3))

Output:

8

And as you can see in the output result, what Sample 3 does is sorting out the grid with double-loop technique and list them all at the end.

Sample 3:

num_grid = [
    [1,2,3],
    [4,5,6],
    [7,8,9],
    [0]
]

for row in num_grid:
    for col in row:
        print(col)

Output:

1
2
3
4
5
6
7
8
9
0

Translation app:

This is something similar to what we’ve seen in my other coding series Road to Google‘s Palindrome section where we’ve gone through a string with a double-loop to sort out the string. Here, what we do is replace a vowel sound with the letter “z” by taking advantage of a for-loop and if-statement.

def translate(phrase):
    translation = ""
    for letter in phrase:
        if letter in "AEIOUaeiou":
            translation = translation + "z"
        else:
            translation = translation + letter
    return translation

print(translate(input("Enter a phrase: ")))

Output:

Enter a phrase: cat
czt

Try/Catch:

Just like Java’s try and catch like I’ve done it before, it’s basically the same logic that’s working on. In Python, the try and except statements are used for exception handling. Exception handling is a way to deal with errors that may occur during the execution of a program, such as a divide-by-zero error or an attempt to access an invalid file.

Sample 1:

try:
    number = int(input("Enter a number "))
    print(number)
except:
    print("Invalid Input")

Output:

Enter a number dweadwa
Invalid Input

And… Sample 2 is the better version of it.

Sample 2:

try:
    number = int(input("Enter a number "))
    print(number)
except ZeroDivisionError as err:
    print(err)
except ValueError as err:
    print(err)

Output:

Enter a number sss
invalid literal for int() with base 10: 'sss'

Reading files:

Previously, when I covered reading files in Python, it was about how to do the process in Linux. Since this time, I use Windows as my platform machine and use PyCharm, the file path syntax abides by based on the Microsoft OS’s rules. But the logic behind it is all the same with Linux as well.

employee.txt

Tom - Salesman
Jim - Accountant
Sarah - Programmer

ReadingFile.py

employee_file = open("employee.txt", "r")

for line in employee_file.readlines():
    print(line)

employee_file.close()
Tom - Salesman

Jim - Accountant

Sarah - Programmer

Writing to files:

“a” is for append. If you have done programming or are familiar with computing terms in general, you might be aware of, it appends a new line in a file that already contains some data in it.

WritingFile.py

employee_file = open("employee.txt", "a")

employee_file.write("\nKelly - Managaer")

employee_file.close()

employee.txt

Tom - Salesman
Jim - Accountant
Sarah - Programmer
Kelly - Managaer

WritingFile.py

And “w” stands for “write” and it replaces the old data with the new line. So, in this case, the old lines were all gone.

employee_file = open("employee.txt", "w")

employee_file.write("\nKelly - Managaer")

employee_file.close()

employee.txt

Kelly - Managaer

Modules and Pip:

You can use other python file functions by importing them. Here, SampleApp.py imports useful_tools.py and SampleApp.py can access to the latter’s functions.

useful_tools.py

import random

feet_in_miles = 5280
meters_in_kilometer = 1000
beatles = ["John Lennon", "Paul McCartney", "George Harrison"]

def get_file_ext(filename):
    return filename[filename.index(".") + 1]

def roll_dice(num):
    return random.randient(1, num)

SampleApp.py

import useful_tools

print(useful_tools.roll_dice(10))

In PyCharm, you can find all the default modules under the Lib folder.

Pip:

You can check pip’s version info by typing like this on cmd.

PS C:\Users\deeps> pip --version
pip 22.3.1 from D:\Program Files\Python311\Lib\site-packages\pip (python 3.11)
PS C:\Users\deeps>

Leave a Reply