This post is just me playing around with learning Python.
I have a good handle on R scrip but I wanted to learn python to round out my skills.
I am following an example from Maven Analytics course Python Foundations for Data Analysis
import pandas
def tax_calculator(subtotal, sales_tax=0): # adding = gives default argument if none given
""" takes in a subtotal and tax rate and returns total sale
Args:
subtotal (float): cost of transaction
sales_tax (float): tax rate at store location
Returns:
(float): total amount owed
"""
= subtotal + (subtotal * sales_tax)
total return total
= tax_calculator(100, .06)
totalsale
print(totalsale)
106.0
R Script Version
Rtax_calculator <- function(subtotal, sales_tax){
total = subtotal + (subtotal*sales_tax)
}
totalsaleR <- Rtax_calculator(100,.06)
print(totalsaleR)
[1] 106
Python text cleaner
= ["5 stars", "4 3star"]
website_ratings
def rating_cleaner(*ratings, index = 0):
""" takes in a string and returns a clean integer
Args:
ratings (string): string to be cleaned
index (int, optional): location in the string
Returns:
(int): clean integer
"""
for rating in ratings:
= int(rating[index])
numeric_rating print(numeric_rating)
*website_ratings) rating_cleaner(
5
4
Outputting to separate variables
= ["5 stars", "4 star", "3stars"]
website_ratings
def rating_cleaner2(rating):
= int(rating[0])
numeric_rating # global numeric_rating = int(rating[0]) # global function allows variable to be used outside of the function
return rating, numeric_rating
= rating_cleaner2(website_ratings[0])
rating, numeric_rating
rating
'5 stars'
numeric_rating
5
Notes about writing personal code libraries that can be imported and used later.
# %% writefile rating_cleaner2.py allows the creation of a module aka personal library that can later be imported and used.
# def rating_cleaner2(rating):
# numeric_rating = int(rating[0])
# return rating, numeric_rating
# import ratingcleaner2 as r
# r.ratingcleaner2()