The Problem to Analyze and Implement
Implement an inventory system of parts and prices using two parallel lists. The user can choose
from 4 options in a menu: to add a part, search for a part and display its price, display
everything in inventory, or exit.
The menu continues to redisplay until the user chooses to exit the system.
Requirement 1 – search_inventory Function
Name of function: search_inventory
Input to function: list1, list2
Output from function: None
Functionality: 1. The input list1 will be the list of parts.
2. The input list2 will be the list of prices.
3. Prompt the user for the part to search for.
4. Implement linear search to search for the part in list1.
5. If it is found, display the corresponding price from list2.
6. If it is not found, display a message.
Requirement 2 – add_to_inventory Function
Name of function: add_to_inventory
Input to function: list1, list2
Output from function: None
Functionality: 1. Prompt the user for the part to add.
2. Append this value to list1.
3. Prompt the user for the price to add.
4. Append this value to list2.
Requirement 3 – display_inventory Function
Name of function: display_inventory
Input to function: list1, list2
Output from function: None
Functionality: 1. Print column headers.
2. Use a counter-controlled while loop to print the contents of
each list in two columns.
3. See the sample runs below for the format of the output.
4. The prices must display with two values after the decimal
and be right-aligned.
Requirement 4 – display_menu Function
Name of function: display_menu
Input to function: None
Output from function: User’s choice as an integer
Functionality: 1. Display the menu of choices as shown in the sample run.
2. Prompt the user for their choice and store this value as an
integer.
3. Return the user’s choice
Requirement 5 – Main Section of Program
Declare two empty lists: parts_list and price_list.
Call the display_menu function and save the return value.
Create a sentinel_controlled loop:
a. Within this loop, use a selection structure to check the return value from the display
menu function and call the appropriate function depending on the user’s choice.
b. Call the display_menu function and save the return value.
c. You will have to figure out what the sentinel value is. (Hint – when should this loop
end?)
My codes:
**
def search_inventory(parts_list, price_list):
name_part = input("Name of a part: ")
index = 0
part_found = False
while part_found == False and index < len(parts_list):
if name_part == parts_list[index]:
part_found = True
else:
index = index + 1
if part_found:
print("Name of part:", name_part)
print("Price of part:", price_list)
else:
print(name_part, "was not found in the list")
return
def add_to_inventory(parts_list, price_list):
add_part = input("Add to inventory: ")
parts_list.append(add_part)
add_price = input("Add price: ")
price_list.append(add_price)
print("Part added successfully")
return
def dispay_inventory(parts_list, price_list):
part_name = ""
part_price = 0
while part_name == parts_list and part_price == price_list:
print("Name of part: ", part_name)
print("Price of part:{0:.2f}", part_price)
return
def dislay_menu():
print("Welcome to JJC Inventory System")
print("1. Add to inventory")
print("2. Check price")
print("3. Display inventory")
print("4. Exit")
user_choice = int(input("Your choice: "))
return user_choice
parts_list = []
price_list = []
user_choice = 0
dislay_menu()
while (user_choice != 4):
if user_choice == 1:
add_to_inventory(parts_list, price_list)
elif user_choice == 2:
search_inventory(parts_list, price_list)
elif user_choice == 3:
dispay_inventory(parts_list, price_list)
else:
break
dislay_menu()
**
I think the problem is with the sentinel_controlled loop. I checked the return value from the display
menu function and called the appropriate function depending on the user’s choice.
Related
For the task that I have been assigned, you are told that when a person enters a number, that data cell value should be pulled from the list. How do I achieve this?
I assume you mean "data cell value" as "list item" at an index.
First there is input from the user, using the input function.
If this is not a valid integer, the int function will raise an exception.
Then we must also check that the index given by the user is within the list size. The first element of a list is at index #0, and the last is #list-length - 1. For example, a 3-item list has elements at 0, 1, 2.
fruit = [ "Apples", "Oranges", "Rambutan", "Mango" ]
try:
user_text = input("Enter fruit index: ")
user_choice = int(user_text)
except:
print("Bad Choice");
user_choice = -1
if (user_choice >= 0 and user_choice < len(fruit)):
print("Your Fruit is: " + fruit[user_choice])
else:
print("Index out of range")
E.g.:
# python3 ./fruit.py
Enter fruit index: 2
Your Fruit is: Rambutan
# python3 ./fruit.py
Enter fruit index: None of your business
Bad Choice
Choice out of range
I am having a problem with my code. The loop runs only once respective of the number the user enters. Thanks for the help.
#create an empty list and ask the user how many items they want to add
# take the items the user entered and add it to the empty list.
print("enter the number of items")
x = int(input(">")) #take number of user input with the type int
print("thanks")
print("enter your food items")
fitems = [] # empty list
for i in range(x): #range to limit the number of iteration the user entered.
items = input (">") #taking the items from the user
empty = ""
if (items == empty):# checking if the user added nothing
print("no items added")
break
else:
fitems.append(items) #add the list of items the user entered to the
empty list
print("hello here is your food items: \n",fitems) #output user items
You are missing some indentation in your code and there are also some other mistakes. This is (I think) the correct code:
print("enter the number of items")
x = int(input(">"))
print("thanks")
print("enter your food items")
fitems = []
for i in range(x):
items = input(">").strip() # there was a space before first bracket in your code, it's possible to have it there, but this is better
# edit: added .strip(), it removes extra whitespace from beginning and end
if items == "": # no need to create empty string variable, compare simply with empty string,
# edit: you can also use 'if not items:', because empty string evaluates to false
print("no items added")
break # break only if nothing added, so indent break to be only executed if empty
fitems.append(items) # you don't have to have else here, break ends the loop, so this is not executed then
print("hello here are your food items: \n",fitems) # remove 1 indent, print only after loop ended
I took the liberty to make some changes. Try this out:
# create an empty list and ask the user how many items they want to add
# take the items the user entered and add it to the empty list.
fitems = []
# Define valid input for amount of items
valid = [str(i) for i in range(1,10)] # ["1","2"...."9"]
# If item is not in the list of valid, continue asking
while True:
print("enter the number of items [1-9]")
x = input(">")
if x in valid:
break
# Convert to int
itemamount = int(x)
print("thanks\nenter your food items")
# Now ask for inputs using while > 0 and remove itemamount in each loop
while itemamount > 0:
while True:
item = input (">")
if item:
break
print("Blank input")
fitems.append(item)
itemamount-=1
print("hello here is your food items: ")
for ind,i in enumerate(fitems,1):
print("{}. {}".format(ind,i))
This would work, Since you have not indented the "break" inside the for loop
#create an empty list and ask the user how many items they want to add
# take the items the user entered and add it to the empty list.
print("enter the number of items")
x = int(input(">")) #take number of user input with the type int
print("thanks")
print("enter your food items")
fitems = [] # empty list
for i in range(x): #range to limit the number of iteration the user entered.
items = input (">") #taking the items from the user
empty = ""
if (items == empty):# checking if the user added nothing
print("no items added")
break #your error corrected
else:
fitems.append(items) #add the list of items the user entered to the
empty list
print("hello here is your food items: \n",fitems) #output user items
I think the only problem in your code is the identation, so you should change like this:
print("enter the number of items")
x = int(input(">")) #take number of user input with the type int
print("thanks")
print("enter your food items")
fitems = [] # empty list
for i in range(x): #range to limit the number of iteration the user ente red.
items = input (">") #taking the items from the user
empty = ""
if (items == empty):# checking if the user added nothing
print("no items added")
break
else:
fitems.append(items) #add the list of items the user entered to the
print("hello here is your food items: \n",fitems)
First of all break statement and else statement aren't intended properly. Furthermore when you use .append() you should add a i+=1 to loop through x , that the user inputs.
This will work :
for i in range(x): #range to limit the number of iteration the user entered.
items = input (">") #taking the items from the user
empty = ""
if (items == empty):# checking if the user added nothing
print("no items added")
break
else:
fitems.append(items) #add the list of items the user entered to the
i += 1
This will result in a no-print if nothing was entered:
print("enter the number of items")
x = int(input(">")) #take number of user input with the type int
print("thanks")
print("enter your food items")
fitems = [] # empty list
for i in range(x): #range to limit the number of iteration the user entered.
items = input (">") #taking the items from the user
empty = ""
if (items == empty):# checking if the user added nothing
print("no items added")
break
else:
fitems.append(items) #add the list of items the user entered to the\
empty list
if len(fitems)==0:
pass
else:
print("hello here is your food items: \n",fitems)
I'm stuck on writing this program. These are the instructions that were given to us.
As per the guidelines at the top of the assignment you may NOT import any modules. This
includes the statistics module.
The user should be displayed with a list of options from 1 to 5
If the user chooses 1 they should be prompted to enter a student's name and grade
If the student does not appear in the grade book, the student and the grade should be
added to the grade book
If the student is already in the grade book their grade should be changed to the value
given
If the user chooses 2 they should be prompted to enter a student's name.
That student should be removed from the grade book
If the student is not in the grade book then the grade book should not be modified
but also no error should be displayed.
If the user chooses 3 the names and grades of all students should be displayed in
alphabetical order
If the user chooses 4 the following statistics for the course should be displayed: Mean,
Median, and Mode
The median is the middle number in a list of sorted numbers
The mode is the value that appears most often
If more there are 2 or more more numbers that appear most often then you may display any of them.
If the user chooses 5 the program should terminate
If any other option is chosen the program should tell the user that it does not recognize
the option and ask the user for another choice.
All inputs besides the command choice will be valid.
You do not have to match the exact number of spaces I have in my output when
displaying grades and course statistics but there needs to be at least 1 space.
Hint: Break the problem down into small functions that each tackle one part of the
problem. For example have one function for inserting a student into the grade book, another for calculating the mean, etc.
This is what I have so far and there are a few errors:
def menuprint():
print('1. Add/modify student grade.\n')
print('2. Delete student grade\n')
print('3. Print student grades\n')
print('4. Display the course statistics\n')
print('5. Quit\n')
menuprint()
choice = 0
students = []
grades = []
def addmodify():
name_points = input('Enter name and points: ')
nameGrade_list = name_points.split()
name = nameGrade_list[0]
points = nameGrade_list[1]
students.append(name)
grades.append([points])
def stat():
for i in range(0,len(students)):
print("NAME:", students[i])
print ("GRADES:", grades [i])
def mean(list):
sum = 0
floatNums = [float(x) for x in list]
return sum(floatNums) / len(list)
while choice !=5:
choice = int(input('Your choice: '))
if choice == 1:
addmodify()
print('Enter name and points:')
elif choice == 2:
name = input('Enter name to delete:')
students.remove(name)
elif choice == 3:
gradelist()
print ('SS')
elif choice == 4:
print('Mean', mean(grades))
def mean(num_list):
sum = 0
floatNums = [float(x) for x in num_list]
return sum(floatNums) / len(num_list)
should fix it. list is a keyword and cannot be used anywhere in your code as a variable.
This weeks lab is based on the example on pages 53,54 of the wikibook "Non-Programmers Tutorial For Python" by Josh Cogliati (2005), (see http://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3/Dictionaries).
In his example, Cogliati has options for printing, adding, removing, and looking up a phone number. Change the code so that, instead of the value in the dictionary being a simple phone number, it is now a list with three values:
phone number
e-mail
address web page
The key should still be simply the persons name. Adapt the menu used in the example accordingly, for example the '2. Add a Phone Number' should now read '2. Add an entry' and if selected should ask the user for the 4 items of information (name, phone, email, web). Aditionally:
Add an option (e.g. number 6 in the menu) to 'Change/Edit an existing entry'.
Add options to:
Print just a list of the phone numbers
Print just a list of the e-mail addresses
Print just a list of the web addresses
Print all of the above together
This is the assignment we were given, I understand what's given in the link and have added a bit to it, unsure as to how to go about adding in the calling upon of the email and webpage information once stored
Although I agree with the comment under your answer, I will still try my best to give you some guidance.
Original Code:
def print_menu():
print('1. Print Phone Numbers')
print('2. Add a Phone Number')
print('3. Remove a Phone Number')
print('4. Lookup a Phone Number')
print('5. Quit')
print()
numbers = {}
menu_choice = 0
print_menu()
while menu_choice != 5:
menu_choice = int(input("Type in a number (1-5): "))
if menu_choice == 1:
print("Telephone Numbers:")
for x in numbers.keys():
print("Name: ", x, "\tNumber:", numbers[x])
print()
elif menu_choice == 2:
print("Add Name and Number")
name = input("Name: ")
phone = input("Number: ")
numbers[name] = phone
elif menu_choice == 3:
print("Remove Name and Number")
name = input("Name: ")
if name in numbers:
del numbers[name]
else:
print(name, "was not found")
elif menu_choice == 4:
print("Lookup Number")
name = input("Name: ")
if name in numbers:
print("The number is", numbers[name])
else:
print(name, "was not found")
elif menu_choice != 5:
print_menu()
Notice that numbers is equal to {} - this signifies that it is a "Dictionary", which stores key/value pairs. To add to a dictionary (or "dict"), you can modify it manually as such: numbers = {'David': 18003574689}. So, in order to access David's phone number, you would type in numbers['David'].
Another way to add to it is by instantiating it (which is already done for you via numbers = {}), and then adding information into to it via the shortcut formula dictname['key'] = value. So in this case, the shorthand can be numbers['Laura'] = 9173162546.
Now, to add a list into the mix, you could use [] (which is a list in python), but you would probably be better suited nesting another dict into the current one. For example, instead of numbers = {'David': 18003574689}, you can now have numbers = {'David': {'phone number': 18003574689, 'e-mail': 'david2015#gmail.com', 'address web page': 'http://dave.com'}, 'Laura': [...etc...]}.
To access these new nested dicts, what you can do is the shorthand numbers['David']['phone number'], which will return his #. You can then do this exact shortcode 2 more times numbers['David']['e-mail'] & numbers['David']['address web page']. These three will access the associated data.
Since I believe this is the toughest part for a newcomer, I'll stop here since the rest should be easy. All you have to do is create new inputs in the correct if conditions. Assign the captured input data into proper variables via the = assignment operator (ex. email = input('Email: ')), and then use the rest of the info logically. I hope this helps.
I have updated my code with the changes made. I am still getting incorrect results...
# Import statements
import random
# Define main function that will ask for input, generate computer choice,
# determine winner and show output when finished.
def main():
# Initialize Accumulators
tie = 0
win = 0
lose = 0
score = 0
# initialize variables
user = 0
computer = 0
# Initialize loop control variable
again = 'y'
while again == 'y':
userInput()
computerInput()
if score == win:
print('You won this round, good job!')
win += 1
elif score == tie:
print('You tied this round, please try again!')
tie += 1
else:
print('You lost this round, please try again!')
lose += 1
again = input('Would you like to play another round (y/n)? ')
#determine winning average
average = (win / (win + lose + tie))
print('You won ', win, 'games against the computer!')
print('You lost ', lose, 'games against the computer.')
print('You tied with the computer for', tie)
print('Your winning average is', average)
print('Thanks for playing!!')
# get user input for calculation
def userInput():
print('Welcome to Rock, Paper, Scissor!')
print('Please make your selection and and Good Luck!')
print('1) Rock')
print('2) Paper')
print('3) Scissor')
user = int(input('Please enter your selection here: '))
print('You selected', user)
# get compter input for calculation
def computerInput():
computer = random.randint(1, 3)
print('The computer chose', computer)
def getScore():
if user == 1 and computer == 3:
score = win
return score
elif user == 2 and computer == 1:
score = win
return score
elif user == 3 and computer == 2:
score = win
return score
elif user == computer:
score = tie
return score
else:
score = lose
return score
# Call Main
main()
In Python:
>>> print("3" == 3)
False
Strings and integers are values of different data types, and will not compare equal. Try changing your input to:
userInput = int(input('Please enter your selection here: '))
This will convert the string typed by the user to a number for later comparison. (Note that I have assumed you are using Python 3.x, because input() behaves slightly differently in Python 2.x.)
Note that this will throw an error if you type anything other than a number.
Update: As pointed out by #FelipeFG in the comments below, you are also overwriting the function userInput with the value typed by the user. You'll need to change the name of one or the other, for example:
def getUserInput():
...
Also don't forget to change the place where you call the function. Do the same for computerInput (change to getComputerInput).
Later on, you can change those to actual functions that return values.
userInput() calls the function "userInput", but you discard the result. The same remark applies to computerInput().
userInput == 1 asks whether the function userInput itself is equal to 1. It isn't. The same remark applies to computerInput == 3 and the others.
In the function "userInput", userInput = ... binds the name "userInput" to the result of the expression. This makes "userInput" a local variable of the function. The function doesn't explcitly return anything, therefore it returns None.
If you're using Python 3, input returns a string, and you should convert its result to an int. If you're using Python 2, input evaluates whatever is entered, which isn't safe; you should use raw_input instead and convert its result to an int.
You need to compare against the return value of your function, not the function itself.
Also:
again = input('Would you like to play another round (y/n)? ')
This will throw an exception if you enter y or n, because there is no defined identifier of that name! What you want to use instead is raw_input()
Edit: As pointed out by Greg, this only applies to Python 2.x. You seem to be using Python3 though.