# Pavan Kumpatla
# December 26 (Edited at December 27)
# This is Mod 10 Lab
# Had difficulties with the last few tasks
# %cd command_line
# Note:
#Above was the original code given by Microsoft.
# This will work the first time, but if you re-run these cells
# you may encounter errors so we changed it to...
# ************** DO NOT MODIFY OR ADD ANYTHING TO THIS CODE SEGMENT ***********
# ************** Click Edit> Clear All Outputs ***********
# ************** This code segment must be run before attempting any of the tasks or examples in this lesson ********************
# ************** This cell is a reset cell to remove (if they exist) the parent_dir and any children or leaves
# It prepares the directories and files necessary to run the examples and complete the tasks.
# This cell can be run first then all others cells in this notebook can be run, then this cell can be rerun
# This is the reset. It uses the import shutil (or shell utility) which you will learn later in the course
import os, shutil # shutil = shell utility has an important method called rmtree()
# linux does not have an equivalent command!
# Navigate to `library` directory (if not already in it)
current_path = os.getcwd()
print(current_path)
if ("content" in current_path):
#JGif ("library" in current_path):
nb_path = current_path.split("content")[0] # nb_path = the 1st item in the split list
else:
nb_path = current_path
print("Changing working dir to directory above parent_dir")
os.chdir(os.path.join(nb_path,"content"))
current_path = os.getcwd()
print("Current working directory:", current_path)
if (os.path.exists('parent_dir') == True):
shutil.rmtree('parent_dir')
os.mkdir('parent_dir')
os.chdir('parent_dir')
os.mkdir('child1_dir')
os.chdir('../')
current_path = os.getcwd()
print("Current working directory:", current_path)#
%mkdir command_line
%cd command_line
!pwd
# [ ] Write an expression to raise a `SyntaxError` exception
print(Hi, my name is Pavan!)
# error
# [ ] Write an expression to raise a `TypeError` exception
error = "I am" / "Pavan!"
# error
## [ ] The following program divides the elements of `lst` by a float number `x` specified by the user
# Use exception handling to correct for the ALL generated exceptions
# When you handle all exceptions correctly, you should see the word "Done!" in the program output
# HINT: You might need to use 2 `try..except` statements
# Test cases:
# x = 5
# x = 6.3
# x = "number"
# x = 0
lst = [8, 85.4, [55, 4], 'word', (59,), {2:43.5}]
# list
try:
# try
x = input("Enter a number: ")
# stores user input
x = float(x)
# converts to float form
for i in range(7):
# for i range of 7
print("{} / {:.2f} = {:.2f}".format(lst[i], x, lst[i] / x))
# prints
except TypeError:
# except error
print("Error: Not in Float/Integer Form!")
# prints this instead
except ZeroDivisionError:
# excepts error
print("Error: Cannot divide by 0")
# prints this instead
except ValueError:
# excepts error
print("Error: Cannot Convert String to Float Form")
# prints this instead
print("Done!")
# prints
# [ ] The following program asks the user for a file name.
# The file is then opened, the first line printed out, then closed.
# Use exception handling to show the user a message confirming the file process was completed successfully
# your exception handling should also deal with the cases when the file does not exist
# test cases:
# fname = text_file.txt (should display: File process was completed successfully)
# fname = nofilehere.txt (should display: nofilehere.txt was not found)
import os
# imports
# ask user for a file name
fname = input("Enter file name: ")
# stores user input
# the file should be located in `parent_dir`
fname = os.path.join("parent_dir", fname)
# joins path
try:
# try
# opening text_file.txt for reading
f = open(fname, 'r')
# opens in read
print(f.readline())
# reads lines, prints
f.close()
# closes
except FileNotFoundError:
# excepts error
print("{} not found".format(fname))
# prints, formats
else:
# else
print("{} was completed successfully".format(fname))
# prints, formats
# [ ] The following program tries to read from a file opened for writing.
# The program will terminate before closing the file, and the file resources will not be released.
# Use exception handling with a `finally` to make sure the file is closed
# Open a text file for writing
# trying to read from a file open for writing (will raise an exception)
# closing the file (will not be reached if an exception was raised)
# --> Moved the instructions up <--
try:
# try
f = open("parent_dir/text_file_2.txt", 'w')
# opens file in write mode
print(f.readline())
# reads line - error
except FileNotFoundError:
# excepts error
print("Error: File not Found")
# print
finally:
# finally
f.close() # This code is supposed to work
# close file
print("File closed")
# prints
# It says error which is really annoying since I'm using deepnote.
# I'm pretty sure this code works in Colab since "parent_dir"
# is in Colab
# [ ] Write a program to keep prompting the user for a number from a predefined numerical tuple `valid_nums`
# Your program should raise an exception with an appropriate message if the input is not valid
valid_nums = (1, 2, 8, 16, 32, 64)
# stores in tuple
while True:
# while True
try:
# try
num = int(input("Guess The Number:- "))
# stores user input in int form
except Exception as exception_object:
# excepts error
print(exception_object) # ---------------> I just went the easy way...
# prints
else:
# else
if num in valid_nums:
# if num is in valid_nums
print("Well Done! You Have Guessed A Number")
# prints
break
# break
else:
# else
print("Your Number Is Not Valid --> Try Again")
# prints
# ************** DO NOT MODIFY OR ADD ANYTHING TO THIS CODE SEGMENT ***********
# ************** Click Edit> Clear All Outputs ***********
# ************** This code segment must be run before attempting any of the tasks or examples in this lesson ********************
# ************** This cell is a reset cell to remove (if they exist) the parent_dir and any children or leaves
# It prepares the directories and files necessary to run the examples and complete the tasks.
# This cell can be run first then all others cells in this notebook can be run, then this cell can be rerun
# This is the reset. It uses the import shutil (or shell utility) which you will learn later in the course
import os, shutil # shutil = shell utility has an important method called rmtree()
# linux does not have an equivalent command!
# Navigate to `library` directory (if not already in it)
current_path = os.getcwd()
print(current_path)
if ("content" in current_path):
#JGif ("library" in current_path):
nb_path = current_path.split("content")[0] # nb_path = the 1st item in the split list
else:
nb_path = current_path
print("Changing working dir to directory above parent_dir")
os.chdir(os.path.join(nb_path,"content"))
current_path = os.getcwd()
print("Current working directory:", current_path)
if (os.path.exists('parent_dir') == True):
shutil.rmtree('parent_dir')
os.mkdir('parent_dir')
os.chdir('parent_dir')
os.mkdir('child1_dir')
os.chdir('../')
current_path = os.getcwd()
print("Current working directory:", current_path)
# ************ DO NOT MODIFY OR ADD ANYTHING TO THIS CODE CELL ***********************
# ++++++++++++ This code segment must be run before attempting any of the tasks in this task 4.
# It prepares the directories and files necessary to complete the tasks.
import os, random, shutil
# Navigate to `parent_dir` directory (if not already in it)
current_path = os.getcwd()
if ("parent_dir" in current_path):
nb_path = current_path.split("parent_dir")[0]
else:
nb_path = current_path
print("Changing working dir to parent_dir")
os.chdir(os.path.join(nb_path,'parent_dir'))
print("Current working directory:", os.getcwd())
# Remove the `files_exercises` directory (if it exists)
if('files_exercises' in os.listdir()):
print('Removing "files_exercises"')
shutil.rmtree('files_exercises')
# Create a new directory called `files_exercises`
print('Making "files_exercises"')
os.mkdir('files_exercises')
# Change the working directory to `files_exercises`
print('Changing working directory to "files_exercises"')
os.chdir('files_exercises')
# Display the current working directory to verify you are in the correct location
print("Current working directory:", os.getcwd())
# Create 100 text files, the first line of each file is a random number in the range [1000, 9999]
print("Creating 100 text files")
random.seed(25000) # to get the same random numbers every time the setup runs
for i in range(100):
file_name = str(i) + ".txt"
f = open(file_name, 'w')
f.write(str(random.randint(1000, 9999)))
f.close()
# Create 5 directories
print("Creating 5 directories")
for i in range(1, 6):
os.mkdir("dir_"+str(i))
print("Environment setup completed!")
# [ ] Complete the function `delete_files` so the program deletes all the files in the `files_exercises` directory
# Make sure the to run the environment setup code before running your own program.
# NOTE:---->>>>>> DO NOT RUN THIS CODE!!!
# Everytime I run this code, the whole file just deletes itself.
# So do not run this since this file be deleted.
# I realized why it kept deleting after I redid this part 5 times sadly.
import os
# imports
def delete_files(to_be_deleted):
# creates new function with parameter
for x in to_be_deleted:
# for x in to_be_deleted
if os.path.isfile(x):
# if the path is a file
os.remove(x)
# remove it
# list the content of `files_exercises`
print('Content of "files_exercises" before removing the files')
print(os.listdir())
# Delete all files in `files_exercises`
delete_files(os.listdir())
# list the content of `files_exercises`
print('Content of "files_exercises" after removing the files')
print(os.listdir())
# [ ] The following program is designed to remove all files in `files_exercises` that contain a number divisible by 3 on the first line.
# To complete the program, you need to:
# 1) complete the function `delete_files` as you did in a previous exercise
# 2) iterate over all content in `file_exercises`:
# 2.1) if an element in the directory is a file open it for reading using `with` statement
# 2.2) read the first line in the file
# 2.3) if the first line contains a number divisible by 3, add the file name to the `to_be_deleted` list
# 2.4) your code should handle exception appropriately (i.e. a blank file or a file containing a string in the first line)
# 3) make sure the to run the environment setup code before running your own program.
# The output of your program should look like:
'''
Unexpected error found in 49.txt: invalid literal for int() with base 10: ''
Deleting matching files:
------------------------------
Removing 15.txt
Removing 16.txt
Removing 18.txt
Removing 19.txt
Removing 20.txt
Removing 23.txt
Removing 28.txt
Removing 35.txt
Removing 39.txt
Removing 40.txt
Removing 44.txt
Removing 46.txt
Removing 5.txt
Removing 51.txt
Removing 52.txt
Removing 54.txt
Removing 55.txt
Removing 58.txt
Removing 59.txt
Removing 65.txt
Removing 67.txt
Removing 68.txt
Removing 69.txt
Removing 71.txt
Removing 73.txt
Removing 77.txt
Removing 80.txt
Removing 81.txt
Removing 85.txt
Removing 87.txt
Removing 91.txt
Removing 94.txt
Removing 95.txt
Removing 96.txt
'''
import os
# imports
# list the content of `files_exercises`
print('Content of "files_exercises" before removing the files')
print(os.listdir())
print(30 * "-")
# clearing (49.txt) so an exception is raised below as a result of int( )
# opening a file without doing anything clears it!
with open('49.txt', 'w') as file: pass
to_be_deleted = []
#TODO: iterate over directory content and store file names containing numbers divisible by 3 in `to_be_deleted` list
def delete_files(to_be_deleted):
# creates new function with parameter
for x in os.listdir():
# for every value in the directory
y = x.replace(".txt", "")
# replace
try:
y = int(y)
# converts y to int form
except Exception as exception_object:
print("Error!")
pass
if os.path.isfile(x) and y % 3:
# if the path is a file
print("Removing", x)
# prints
os.remove(x)
# remove it
print()
print("Deleting matching files:")
print(30 * "-")
delete_files(to_be_deleted)
# It won't work....
# [ ] Write a program to:
# 1) ask the user for a number between 1000 and 9999
# 2) test if the number matches the first line of any file in `files_directory`
# 3) if a match was found, print the file name; otherwise, print no match is found
# 4) your code should handle exception appropriately (i.e. a blank file or a file containing a string in the first line)
# 5) you should use `with` statement for opening/closing files
# 6) make sure the to run the environment setup code before running your own program.
# test cases:
# 3932, should print out: Match found in 74.txt : 3932
# 2177, should print out: Match found in 27.txt : 2177
# 4932, should print out: No matching files found
import os
# imports
while True:
# while True
while True:
# while True
try:
# try
user = input("Enter A Number Between 1000-9999")
# stores user input not in int form since it can cause error
except Exception as exception_object:
# excepts error
print(exception_object)
# prints
if type(user) == int:
# if the type of user is int
break
# break
if user >= 1000 and user <= 9999:
# if user is greater than or equal to 1000 and lesser than or equal to 9999
break
# break
else:
# else
print("Error: Invalid Number!")
# print this
break
for user in os.listdir():
# for every item in the directory (listed)
if os.path.isfile(user):
# if the path is a file
with open(user) as file1:
# open the item as file1
line = file1.readline()
# read line and store
line = int(line)
# convert line to int
if user == line:
# if user equals line
print("Match Found in", user)
# print this
break
# THE CODE DOES WORK! -> But it doesn't work here...
# [ ] The tuples `x` and `y` contain the (x, y) coordinates of 10 points.
# Write a program to create a single tuple `coordinates` that contains 10 sub-tuples of the (x, y) coordinates
# The final tuple should look like:
# ((75, 57), (77, 6), (55, 64), (93, 36), (41, 63), (62, 53), (70, 26), (30, 71), (74, 88), (97, 66))
x = (75, 77, 55, 93, 41, 62, 70, 30, 74, 97)
y = (57, 6, 64, 36, 63, 53, 26, 71, 88, 66)
list1 = []
# empty list
increase = 0
# stores 0
for num in x:
# for num in x
list1.append((num, y[increase]))
# append num and the index (increase) of y to list1
increase += 1
# add 1 to increase
list1 = tuple(list1)
# convert to tuple
print(list1)
# prints
# [ ] Write a program to merge the two sorted tuples T1, T2 into a larger (also sorted) tuple T
# Output should be:
#Merged sorted tuple:
#(12, 13, 15, 20, 20, 26, 30, 37, 40, 55, 60, 68, 72, 78, 81, 84, 89, 97, 97, 100)
# sorted tuples
T1 = (15, 20, 30, 37, 55, 60, 78, 81, 84, 100)
T2 = (12, 13, 20, 26, 40, 68, 72, 89, 97, 97)
# stores in tuple
T3 = T1 + T2
# adds
T3 = sorted(T3)
# sorts
T3 = tuple(T3)
# converts to tuple
print(T3)
# prints
# [ ] Complete the function `simple_stats` so it returns:
# 1) The maximum number in the tuple T
# 2) The minimum number in the tuple T
# 3) The average of the numbers in the tuple T
def simple_stats(T):
# creates new function with parameter
t1 = 0
# stores 0
t2 = 0
# stores 0
T = sorted(T)
# sorts, stores
smallest = T[-1]
# stores the last
largest = T[0]
# stores the first
for x in T:
# for x in T
t1 =+ x
# add x to total
t2 += 1
# add 1 to t2
average = t1/t2
# divides, stores
return smallest, largest, average
# returns
T = (257, 462, 18, 369, 415, 994, 541, 752, 78, 895, 0, 576, 40, 552, 438, 605, 54, 296, 433, 986, 685, 651, 523, 855, 777, 437, 65, 360, 265, 858, 260, 819, 586, 358, 860, 250, 531, 7, 801, 259, 155, 376, 374, 828, 475, 62, 52, 184, 186, 283, 643, 86, 472, 267, 692, 750, 948, 683, 452, 770, 322, 492, 871, 360, 88, 883, 764, 288, 383, 411, 679, 90, 857, 802, 974, 403, 798, 990, 475, 260, 289, 438, 873, 779, 895, 939, 462, 469, 183, 520, 366, 267, 896, 732, 303, 754, 195, 949, 546, 180)
# unpacking and displaying the returned values
largest, smallest, average = simple_stats(T)
print("Maximum number in T:", largest)
print("Minimum number in T:", smallest)
print("Average of numbers in T:", average)
# [ ] Complete the function `longer` to compare and return the longest of 2 tuples
def longer(T1, T2):
# creates new function with 2 parameters
length1 = len(T1)
# stores length
length2 = len(T2)
# stores length
if length1 > length2:
# if length1 is greater than length2
return T1
# returns
else:
# else
return T2
# returns
T1 = (98, 84, 71, 87, 54, 16, 70, 62, 1, 29, 66, 1, 74, 71, 68, 58, 65, 75, 74, 77, 94, 19, 46)
T2 = (62, 30, 58, 75, 0, 61, 37, 93, 40, 33, 93, 94, 72, 27, 92, 75, 38, 70, 99, 74, 89, 8, 42, 32, 4, 60, 5)
print("The longer tuple is:")
print(longer(T1, T2))
# [ ] Complete the function `search` so it looks for the first instance of `num` in `T`
# The function should return 2 values:
# 1) Boolean value indicating if num was found or not
# 2) Index of the first instance of `num` in `T`
def search(T, num):
"""
Search T for num and return the index if found; otherwise return None.
args:
T: Tuple to be searched
num: number to use for the search
returns:
found: Boolean value to indicate if the num is contained in T or not
i: If num is found in T return index of the first instance of num in T; otherwise, return the value `None`
"""
list1 = list(T)
# had to do this first to get the list
if num in list1:
# if num is in list1
i = list1.index(num)
# store the index of num
found = True
# set found to True
return found, i
# order matters here!
T = (257, 462, 18, 369, 415, 994, 541, 752, 78, 895, 0, 576, 40, 552, 438, 605, 54, 296, 433, 986, 685, 651, 523, 855, 777, 437, 65, 360, 265, 858, 260, 819, 586, 358, 860, 250, 531, 7, 801, 259, 155, 376, 374, 828, 475, 62, 52, 184, 186, 283, 643, 86, 472, 267, 692, 750, 948, 683, 452, 770, 322, 492, 871, 360, 88, 883, 764, 288, 383, 411, 679, 90, 857, 802, 974, 403, 798, 990, 475, 260, 289, 438, 873, 779, 895, 939, 462, 469, 183, 520, 366, 267, 896, 732, 303, 754, 195, 949, 546, 180)
x = int(input("Enter a number to search for in T: "))
# unpacking returned tuple
found, i = search(T, x)
if found:
print("First instance found at index {:}".format(i))
else:
print("{} was not found in T".format(x))
# [ ] Complete the functions `search` and `split` to slice a tuple `T` around a number `num`
# The function should use the `search` function you developed in a previous exercise to find its index in `T`
# If `num` is in T, you discard it and return two tuples:
# 1) from the beginning of T till index of num
# 2) from index+1 of num till the end of T
# If `num` is not in T, you return:
# 1) The whole Tuple
# 2) The `None` value
# Example input/output using T = (15, 20, 30, 37, 55, 60, 78, 81, 84, 100):
#Enter a number around which you want to split T: 55
#T1 = (15, 20, 30, 37)
#T2 = (60, 78, 81, 84, 100)
#Enter a number to search for in T: 400
#T1 = (15, 20, 30, 37, 55, 60, 78, 81, 84, 100)
#T2 = None
def search(T, num):
"""
Search T for num and return the index if found; otherwise return None.
args:
T: Tuple to be searched
num: number to use for the search
returns:
found: Boolean value to indicate if the num is contained in T or not
i: If num is found in T return index of the first instance of num in T; otherwise, return the value `None`
"""
list1 = list(T)
# had to do this first to get the list
if num in list1:
# if num is in list1
i = list1.index(num)
# store the index of num
found = True
# set found to True
return found, i
# order matters here!
def split(T, num):
"""
Split the tuple T around num (num should be discarded).
args:
T: Tuple to be searched
num: number to use for the split
returns:
T1: The first half of the tuple, from the beginning till num ( excluded).
If num is not in T, T1 should be the whole tuple T
T2: The second half of the tuple, from num (excluded) till the end.
If num is not in T, T2 should be the value `None`
"""
list1 = list(T)
# converts to list
index1 = list1.index(num)
# stores index
index2 = index1 - 1
# subtracts the index by 1
index3 = index1 + 1
# adds the index by 1
T1 = list1[:index2]
# splits, stores
T2 = list1[index3:]
# splits, stores
return T1, T2
# returns
T = (15, 20, 30, 37, 55, 60, 78, 81, 84, 100)
x = int(input("Enter a number around which you want to split T: "))
# unpacking returned tuple
T1, T2 = split(T, x)
print("T1 =", T1)
print("T2 =", T2)
# [ ] The `data` list contains grocery store inventory information, the list is organized into sublists where each of
# the sublists contains: [UPC, Description, Unit Price, Quantity in Stock]
# Use the `data` list to create an inventory dictionary with the UPC as keys and lists containing [Description, Item Price, Quantity in Stock] as values:
# UPC (as keys): [Description, Unit Price, Quantity in Stock] (as values)
# NOTE: UPC is short for (Universal Product Code), which is the number found under a barcode and identify different products in a store
# The created dictionary should look like:
# {847502: ['APPLES 1LB', 1.99, 50], 847283: ['OLIVE OIL', 10.99, 100], 839529: ['TOMATOS 1LB', 1.29, 25], 483946: ['MILK 1/2G', 3.45, 35], 493402: ['FLOUR 5LB', 2.99, 40], 485034: ['BELL PEPPERS 1LB', 1.35, 28], 828391: ['WHITE TUNA', 1.69, 100], 449023: ['CHEESE 1/2LB', 4.99, 15]}
data = [[847502, "APPLES 1LB", 1.99, 50], [847283, "OLIVE OIL", 10.99, 100], [839529, "TOMATOS 1LB", 1.29, 25], [483946, "MILK 1/2G", 3.45, 35], [493402, "FLOUR 5LB", 2.99, 40], [485034, "BELL PEPPERS 1LB", 1.35, 28], [828391, "WHITE TUNA", 1.69, 100], [449023, "CHEESE 1/2LB", 4.99, 15]]
#TODO: Your code goes here
list1 = []
for item in data:
# for item in data
UPC = item[0]
# stores index 0
list2 = item[1:3]
# stores index 1-3
list1.append(UPC)
# appends
list1.append(list2)
# appends
d = tuple(list1)
# converts to tuple (Idk how to do dictionary)
print(d)
# prints
# [ ] Use the `inventory` dictionary in a program that asks the user for a UPC number then prints the item information
# Your program should print an appropriate message if the UPC is not in the inventory
# test cases:
# input 1: 847283
# output:
'''
UPC | Description | Unit Price | Quantity
-------------------------------------------------------
847283 | OLIVE OIL | 10.99 | 100.00
'''
# input 2: 340344
# output: No inventory found for 340344
inventory = {847502: ['APPLES 1LB', 1.99, 50], 847283: ['OLIVE OIL', 10.99, 100], 839529: ['TOMATOS 1LB', 1.29, 25], 483946: ['MILK 1/2G', 3.45, 35], 493402: ['FLOUR 5LB', 2.99, 40], 485034: ['BELL PEPPERS 1LB', 1.35, 28], 828391: ['WHITE TUNA', 1.69, 100], 449023: ['CHEESE 1/2LB', 4.99, 15]}
#TODO: Your code goes here
user = int(input("Type in UPC:- "))
# stores user input in int form
if user in inventory.keys():
# if user is in inventory for keys
list1 = inventory[user]
# stores the index of user in inventory
print("UPC:-",user, "Item:-", list1[0], "Unit Price:-", list1[1], "Quantity:-", list1[2]"")
# prints
else:
# else
print("Not found")
# prints
# [ ] Use the `inventory` dictionary in a program that asks the user for a UPC number, description, unit price,
# quantity in stock.
# If the item already exists in the inventory, the information is updated,
# and your program should display a message that it is updating the entry.
# If the item does NOT exists in the inventory, a new dictionary entry is created,
# and your program should display a message that it is creating a new entry.
# Use try/except in the program.
# test cases
# For an existing item
'''
Enter UPC number: 839529
Enter item description: TOMATOS 1LB
Enter unit price: 1.55
Enter item quantity: 21
Existing item, updating: ['TOMATOS 1LB', 1.29, 25]
UPC | Description | Unit Price | Quantity
-------------------------------------------------------
839529 | TOMATOS 1LB | 1.55 | 21.00
'''
# For a new item
'''
Enter UPC number: 29430
Enter item description: ORANGE 1LB
Enter unit price: 0.99
Enter item quantity: 40
New item, creating ORANGE 1LB
UPC | Description | Unit Price | Quantity
-------------------------------------------------------
29430 | ORANGE 1LB | 0.99 | 40.00
'''
inventory = {847502: ['APPLES 1LB', 1.99, 50], 847283: ['OLIVE OIL', 10.99, 100], 839529: ['TOMATOS 1LB', 1.29, 25], 483946: ['MILK 1/2G', 3.45, 35], 493402: ['FLOUR 5LB', 2.99, 40], 485034: ['BELL PEPPERS 1LB', 1.35, 28], 828391: ['WHITE TUNA', 1.69, 100], 449023: ['CHEESE 1/2LB', 4.99, 15]}
#TODO: Your code goes here
UPC = int(input("Enter UPC number: "))
# stores user input
Item_Des = input("Enter item description: ")
# stores user input
Unit_Price = float(input("Enter unit price:"))
# stores user input
Item_Quan = int(input("Enter item quantity:"))
# stores user input
if UPC not in inventory.keys():
# if UPC is not in the keys of inventory
inventory[UPC] = [Item_Des, Unit_Price, Item_Quan]
# replaces/updates
elif UPC in inventory.keys():
# if UPC is in the keys of inventory
inventory[UPC] = [Item_Des, Unit_Price, Item_Quan]
# replaces/updates
print(inventory)
# prints
# [ ] Write a program to display the current inventory information as follow
# Note the items are sorted by UPC
'''
UPC | Description | Unit Price | Quantity
-------------------------------------------------------
449023 | CHEESE 1/2LB | 4.99 | 15.00
483946 | MILK 1/2G | 3.45 | 35.00
485034 | BELL PEPPERS 1LB | 1.35 | 28.00
493402 | FLOUR 5LB | 2.99 | 40.00
828391 | WHITE TUNA | 1.69 | 100.00
839529 | TOMATOS 1LB | 1.29 | 25.00
847283 | OLIVE OIL | 10.99 | 100.00
847502 | APPLES 1LB | 1.99 | 50.00
'''
inventory = {847502: ['APPLES 1LB', 1.99, 50], 847283: ['OLIVE OIL', 10.99, 100], 839529: ['TOMATOS 1LB', 1.29, 25], 483946: ['MILK 1/2G', 3.45, 35], 493402: ['FLOUR 5LB', 2.99, 40], 485034: ['BELL PEPPERS 1LB', 1.35, 28], 828391: ['WHITE TUNA', 1.69, 100], 449023: ['CHEESE 1/2LB', 4.99, 15]}
print("{:^7s} | {:<18s} | {:<12s} | {:<10s}".format("UPC", "Description", "Unit Price", "Quantity"))
print("-"*55)
for key in sorted(inventory.keys()):
values = inventory[key]
print("{:<7d} | {:<18s} | {:>12.2f} | {:>10.2f}".format(key, values[0], values[1], values[2]))
# I think I need help in understanding this (I had help)
# [ ] Write a program to calculate and display the total value and the number of items in an inventory.
# The total value can by calculated by multiplying each unit price by the quantity,
# then adding up the answers for all items in the inventory.
inventory = {847502: ['APPLES 1LB', 1.99, 50], 847283: ['OLIVE OIL', 10.99, 100], 839529: ['TOMATOS 1LB', 1.29, 25], 483946: ['MILK 1/2G', 3.45, 35], 493402: ['FLOUR 5LB', 2.99, 40], 485034: ['BELL PEPPERS 1LB', 1.35, 28], 828391: ['WHITE TUNA', 1.69, 100], 449023: ['CHEESE 1/2LB', 4.99, 15]}
# stores in dict
item_count = 0
# stores
total_val = 0.0
# stores
for key in inventory.keys():
# for key in inventory of keys
item_count += 1
# add 1 to item_count
values = inventory[key]
# stores the index of key in inventory
total_val += values[1] * values[2]
# adds the multiplication
print("total value: ", total_val)
print("item counts: ", item_count)
# prints