Question

I currently have a code that I have written that uses global variables. My professor wants...

I currently have a code that I have written that uses global variables. My professor wants me to rewrite this code so that it uses the return function instead. I dont understand why because it works the same, but I am not great at using return and barely understand it. here is my code. This is in Python3

#Created an empty dictionary using variable
#grocery_item
grocery_item = {}
#Created an empty list for using variable
#grocery_history
grocery_history = []

#This is the variable our loop is based off with the
#value 'go'
stop = 'go'
#Using a while loop to tell the computer
#that as long as the user does not enter 'q', the
#program will continue to iterate
while stop != 'q':
#Giving variables for items in list for user to input
item_name = input('item name:\n')
  
quantity=input("Quantity purchased:\n")
  
cost = input("Price per item:\n")
#modifying the dictionary by adding values to the keys   
grocery_item = {'name': item_name, 'number': int(quantity), 'price':float(cost)}
#Used the append method to add grocery_item to
#grocery_history list
grocery_history.append(grocery_item)
  
stop = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:\n")

#Variable for the grand total
grand_total=0
  
#Using a for loop to iterate over the grocery_item
# in grocery_history
for grocery_item in grocery_history:
  
  
#Here I access the values in the dictionary grocery_item
#by calling them in brackets. i.e ['number'] and ['price']
item_total = grocery_item['number'] * grocery_item['price']
  
grand_total += item_total
#modified values in the dictionary to show up as currency
#by using $%.2f and to moving the decimal to the right place.
print('%d %s @ $%.2f ea $%.2f' % (grocery_item['number'], grocery_item['name'],grocery_item['price'],item_total))
  
item_total = 0
#Print the grand total
(print('Grand total: $%.2f' % grand_total))

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE

=============

#Created an empty dictionary using variable

#grocery_item

grocery_item = {}

#Created an empty list for using variable

#grocery_history

grocery_history = []

def getGroceryTotalBill():

#This is the variable our loop is based off with the

#value 'go'

stop = 'go'

#Using a while loop to tell the computer

#that as long as the user does not enter 'q', the

#program will continue to iterate

while stop != 'q':

#Giving variables for items in list for user to input

item_name = input('item name: ')

quantity=input("Quantity purchased: ")

cost = input("Price per item: ")

#modifying the dictionary by adding values to the keys

grocery_item = {'name': item_name, 'number': int(quantity), 'price':float(cost)}

#Used the append method to add grocery_item to

#grocery_history list

grocery_history.append(grocery_item)

stop = input("Would you like to enter another item? Type 'c' for continue or 'q' to quit: ")

#Variable for the grand total

grand_total=0

#Using a for loop to iterate over the grocery_item

# in grocery_history

for grocery_item in grocery_history:

#Here I access the values in the dictionary grocery_item

#by calling them in brackets. i.e ['number'] and ['price']

item_total = grocery_item['number'] * grocery_item['price']

grand_total += item_total

#modified values in the dictionary to show up as currency

#by using $%.2f and to moving the decimal to the right place.

print('%d %s @ $%.2f ea $%.2f' % (grocery_item['number'], grocery_item['name'],grocery_item['price'],item_total))

item_total = 0

#return the grand total

return grand_total

if __name__ == "__main__":

(print('Grand total: $%.2f' % getGroceryTotalBill()))


Add a comment
Know the answer?
Add Answer to:
I currently have a code that I have written that uses global variables. My professor wants...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Zybooks 11.12 LAB*: Program: Online shopping cart (continued) Python 3 is the code needed and this...

    Zybooks 11.12 LAB*: Program: Online shopping cart (continued) Python 3 is the code needed and this is in Zybooks Existing Code # Type code for classes here class ItemToPurchase: def __init__(self, item_name="none", item_price=0, item_quantity=0): self.item_name = item_name self.item_price = item_price self.item_quantity = item_quantity # def __mul__(self): # print_item_cost = (self.item_quantity * self.item_price) # return '{} {} @ ${} = ${}' .format(self_item_name, self.item_quantity, self.item_price, print_item_cost) def print_item_cost(self): self.print_cost = (self.item_quantity * self.item_price) print(('{} {} @ ${} = ${}') .format(self.item_name, self.item_quantity, self.item_price,...

  • the same problem: We picked the variable name user_dictionary because it will be a dictionary that...

    the same problem: We picked the variable name user_dictionary because it will be a dictionary that is created by a user. Other names could be appropriate as well! Though it may seem unnecessary, we'll add a print statement to remind ourself that user_dictionary is empty. Next we'll build up the for loop! Save & Run Load History Show CodeLens 1 # initialize a dictionary 2 user_dictionary - {} 3 print("--- keys in user_dictionary: " + str(list(user_dictionary.keys()) + 5 # write...

  • Could anyone help add to my python code? I now need to calculate the mean and...

    Could anyone help add to my python code? I now need to calculate the mean and median. In this programming assignment you are to extend the program you wrote for Number Stats to determine the median and mode of the numbers read from the file. You are to create a program called numstat2.py that reads a series of integer numbers from a file and determines and displays the following: The name of the file. The sum of the numbers. The...

  • Hi, can someone offer input on how to address these 4 remain parts the zybook python...

    Hi, can someone offer input on how to address these 4 remain parts the zybook python questions?   4: Tests that get_num_items_in_cart() returns 6 (ShoppingCart) Your output ADD ITEM TO CART Enter the item name: Traceback (most recent call last): File "zyLabsUnitTestRunner.py", line 10, in <module> passed = test_passed(test_passed_output_file) File "/home/runner/local/submission/unit_test_student_code/zyLabsUnitTest.py", line 8, in test_passed cart.add_item(item1) File "/home/runner/local/submission/unit_test_student_code/main.py", line 30, in add_item item_name = str(input('Enter the item name:\n')) EOFError: EOF when reading a line 5: Test that get_cost_of_cart() returns 10 (ShoppingCart)...

  • VERY URGENT*** THANK YOU IN ADVANCE: THIS IS THE CODE I HAVE GOTTEN SO FAR: PYTHON...

    VERY URGENT*** THANK YOU IN ADVANCE: THIS IS THE CODE I HAVE GOTTEN SO FAR: PYTHON This is a code that is supposed to help someone study/ practice for jeopardy. The two functions described below are required for this assignment. You may add other functions that you think are appropriate: menu() This function, which displays all the user options to the screen, prompt the user for their choice and returns their choice. This function will verify user input and ALWAYS...

  • This script will create a dictionary whose keys are all the directories listed in thePATH system...

    This script will create a dictionary whose keys are all the directories listed in thePATH system variable, and whose values are the number of files in each of these directories. The script will also print each directory entry sorted by directory name. The script will use the following five functions to get the required results get_environment_variable_value() get_dirs_from_path() get_file_count() get_file_count_for_dir_list() print_sorted_dictionary() get_environment_variable_value() The header for this function must be This function must accept a shell variable as its only parameter The...

  • how would i write my code in Pseudocode? I am pretty much a beginner, therefore this...

    how would i write my code in Pseudocode? I am pretty much a beginner, therefore this is my first major computer science assignment and im not really understanding the written way of code.. please help and explain. Thank you! this is my working code: # Guess The Number HW assignment import random guessesTaken = 0 names=[] tries=[] print("Welcome! ") question = input("Would you like to play the guessing game? [Y/N]") if question == "N": print("Sorry to see you go so...

  • Hello, I have some errors in my C++ code when I try to debug it. I...

    Hello, I have some errors in my C++ code when I try to debug it. I tried to follow the requirements stated below: Code: // Linked.h #ifndef INTLINKEDQUEUE #define INTLINKEDQUEUE #include <iostream> usingnamespace std; class IntLinkedQueue { private: struct Node { int data; Node *next; }; Node *front; // -> first item Node *rear; // -> last item Node *p; // traversal position Node *pp ; // previous position int size; // number of elements in the queue public: IntLinkedQueue();...

  • Below is my code please help me edit it so in the beginning it ask for Press any key to start Tas...

    below is my code please help me edit it so in the beginning it ask for Press any key to start Task n, where n is the task number (1, 2, or 3,4). I already wrote the code for the 4 task. Also please write it so when 1 code is finish running it return to the prompt where it ask to run another task #task 1 list1 = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','.',',','?'] morse = ['.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..','-----','.----','..---','...--','....-','.....','-....','--...','---..','----.','.-.-.-','--..--','..--..'] inp = input("Enter original text : ")...

  • Instructions: Written in English (Basic Language) Modify the Base Project Sample Code to create a database...

    Instructions: Written in English (Basic Language) Modify the Base Project Sample Code to create a database of your own design that includes at least four data fields. The overall design and format of your program is up to you. Your program should implement the following menu options – A. Add Item B. List All Items C. Quit Any data theme or motif is acceptable, provided your project has at least four data elements. Please make sure your data structure implements...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT