In: Computer Science
#Problem 2
Write function write_stock that asks the user to input a company name, its associated ticker symbol (eg. Exxon, XOM), and the price per share of the stock. These are then written to file stock.txt one item per line. The user will type in ‘quit’ to stop.
Write function get_share_value that accepts a company name and the number of shares. The function will search file stock.txt and return a list of two values; the ticker symbol and the total value of the shares. This function must use an exception handler to insure the file is valid, that the price can be converted to a number, and catch any other exception that might be raised.
Write a program that calls write_stock and get_share_value. The program will ask the user for the company name and number of shares for read_stock and print the answer.
Sample output might look as follows.
Enter company name; enter quit to stop: Amazon
Enter ticker symbol: amzn
Enter price: 1000
Enter company name; enter quit to stop: Apple
Enter ticker symbol: aapl
Enter price: 125
Enter company name; enter quit to stop: Microsoft
Enter ticker symbol: msft
Enter price: 250
Enter company name; enter quit to stop: quit
What stock did you buy?: Apple
How many shares?: 10
Your total value for aapl is $1250.00
PYTHON CODE
Below is the python solution with output screenshot
Code :
def write_stock():
f = open("stock.txt", 'a')
while(True):
company = input("Enter company name; enter quit to stop: ")
if(company == 'quit' or company == 'QUIT'):
break
else:
symbol = input("Enter ticker symbol: ")
price = input("Enter price: ")
f.write(company+'\n')
f.write(symbol+'\n')
f.write(price+'\n')
def get_share_value ():
company = input("What stock did you buy?: ")
shares = input("How many shares?: ")
try:
f = open('stock.txt', 'r')
while True:
# Get next line from file
line = f.readline()
line = line.rstrip()
# if line is empty end of file is reached
if not line:
break
if(line == company):
symbol = f.readline()
symbol = symbol.rstrip()
price = f.readline()
price = price.rstrip()
try:
price = int(price)
shares = int(shares)
total_price = price*shares
except:
print("Error: invalid price value")
return [symbol, total_price]
except:
print("Some Error Occured")
exit()
if __name__ == "__main__":
write_stock()
data = get_share_value()
print('Your total value for', data[0], 'is $', round(data[1],2))
Output :
Note : for better understanding please refer to the code screenshot below