0% found this document useful (0 votes)
5 views14 pages

Python 7a Notes - Updated 1

The document outlines the development of a Python program, FruitOrderCase.py, designed to help customers calculate the final price of their fruit orders. It details the use of a nested dictionary to store fruit prices and quantities, along with a step-by-step algorithm for user interaction and order processing. Additionally, it includes a classwork assignment to enhance the program by adding input validation for user responses.

Uploaded by

gigicho0815
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views14 pages

Python 7a Notes - Updated 1

The document outlines the development of a Python program, FruitOrderCase.py, designed to help customers calculate the final price of their fruit orders. It details the use of a nested dictionary to store fruit prices and quantities, along with a step-by-step algorithm for user interaction and order processing. Additionally, it includes a classwork assignment to enhance the program by adding input validation for user responses.

Uploaded by

gigicho0815
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

P.

1 of 14

Contents

Example of Nested Dictionary........................................................................................ 2


Case of Tracking Fruit Order................................................................................... 2
Algorithmn for FruitOrderCase.py ................................................................. 5
Code listing of FruitOrderCase.py .................................................................. 6
Elaboration of FruitOrderCase.py .......................................................... 8
Classwork 1 .................................................................................................. 14
P. 2 of 14

Example of Nested Dictionary


Case of Tracking Fruit Order
Try to build up a Python program (FruitOrderCase.py) which can help the customer
to calculate the final price he/she has to pay after selecting the fruits. The possible
output of the program is shown below.

The system will first ask user to input the price of each fruit. Thereafter, the system
will display the list on screen for reference:
P. 3 of 14

The next step is user being asked to input the fruit he/she prefers to buy and the
amount would like to buy. See the screen capture below for your reference:
P. 4 of 14

By the time user chooses No for indication of stop buying, the system should show
out the order list and calculate the subtotal and total prices.
P. 5 of 14

Algorithmn for FruitOrderCase.py


Before we start writing the program, we have to think of the solution or method to
store up the price and order of each kind of fruit. This is also the core aspect of this
program.

As there are 4 kinds of fruits appear in the program, it’s easy to figure out a specific
data structure should be used within the program. In such case, we may consider to
use list or dictionary.

For the current case, dictionary will be more preferable as we can set each fruit
name as the key of the dictionary. For each value of each item in dictionary, we can
put a nested dictionary so that it can set price and order as the keys. This is what we
usually describe as nested dictionary.

Take a look at the diagram below for further elaboration on the structure of
fruitList dictionary:

Apple Banana Orange GrapeFruit


price order price order price order price order
P. 6 of 14

Code listing of FruitOrderCase.py

fruitList = ["BANANA", "APPLE", "ORANGE", "GRAPEFRUIT"]

fruitList.sort()

fruitDict = {}

for f in fruitList:
tempString = "What is the price of " + f + "? "
price = int(input(tempString))
order = 0
innerDict = {}
innerDict["price"]=price
innerDict["order"]=order
fruitDict[f]=innerDict

#print(innerDict)

#print(fruitDict)

print("\nThis is the price list:")

for k,v in sorted(fruitDict.items(), reverse = False):


tempPrice = v.get("price")
print("%s costs $%d" %(k, tempPrice))
#print(tempPrice)

flag = True

while flag:
fruitName = input('\nWhat fruit do you want to buy? ').upper()
numOrder = int(input('How many %s do you want to buy? ' %fruitName))

tempDict = fruitDict.get(fruitName)
P. 7 of 14

tempDict["order"] = tempDict.get("order") + numOrder

if tempDict.get("order") > 1:
print('You want to buy %d %sS' %(tempDict.get("order"), fruitName))
else :
print('You want to buy %d %s' %(tempDict.get("order"), fruitName))

cont = input('\nDo you want to buy more (Yes / No) ? ' ).upper()

if cont =="YES":
print("\n-------------------------------------------")
else:
flag = False

else:
print("\n\nThis is your oder:")
total=0
for kk,vv in sorted(fruitDict.items(), reverse = False):
tempOrder = vv.get("order")
print("%s: %d" %(kk, tempOrder))
subTotal = vv.get("order") * vv.get("price")
print("EachPrice: $%d" %vv.get("price"))
print("Subtotal: $%d" %subTotal)
total = total + subTotal
print()
else:
print('==============================================')
print ("Total amount is $%d " %total)

ch = input("")
P. 8 of 14

Elaboration of FruitOrderCase.py

Here’s a detailed explanation of FruitOrderCase.py:

1. Initialization of fruitList
fruitList = ["BANANA", "APPLE", "ORANGE", "GRAPEFRUIT"]
fruitList.sort()

➢ A list of fruits (fruitList) is defined and sorted alphabetically using


the .sort() method.
✓ After sorting, fruitList becomes:

['APPLE', 'BANANA', 'GRAPEFRUIT', 'ORANGE'].

2. Populating fruitDict
fruitDict = {}

for f in fruitList:
tempString = "What is the price of " + f + "? "
price = int(input(tempString))
order = 0
innerDict = {}
innerDict["price"] = price
innerDict["order"] = order
fruitDict[f] = innerDict

➢ An empty dictionary called fruitDict is created to store the fruit details.


➢ The program iterates over each fruit in fruitList. For each fruit:
1. It asks the user for the price of the fruit (price).
2. It initializes an innerDict with two keys:
✓ "price": Stores the price of the fruit as entered by the user.
✓ "order": Initialized to 0, representing the quantity ordered.
3. This innerDict is then assigned to the corresponding fruit key in
fruitDict.
P. 9 of 14

Example Input:
If the user provides these prices:
➢ APPLE: $2
➢ BANANA: $1
➢ GRAPEFRUIT: $3
➢ ORANGE: $2

fruitDict will look like this:

fruitDict = {
"APPLE": {"price": 2, "order": 0},
"BANANA": {"price": 1, "order": 0},
"GRAPEFRUIT": {"price": 3, "order": 0},
"ORANGE": {"price": 2, "order": 0}
}

3. Displaying the Price List


print("\nThis is the price list:")

for k, v in sorted(fruitDict.items(), reverse=False):


tempPrice = v.get("price")
print("%s costs $%d" % (k, tempPrice))

➢ The program displays the sorted price list of all fruits in ascending order of
their names (reverse=False).

➢ Example Output:

This is the price list:


APPLE costs $2
BANANA costs $1
GRAPEFRUIT costs $3
ORANGE costs $2
P. 10 of 14

4. Fruit Ordering Loop


flag = True

while flag:
fruitName = input('\nWhat fruit do you want to buy? ').upper()
numOrder = int(input('How many %s do you want to buy? ' % fruitName))

tempDict = fruitDict.get(fruitName)
tempDict["order"] = tempDict.get("order") + numOrder

➢ A while loop is used to keep the program running until the user decides to
stop ordering.
➢ Inside the loop:
1. The user is asked for the name of the fruit they want to buy. The input
is converted to uppercase for consistency.
2. The user is asked how many units of the fruit they want to order.
3. The order value in the corresponding fruit's dictionary (tempDict) is
updated by adding the ordered quantity (numOrder).

Example:
If the user orders 2 APPLES:

fruitDict = {
"APPLE": {"price": 2, "order": 2},
"BANANA": {"price": 1, "order": 0},
"GRAPEFRUIT": {"price": 3, "order": 0},
"ORANGE": {"price": 2, "order": 0}
}
P. 11 of 14

5. Display Order Summary


if tempDict.get("order") > 1:
print('You want to buy %d %sS' % (tempDict.get("order"), fruitName))
else:
print('You want to buy %d %s' % (tempDict.get("order"), fruitName))

➢ If the order value is greater than 1, the fruit name is pluralized by adding an
S.
➢ Otherwise, the singular form of the fruit name is displayed.

6. Continue or Stop Ordering


cont = input('\nDo you want to buy more (Yes / No) ? ').upper()

if cont == "YES":
print("\n-------------------------------------------")
else:
flag = False

➢ The user is asked whether they want to continue ordering.


➢ If they enter "YES", the loop continues.
➢ If they enter anything else (e.g., "NO"), the loop exits, and the program
moves to the order summary.
P. 12 of 14

7. Final Order Summary and Total Cost


print("\n\nThis is your order:")
total = 0

for kk, vv in sorted(fruitDict.items(), reverse=False):


tempOrder = vv.get("order")
print("%s: %d" % (kk, tempOrder))
subTotal = vv.get("order") * vv.get("price")
print("EachPrice: $%d" % vv.get("price"))
print("Subtotal: $%d" % subTotal)
total = total + subTotal
print()

➢ The program displays a summary of the user's orders, including:


✓ Fruit name and quantity ordered.
✓ Price per unit.
✓ Subtotal for each type of fruit.

➢ The total cost is calculated by summing up the subtotals of all fruits.

Example Output:
If the user orders:
➢ 2 APPLES
➢ 3 BANANAS

The output might look like:

This is your order:


APPLE: 2
EachPrice: $2
Subtotal: $4

BANANA: 3
EachPrice: $1
Subtotal: $3

GRAPEFRUIT: 0
EachPrice: $3
P. 13 of 14

Subtotal: $0

ORANGE: 0
EachPrice: $2
Subtotal: $0

==============================================
Total amount is $7
P. 14 of 14

Classwork 1
Try to modify program FruitOrderCase.py to FruitOrderCase – validation.py. In the
new program, add some code to validate the Yes / No input by user. If user input
string other than Yes / No, the system should prompt the user to input again. Take
the following screen for your reference before working on Classwork 1.

You might also like