Question
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
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: ') 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 #Print the grand total (print('Grand total: $%.2f' % grand_total))
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access with AI-Powered Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started