From e49d51eb06f1adcb01f7fa9ed90d1f125597e1bb Mon Sep 17 00:00:00 2001 From: EggMan Date: Tue, 23 Apr 2024 09:40:13 -0400 Subject: [PATCH] init --- .idea/.gitignore | 8 + .idea/CNSA-266-Personal.iml | 10 + .../inspectionProfiles/profiles_settings.xml | 6 + .idea/misc.xml | 4 + .idea/modules.xml | 8 + .idea/vcs.xml | 6 + Barista.py | 18 ++ Intro.py | 5 + Lists.py | 88 +++++ MathPractice.py | 129 ++++++++ Order.py | 42 +++ PhoneDirectory.py | 280 ++++++++++++++++ Skateboards.py | 99 ++++++ fivestar.py | 37 +++ phonev2.py | 306 ++++++++++++++++++ records.txt | 3 + scratch.py | 0 17 files changed, 1049 insertions(+) create mode 100644 .idea/.gitignore create mode 100644 .idea/CNSA-266-Personal.iml create mode 100644 .idea/inspectionProfiles/profiles_settings.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml create mode 100644 Barista.py create mode 100644 Intro.py create mode 100644 Lists.py create mode 100644 MathPractice.py create mode 100644 Order.py create mode 100644 PhoneDirectory.py create mode 100644 Skateboards.py create mode 100644 fivestar.py create mode 100644 phonev2.py create mode 100644 records.txt create mode 100644 scratch.py diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/CNSA-266-Personal.iml b/.idea/CNSA-266-Personal.iml new file mode 100644 index 0000000..2c80e12 --- /dev/null +++ b/.idea/CNSA-266-Personal.iml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..105ce2d --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..37d5de6 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..6694fc8 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Barista.py b/Barista.py new file mode 100644 index 0000000..bd3f134 --- /dev/null +++ b/Barista.py @@ -0,0 +1,18 @@ +NUM_EMPLOYEES = 6 + +def main(): + hours = [0.0] * NUM_EMPLOYEES + + for index in range(NUM_EMPLOYEES): + print("Enter the hours worked by employee ", index + 1, ": ", sep="", end="") + hours[index] = float(input()) + + pay_rate = float(input("Enter the hourly pay rate: ")) + + for index in range(NUM_EMPLOYEES): + gross_pay = hours[index] * pay_rate + print("Gross pay for employee ", index + 1, ": $", format(gross_pay, ',.2f'), sep="") + + + +main() \ No newline at end of file diff --git a/Intro.py b/Intro.py new file mode 100644 index 0000000..17c52ea --- /dev/null +++ b/Intro.py @@ -0,0 +1,5 @@ +name = input("What is your name? ") +quantity = int(input("How many items do you have? ")) +cost = float(input("how many dollars does each cost? ")) +discount = int(input("What is the discount percentage? ")) +print("Hello " + name + ". You have " + str(quantity) + " items, and each costs $" + str(cost) + " and there is a " + str(discount) + "% discount") diff --git a/Lists.py b/Lists.py new file mode 100644 index 0000000..c4e7b19 --- /dev/null +++ b/Lists.py @@ -0,0 +1,88 @@ +# SLIDE 2 + +# Create a list of grades +grades = [10,20,30,40] + +#print grades +print(grades) + +# SLIDE 3 + +# Concatenate grades +grades = grades + [50,60,70] + +# Print grades +print("After concatenation: " + str(grades)) + +#SLIDE 4 + +# Append to grades +grades.extend([50,60,70,70]) +print("After extending the list: " + str(grades)) + +# Find the count, total, min, max average grade +print("Count of grades: " + str(len(grades))) + +# SLIDE 5 + +# Print min & Max +print("Min of grades: " + str(min(grades))) +print("Max of grades: " + str(max(grades))) + +# SLIDE 6 + +# Print total +total = 0 +for item in grades: + total += item + +print("Total of grades is: " + str(total)) + +# SLIDE 7 + +# Average of grades + +avg_grade = total / len(grades) +print("Average grade: " + str(round(avg_grade, 2))) + +# SLIDE 8 + +from statistics import * +# Simple average +print("Simple average: " + str(round(mean(grades), 2))) +# Simple total +print("Simple sum is: " + str(round(sum(grades), 2))) + +# SLIDE 9 + +superbowl_teams = ["Patriots", "Patriots", "Steelers", "Steelers", "Ravens", "Chiefs", "Packers"] + +print("Superbowl Champions:") +for teams in superbowl_teams: + print("\t" + teams) + +# SLIDE 10 + +unique = [] +dupes = [] + +for j in superbowl_teams: + if j not in unique: + unique.append(j) + else: + dupes.append(j) + +# SLIDE 11 + +if len(dupes) != 0: + print("Teams that have won multiple championships: ") + + for i in dupes: + print(i) + +# Check unique teams +if len(unique) != 0: + print("These teams have all won a super bowl: ") + + for k in unique: + print(k) \ No newline at end of file diff --git a/MathPractice.py b/MathPractice.py new file mode 100644 index 0000000..08b4c29 --- /dev/null +++ b/MathPractice.py @@ -0,0 +1,129 @@ +import sys +import time + +DEBUG = False + +totalCorrect = 0 +totalIncorrect = 0 + +# will ask the user if they want to exit the program +def tryExit(): + userIn = "" + while True: + userIn = input("Would you like to exit the program? (y/n) ") + if userIn == "y" or userIn == "Y": + print("\n\n\nThank you for using Math Practice!") + time.sleep(0.5) + print("You got " + str(totalCorrect) + " correct, and " + str(totalIncorrect) + " incorrect.") + sys.exit(0) + elif userIn == "n" or userIn == "N": + break + print("Please enter y or n.") + time.sleep(0.2) + + + +# loops forever until the user enters a valid input (float) +def getInput(message): + userInput = "" + while True: + userInput = input(message) + try: + userInput = float(userInput) + break + except Exception as e: + print("Please enter a valid number.") + time.sleep(0.2) + + if userInput == -99: + tryExit() + + return userInput + +# loops forever until the user enters a valid operator +def getOperator(): + userInput = "" + while True: + try: + userInput = input("Please choose an operator ( + - / * ): ") + + if userInput == "+": + break + elif userInput == "-": + break + elif userInput == "*": + break + elif userInput == "/": + break + elif userInput == "-99": + tryExit() + else: + raise Exception("Please enter a valid operator.") + except Exception as e: + print(e) + time.sleep(0.2) + + return userInput + +# runs a calculation based on two numbers, and the operator provided +def calculate(first, second, op): + if op == "+": + return first + second + if op == "-": + return first - second + if op == "*": + return first * second + if op == "/": + return first / second + +# returns the int value of a float if possible +def reduce(num): + oNum = num + intNum = int(num) + if intNum == oNum: + return intNum + else: + return oNum + +if not DEBUG: + print("\n"*100) + print("Welcome to Math Practice!") + time.sleep(2) + print("This program will ask you to enter one number, then an operation, and a second number") + time.sleep(2) + print("You will then input the answer that you believe to be correct") + time.sleep(2) + print("Your score will be calculated based on how many you got correct and how many you guessed incorrectly") + time.sleep(2) + print("You may enter -99 to exit at any time") + time.sleep(2) + print("Enjoy!") + time.sleep(2) + input("Press Enter to start!") + print("\n"*100) + +# The Main Running Space +while True: + num1 = getInput("Please enter the first number: ") + op = getOperator() + num2 = getInput("Please enter the second number: ") + print("\n") + print("Your equation is: " + str(reduce(num1)) + " " + op + " " + str(reduce(num2))) + userAnswer = getInput("Please enter what you think the answer is: ") + answer = calculate(num1, num2, op) + + if float(userAnswer) == answer: + print("Correct!") + totalCorrect += 1 + time.sleep(1) + print("\n"*100) + print("You may enter -99 to exit at any time\n") + else: + print("Incorrect. Better luck next time!.") + totalIncorrect += 1 + time.sleep(1) + print("\n"*100) + print("You may enter -99 to exit at any time\n") + + + diff --git a/Order.py b/Order.py new file mode 100644 index 0000000..fef2b68 --- /dev/null +++ b/Order.py @@ -0,0 +1,42 @@ +import time + +fName = input("Enter your first name: ") +lName = input("Enter your last name: ") +fullAddress = input("Enter your full address, seperated by semicolons (;): ") +while True: + SSN = input("Enter your SSN in numerical format (e.g. 312943821): ") + if len(SSN) == 9: + break + else: + print("invalid SSN!") + time.sleep(0.3) +while True: + payType = input("Enter your payment type (options are: MasterCard, Discover, Visa, Cash, or Check: ") + if payType.upper() == "MasterCard".upper() or payType.upper() == "VISA".upper() or payType.upper() == "CASH".upper() or payType.upper() == "CHECK".upper() or payType.upper() == "DISCOVER".upper(): + break + print("Please enter a valid payment type.") + time.sleep(0.3) + +uName = input("Enter your username: ") +uPassword = input("Enter your password: ") +uEmail = input("Enter your email address: ") + +fullAddress = fullAddress.split(';') +print("\n" * 8) +print("Confirmation for " + fName + " " + lName + " at ", end="") +trace = 0 +for i in fullAddress: + if trace == len(fullAddress)-1: + print(i.strip()+". ", end="\n") + else: + print(i.strip()+", ", end="") + trace += 1 +print("The last 4 digits of your SSN is ***-**-" + SSN[5:] + ".") +print("Your payment will be made with " + payType + ".") +print("Your username is: " + uName) +hPass = "" +while len(hPass) < len(uPassword): + hPass = hPass + "*" +print("Your password (hidden) is: " + hPass) +print("An email has been sent to you at: " + uEmail + ".", end="\n"*3) +print("Thank you!") \ No newline at end of file diff --git a/PhoneDirectory.py b/PhoneDirectory.py new file mode 100644 index 0000000..21f414c --- /dev/null +++ b/PhoneDirectory.py @@ -0,0 +1,280 @@ +# importing the module +import sys + + +# this function will be the first to run as soon as the main function executes +def initial_phonebook(): + rows, cols = int(input("Please enter initial number of contacts: ")), 5 + + # We are collecting the initial number of contacts the user wants to have in the + # phonebook already. User may also enter 0 if he doesn't wish to enter any. + phone_bookA = open("records.txt", 'a') + phone_bookR = open("records.txt", 'r') + print(phone_bookR.read()) + for i in range(rows): + print("\nEnter contact %d details in the following order (ONLY):" % (i + 1)) + print("NOTE: * indicates mandatory fields") + print("....................................................................") + temp = [] + for j in range(cols): + + # We have taken the conditions for values of j only for the personalized fields + # such as name, number, e-mail id, dob, category etc + if j == 0: + temp.append(str(input("Enter name*: "))) + + # We need to check if the user has left the name empty as its mentioned that + # name & number are mandatory fields. + # So implement a condition to check as below. + if temp[j] == '' or temp[j] == ' ': + sys.exit( + "Name is a mandatory field. Process exiting due to blank field...") + # This will exit the process if a blank field is encountered. + + if j == 1: + temp.append(int(input("Enter number*: "))) + # We do not need to check if user has entered the number because int automatically + # takes care of it. Int value cannot accept a blank as that counts as a string. + # So process automatically exits without us using the sys package. + + if j == 2: + temp.append(str(input("Enter e-mail address: "))) + # Even if this field is left as blank, None will take the blank's place + if temp[j] == '' or temp[j] == ' ': + temp[j] = None + + if j == 3: + temp.append(str(input("Enter date of birth(dd/mm/yy): "))) + # Whatever format the user enters dob in, it won't make a difference to the compiler + # Only while searching the user will have to enter query exactly the same way as + # he entered during the input so as to ensure accurate searches + if temp[j] == '' or temp[j] == ' ': + # Even if this field is left as blank, None will take the blank's place + temp[j] = None + if j == 4: + temp.append( + str(input("Enter category(Family/Friends/Work/Others): "))) + # Even if this field is left as blank, None will take the blank's place + if temp[j] == "" or temp[j] == ' ': + temp[j] = None + + for record in temp: + phone_bookA.write(str(record) + ",") + phone_bookA.write("\n") + # By this step we are appending a list temp into a list phone_book + # That means phone_book is a 2-D array and temp is a 1-D array + + print(phone_bookR.read()) + return phone_bookR.read() + + +def menu(): + # We created this simple menu function for + # code reusability & also for an interactive console + # Menu func will only execute when called + print("********************************************************************") + print("\t\t\tSMARTPHONE DIRECTORY", flush=False) + print("********************************************************************") + print("\tYou can now perform the following operations on this phonebook\n") + print("1. Add a new contact") + print("2. Remove an existing contact") + print("3. Delete all contacts") + print("4. Search for a contact") + print("5. Display all contacts") + print("6. Exit phonebook") + + # Out of the provided 6 choices, user needs to enter any 1 choice among the 6 + # We return the entered choice to the calling function wiz main in our case + choice = int(input("Please enter your choice: ")) + + return choice + + +def add_contact(): + # Adding a contact is the easiest because all you need to do is: + # append another list of details into the already existing list + dip = [] + for i in range(5): + if i == 0: + dip.append(str(input("Enter name: "))) + if i == 1: + dip.append(str(input("Enter number: "))) + if i == 2: + dip.append(str(input("Enter e-mail address: "))) + if i == 3: + dip.append(str(input("Enter date of birth(dd/mm/yy): "))) + if i == 4: + dip.append( + str(input("Enter category(Family/Friends/Work/Others): "))) + pb = open("records.txt", 'a') + for record in dip: + pb.write(record + ",") + pb.write("\n") + pb.close() + + +def remove_existing(): + pbr = open("records.txt", 'r') + pbw = open("records.txt", 'w') + + # This function is to remove a contact's details from existing phonebook + query = str( + input("Please enter the name of the contact you wish to remove: ")) + # We'll collect name of the contact and search if it exists in our phonebook + pb = [] + temp = 0 + # temp is a checking variable here. We assigned a value 0 to temp. + + for i in range(len(pb)): + if query == pbr[i][0]: + temp += 1 + # Temp will be incremented & it won't be 0 anymore in this function's scope + + print(pb.pop(i)) + # The pop function removes entry at index i + + print("This query has now been removed") + # printing a confirmation message after removal. + # This ensures that removal was successful. + # After removal we will return the modified phonebook to the calling function + # which is main in our program + + return pb + if temp == 0: + # Now if at all any case matches temp should've incremented but if otherwise, + # temp will remain 0 and that means the query does not exist in this phonebook + print("Sorry, you have entered an invalid query.\ + Please recheck and try again later.") + + return pb + + +def delete_all(): + # This function will simply delete all the entries in the phonebook pb + # It will return an empty phonebook after clearing + + pb = open("records.txt", 'w') + pb.write("") + + +def search_existing(): + # This function searches for an existing contact and displays the result + choice = int(input("Enter search criteria\n\n\ + 1. Name\n2. Number\n3. Email-id\n4. DOB\n5. Category(Family/Friends/Work/Others)\ + \nPlease enter: ")) + # We're doing so just to ensure that the user experiences a customized search result + + temp = [] + check = -1 + + if choice == 1: + # This will execute for searches based on contact name + query = str( + input("Please enter the name of the contact you wish to search: ")) + for i in range(len(pb)): + if query == pb[i][0]: + check = i + temp.append(pb[i]) + + elif choice == 2: + # This will execute for searches based on contact number + query = int( + input("Please enter the number of the contact you wish to search: ")) + for i in range(len(pb)): + if query == pb[i][1]: + check = i + temp.append(pb[i]) + + elif choice == 3: + # This will execute for searches based on contact's e-mail address + query = str(input("Please enter the e-mail ID\ + of the contact you wish to search: ")) + for i in range(len(pb)): + if query == pb[i][2]: + check = i + temp.append(pb[i]) + + elif choice == 4: + # This will execute for searches based on contact''s date of birth + query = str(input("Please enter the DOB (in dd/mm/yyyy format ONLY)\ + of the contact you wish to search: ")) + for i in range(len(pb)): + if query == pb[i][3]: + check = i + temp.append(pb[i]) + + elif choice == 5: + # This will execute for searches based on contact category + query = str( + input("Please enter the category of the contact you wish to search: ")) + for i in range(len(pb)): + if query == pb[i][4]: + check = i + temp.append(pb[i]) + # All contacts under query category will be shown using this feature + + else: + # If the user enters any other choice then the search will be unsuccessful + print("Invalid search criteria") + return -1 + # returning -1 indicates that the search was unsuccessful + + # all the searches are stored in temp and all the results will be displayed with + # the help of display function + + if check == -1: + return -1 + # returning -1 indicates that the query did not exist in the directory + else: + display_all(temp) + return check + # we're just returning a index value wiz not -1 to calling function just to notify + # that the search worked successfully + + +# this function displays all content of phonebook pb +def display_all(pb): + if not pb: + # if display function is called after deleting all contacts then the len will be 0 + # And then without this condition it will throw an error + print("List is empty: []") + else: + for i in range(len(pb)): + print(pb[i]) + + +def thanks(): + # A simple gesture of courtesy towards the user to enhance user experience + print("********************************************************************") + print("Thank you for using our Smartphone directory system.") + print("Please visit again!") + print("********************************************************************") + sys.exit("Goodbye, have a nice day ahead!") + + +# Main function code +print("....................................................................") +print("Hello dear user, welcome to our smartphone directory system") +print("You may now proceed to explore this directory") +print("....................................................................") +# This is solely meant for decoration purpose only. +# You're free to modify your interface as per your will to make it look interactive + +ch = 1 +initial_phonebook() +while ch in (1, 2, 3, 4, 5): + ch = menu() + if ch == 1: + add_contact() + elif ch == 2: + remove_existing() + elif ch == 3: + delete_all() + elif ch == 4: + d = search_existing() + if d == -1: + print("The contact does not exist. Please try again") + elif ch == 5: + display_all() + else: + thanks() diff --git a/Skateboards.py b/Skateboards.py new file mode 100644 index 0000000..a86663b --- /dev/null +++ b/Skateboards.py @@ -0,0 +1,99 @@ +import time + + +# Item Prices +YELLOW_COST = 15.97 +BLUE_COST = 24.99 + +# Summary Values +totalYellow = 0 +totalBlue = 0 +TotalTransactions = 0 +TotalSales = 0.0 + +# Tax Rates +IN_TAX = 0.04 +OUT_TAX = 0.06 + +repeat = True + +print("\n"*100) +print("Welcome to TSCT Skating Association!\n") + +# Keep looping until user decides to exit +while repeat: + state = "z" + sale = 0.0 + + # Get number of blue skateboards + blue = input("How many blue skateboards ($24.99) would you like to purchase: ") + if blue.isnumeric(): + blue = int(blue) + else: + blue = 0 + + # Get number of yellow skateboards + yellow = input("How many yellow skateboards ($15.97) would you like to purchase: ") + if yellow.isnumeric(): + yellow = int(yellow) + else: + yellow = 0 + + # Get whether the user is from out of state or not for use with tax rates + while True: + state = input("Are you from out of state? (y/n): ") + if state == "y" or state == "Y" or state == "n" or state == "N": + break + else: + print("Please enter either 'y' or 'n'.") + + # set tax rates + if state == "y" or state == "Y": + tax = OUT_TAX + else: + tax = IN_TAX + + # Calculate this sale + sale = round((blue * BLUE_COST + yellow * YELLOW_COST) * (1+tax),2) + + # Update running totals + totalYellow += yellow + totalBlue += blue + TotalTransactions += 1 + TotalSales += sale + + # Print out the sale + print("You sold " + str(format(blue, ',')) + " blue skateboards, and " + str(format(yellow, ',')) + " yellow skateboards.") + print("This will cost $" + str(format(sale, ',.2f')), end="\n\n") + + # ask the user if they would like to make another sale + while True: + again = input("Would you like to make another sale? (y/n): ") + if again == "y" or again == "Y": + print("Initiating a new sale.",end="") + time.sleep(0.5) + print(".",end="") + time.sleep(0.5) + print(".",end="") + time.sleep(0.5) + print("\n"*100) + break + elif again == "n" or again == "N": + print("Exiting.",end="") + time.sleep(0.5) + print(".",end="") + time.sleep(0.5) + print(".",end="") + time.sleep(0.5) + print("\n"*100) + repeat = False + break + else: + print("Please enter either 'y' or 'n'.") + + +# Print out the summary +print("You sold " + str(format(totalBlue,',')) + " blue skateboards, and " + str(format(totalYellow,',')) + " yellow skateboards.") +print("You made a total of " + str(format(TotalTransactions,',')) + " individual transactions.") +print("You made $" + str(format(round(TotalSales,2),',.2f')), end=".\n\n") +print("Thank you for using TSCT Skating Association!") \ No newline at end of file diff --git a/fivestar.py b/fivestar.py new file mode 100644 index 0000000..f6e113b --- /dev/null +++ b/fivestar.py @@ -0,0 +1,37 @@ +STD_TAX = 0.06 +OTH_TAX = 0.05 +while True: + con = "Z" + validstate = False + fullName = str(input("Enter your full name: ")) + quan = int(input("Enter the number of items: ")) + cost = float(input("Enter the cost per item: ")) + discount = float(input("Enter the discount percentage (e.g. 10 for 10%): ")) + state = str(input("Enter your state (e.g. PA): ")) + + if state == "PA": + tax = STD_TAX + validstate = True + elif len(state) != 2: + print("invalid state!") + validstate = False + else: + tax = OTH_TAX + validstate = True + + # print("Welcome " + fullName + "!") + # print("You are purchasing " + str(quan) + " items at $" + str(cost) + " per item.") + # print("You will have " + str(int(discount)) + " percent discount.") + # print("Your total is $" + str(round(cost*quan - (((discount/100) * (cost*quan))))*(tax + 1)),2) + if validstate: + print("Thank you: " + fullName) + print("Your Order:") + print("\t Qualtity: " + str(quan)) + print("\t Cost: $" + str(round((cost*quan-(cost*quan*(discount/100)))*(1+tax),2))) + + while (con != "Y" and con != "y") and (con != "N" and con != "n"): + con = input("Do you want to start over? (Y/N): ") + + if con == "N" or con == "n": + break + diff --git a/phonev2.py b/phonev2.py new file mode 100644 index 0000000..67ca8d5 --- /dev/null +++ b/phonev2.py @@ -0,0 +1,306 @@ +# importing the module +import sys + + +# this function will be the first to run as soon as the main function executes +def writeFile(pb): + + b = open("records.txt", 'w') + + for record in pb: + for item in record: + if item != record[len(record) - 1]: + b.write(str(item) + ",") + else: + b.write(str(item) + "\n") + + b.close() + +def readFile(): + + pb = [] + f = open("records.txt", 'r') + while True: + d = f.readline().strip().split(',') + if len(d) == 1: + break + + pb.append(d) + + f.close() + return pb + +def initial_phonebook(): + rows, cols = int(input("Please enter initial number of contacts: ")), 5 + + + # We are collecting the initial number of contacts the user wants to have in the + # phonebook already. User may also enter 0 if he doesn't wish to enter any. + phone_book = readFile() + if rows >= 1: + for i in range(rows): + print("\nEnter contact %d details in the following order (ONLY):" % (i + 1)) + print("NOTE: * indicates mandatory fields") + print("....................................................................") + temp = [] + for j in range(cols): + + # We have taken the conditions for values of j only for the personalized fields + # such as name, number, e-mail id, dob, category etc + if j == 0: + temp.append(str(input("Enter name*: "))) + + # We need to check if the user has left the name empty as its mentioned that + # name & number are mandatory fields. + # So implement a condition to check as below. + if temp[j] == '' or temp[j] == ' ': + sys.exit( + "Name is a mandatory field. Process exiting due to blank field...") + # This will exit the process if a blank field is encountered. + + if j == 1: + temp.append(int(input("Enter number*: "))) + # We do not need to check if user has entered the number because int automatically + # takes care of it. Int value cannot accept a blank as that counts as a string. + # So process automatically exits without us using the sys package. + + if j == 2: + temp.append(str(input("Enter e-mail address: "))) + # Even if this field is left as blank, None will take the blank's place + if temp[j] == '' or temp[j] == ' ': + temp[j] = None + + if j == 3: + temp.append(str(input("Enter date of birth(dd/mm/yy): "))) + # Whatever format the user enters dob in, it won't make a difference to the compiler + # Only while searching the user will have to enter query exactly the same way as + # he entered during the input so as to ensure accurate searches + if temp[j] == '' or temp[j] == ' ': + # Even if this field is left as blank, None will take the blank's place + temp[j] = None + if j == 4: + temp.append( + str(input("Enter category(Family/Friends/Work/Others): "))) + # Even if this field is left as blank, None will take the blank's place + if temp[j] == "" or temp[j] == ' ': + temp[j] = None + + phone_book.append(temp) + # By this step we are appending a list temp into a list phone_book + # That means phone_book is a 2-D array and temp is a 1-D array + + for record in phone_book: + for item in record: + print(f"{item:10}", end="\t") + print("") + return phone_book + + +def menu(): + # We created this simple menu function for + # code reusability & also for an interactive console + # Menu func will only execute when called + print("********************************************************************") + print("\t\t\tSMARTPHONE DIRECTORY", flush=False) + print("********************************************************************") + print("\tYou can now perform the following operations on this phonebook\n") + print("1. Add a new contact") + print("2. Remove an existing contact") + print("3. Delete all contacts") + print("4. Search for a contact") + print("5. Display all contacts") + print("6. Save & Exit phonebook") + + # Out of the provided 6 choices, user needs to enter any 1 choice among the 6 + # We return the entered choice to the calling function wiz main in our case + choice = int(input("Please enter your choice: ")) + + return choice + + +def add_contact(pb): + # Adding a contact is the easiest because all you need to do is: + # append another list of details into the already existing list + dip = [] + for i in range(len(pb[0])): + if i == 0: + dip.append(str(input("Enter name: "))) + if i == 1: + dip.append(int(input("Enter number: "))) + if i == 2: + dip.append(str(input("Enter e-mail address: "))) + if i == 3: + dip.append(str(input("Enter date of birth(dd/mm/yy): "))) + if i == 4: + dip.append( + str(input("Enter category(Family/Friends/Work/Others): "))) + pb.append(dip) + # And once you modify the list, you return it to the calling function wiz main, here. + return pb + + +def remove_existing(pb): + # This function is to remove a contact's details from existing phonebook + query = str( + input("Please enter the name of the contact you wish to remove: ")) + # We'll collect name of the contact and search if it exists in our phonebook + + temp = 0 + # temp is a checking variable here. We assigned a value 0 to temp. + + for i in range(len(pb)): + if query == pb[i][0]: + temp += 1 + # Temp will be incremented & it won't be 0 anymore in this function's scope + + print(pb.pop(i)) + # The pop function removes entry at index i + + print("This query has now been removed") + # printing a confirmation message after removal. + # This ensures that removal was successful. + # After removal we will return the modified phonebook to the calling function + # which is main in our program + + return pb + if temp == 0: + # Now if at all any case matches temp should've incremented but if otherwise, + # temp will remain 0 and that means the query does not exist in this phonebook + print("Sorry, you have entered an invalid query.\ + Please recheck and try again later.") + + return pb + + +def delete_all(pb): + # This function will simply delete all the entries in the phonebook pb + # It will return an empty phonebook after clearing + return pb.clear() + + +def search_existing(pb): + # This function searches for an existing contact and displays the result + choice = int(input("Enter search criteria\n\n\ + 1. Name\n2. Number\n3. Email-id\n4. DOB\n5. Category(Family/Friends/Work/Others)\ + \nPlease enter: ")) + # We're doing so just to ensure that the user experiences a customized search result + + temp = [] + check = -1 + + if choice == 1: + # This will execute for searches based on contact name + query = str( + input("Please enter the name of the contact you wish to search: ")) + for i in range(len(pb)): + if query == pb[i][0]: + check = i + temp.append(pb[i]) + + elif choice == 2: + # This will execute for searches based on contact number + query = int( + input("Please enter the number of the contact you wish to search: ")) + for i in range(len(pb)): + if query == pb[i][1]: + check = i + temp.append(pb[i]) + + elif choice == 3: + # This will execute for searches based on contact's e-mail address + query = str(input("Please enter the e-mail ID\ + of the contact you wish to search: ")) + for i in range(len(pb)): + if query == pb[i][2]: + check = i + temp.append(pb[i]) + + elif choice == 4: + # This will execute for searches based on contact''s date of birth + query = str(input("Please enter the DOB (in dd/mm/yyyy format ONLY)\ + of the contact you wish to search: ")) + for i in range(len(pb)): + if query == pb[i][3]: + check = i + temp.append(pb[i]) + + elif choice == 5: + # This will execute for searches based on contact category + query = str( + input("Please enter the category of the contact you wish to search: ")) + for i in range(len(pb)): + if query == pb[i][4]: + check = i + temp.append(pb[i]) + # All contacts under query category will be shown using this feature + + else: + # If the user enters any other choice then the search will be unsuccessful + print("Invalid search criteria") + return -1 + # returning -1 indicates that the search was unsuccessful + + # all the searches are stored in temp and all the results will be displayed with + # the help of display function + + if check == -1: + return -1 + # returning -1 indicates that the query did not exist in the directory + else: + display_all(temp) + return check + # we're just returning a index value wiz not -1 to calling function just to notify + # that the search worked successfully + + +# this function displays all content of phonebook pb +def display_all(pb): + if not pb: + # if display function is called after deleting all contacts then the len will be 0 + # And then without this condition it will throw an error + print("List is empty: []") + else: + for record in pb: + for item in record: + print(f"{item:10}", end="\t") + print("") + + +def thanks(pb): + + writeFile(pb) + + # A simple gesture of courtesy towards the user to enhance user experience + print("********************************************************************") + print("Thank you for using our Smartphone directory system.") + print("Please visit again!") + print("********************************************************************") + sys.exit("Goodbye, have a nice day ahead!") + + +# Main function code +print("....................................................................") +print("Hello dear user, welcome to our smartphone directory system") +print("You may now proceed to explore this directory") +print("....................................................................") +# This is solely meant for decoration purpose only. +# You're free to modify your interface as per your will to make it look interactive + +ch = 1 +pb = initial_phonebook() +while ch in (1, 2, 3, 4, 5): + ch = menu() + if ch == 1: + pb = add_contact(pb) + elif ch == 2: + pb = remove_existing(pb) + elif ch == 3: + pb = delete_all(pb) + elif ch == 4: + d = search_existing(pb) + if d == -1: + print("The contact does not exist. Please try again") + elif ch == 5: + display_all(pb) + else: + thanks(pb) diff --git a/records.txt b/records.txt new file mode 100644 index 0000000..ceaf4ed --- /dev/null +++ b/records.txt @@ -0,0 +1,3 @@ +cyrus,7176218917,egg@gmail.com,4/4/412,fam +smoeone,7175898745,someone@gmail.com,7/12/2024,family +Tom,7175898653,tjhart@stevenscollege.edu,12/5/2003,friends diff --git a/scratch.py b/scratch.py new file mode 100644 index 0000000..e69de29