I am having trouble with some undefined variables in my code for a school assignment using nested loops and functions. Also, if you happen to spot any other errors please lmk.
Code:
shopping_lists = [
['toothpaste', 'q-tips', 'milk'],
['milk', 'candy', 'apples'],
['planner', 'pencils', 'q-tips']
]
customer_input = ''
#prints shopping lists
print(shopping_lists)
print ('')
print("Press '1' to update an item, '2' to view an item, or '3' to view a list")
customer_input = input("What do you want to do? ")
if customer_input == '1':
def update_list(List, Item, newItem):
list = int(input('What list would you like to update? Answer using 1, 2, or 3. ')-1)
print (shopping_lists[list])
itm = int(input('What item would you like to view? ')-1)
print (shopping_lists[list][itm])
newItm = input('What would you like to change the item to? ')
shopping_lists[list][itm] = newItm
update_list(list, itm, newItm)
def view_item():
pass
def view_list():
pass
#While loop
while 'stop' not in customer_input:
update_list(list, itm, newItm)
I would rearrange your execution flow as follows.
shopping_lists = [
['toothpaste', 'q-tips', 'milk'],
['milk', 'candy', 'apples'],
['planner', 'pencils', 'q-tips']
]
def handle_action(action):
if action == '1':
update_list()
elif action == '2':
view_item()
elif action == '3':
view_list()
else:
pass
# What if an unrecognized action is used?
def update_list():
list_number = int(input('What list would you like to update? Answer using 1, 2, or 3. ')) - 1
print(shopping_lists[list_number])
itm = int(input('What item would you like to view? ')) - 1
print(shopping_lists[list_number][itm])
newItm = input('What would you like to change the item to? ')
shopping_lists[list_number][itm] = newItm
def view_item():
pass
def view_list():
pass
#While loop
customer_input = ''
while customer_input != 'stop':
print(shopping_lists)
print("Press 1 to update an item, 2 to view an item, or 3 to view a list")
customer_input = input("What do you want to do? ")
handle_action(customer_input)
Notice the difference on the usage of stop as a break word for the loop. And the handle_action function to control a switch of what you are doing.
I also renamed list to list_number because list is a type name in python.
Related
My program is supposed to record information for athletes in a race. When I select the option to add a score for an athlete, it calls the input_scores function, but then it won't get out of it? Also, for option "b", I want it to display the message that there's no record available if the list athlete_results is empty. I hope I've explained things ok, I am new to programming so any help is appreciated!
menu = """Choose an option:
'a' = Input score
'b' = Display results
'c' = quit
>
"""
athlete_results = []
choice = input(menu).strip().lower()
def input_scores():
name = input("Name: ").strip().title()
country = input("Country: ").strip().title()
time = input("Time: ").strip()
athlete_results.append({
"Name": name,
"Country": country,
"Time:": time
})
def display_results():
for athlete in athlete_results:
name, country, time = athlete_results.values
print(f"{name}| {country}| {time}s")
while True:
if choice == 'a':
input_scores()
elif choice == 'b':
if athlete_results:
display_results()
elif choice == 'c':
break
else:
print("Invalid option!!!")
Move the line
choice = input(menu).strip().lower()
to a line directly after while True:
while True:
choice = input(menu).strip().lower()
in order to have a chance to change the option or quit.
I'm trying to create a list that stores user input to be later manipulated. However when the User inputs names into the temporary list, it updates showing that the nameList has been updated, but when i add the nameList to the concernList, it does not add anything but an empty List!
Empty List
concernList = []
nameList = []
def nameLoop():
global concernList
global nameList
first = input("First Name: ")
nameList.append(first)
print(nameList)
middle = input("Middle Initial: ")
nameList.append(middle)
print(nameList)
last = input("Last Name: ")
nameList.append(last)
print(nameList)
concernList.append(nameList)
nameList.clear()
def siteMonitor():
pass
nameLoop()
while True:
newConcernInput = input("Add Another Concern? (y/n)")
if (newConcernInput.lower() == 'y'):
nameLoop()
print("Type 'q' to stop adding concerns. ")
if (newConcernInput.lower() == 'n'):
monitorInput = input("Begin Background Monitoring? (y/n)")
if (monitorInput == 'y'):
siteMonitor()
else:
pass
if (newConcernInput.lower() == 'q'):
break
for count in range(0, len(nameList)):
pass
print(concernList)
print("Added To Concern List.")
concernList.append(nameList) doesn't create a second list - the newly added element is just a reference to the original list (related). This means that nameList.clear() will delete the contents of the same list that you just appended to concernList.
However, I don't see the need for a global nameList in the first place. This is how I would rewrite the code:
concernList = []
nameList = []
def nameLoop():
first = input("First Name: ")
middle = input("Middle Initial: ")
last = input("Last Name: ")
return [first, middle, last]
def siteMonitor():
pass
nameList = nameLoop()
concernList.append(nameList)
while True:
newConcernInput = input("Add Another Concern? (y/n)")
if newConcernInput.lower() == 'y':
nameList = nameLoop()
concernList.append(nameList)
print("Type 'q' to stop adding concerns. ")
if newConcernInput.lower() == 'n':
monitorInput = input("Begin Background Monitoring? (y/n)")
if monitorInput == 'y':
siteMonitor()
else:
pass
if newConcernInput.lower() == 'q':
break
for count in range(0, len(nameList)):
pass
print(concernList)
print("Added To Concern List.")
I am writing a program to accept user input to build a sentence word-by-word. After the user is done it is supposed to display the the sentence and the amount of words in the list. I know my code isn't complete and I am only requesting help for one issue. As of the moment I cannot get the first input to append or insert into the list, while others are. Any help would be great. I have been searching for awhile with no progress.
Code:
index = 0
def main():
wordList = []
inputFunc(wordList = [])
def inputFunc(wordList = []):
global index
print("To make a sentence, enter one word at a time... ")
wordInput = input("Enter word... : ")
wordList.insert(index,wordInput)
index += 1
choice = input("(y = Yes, n = No, r = Reset List)Another word?: " )
inputCalc(choice)
completeList(wordList)
def inputCalc(choice):
while choice == 'y':
inputFunc()
while choice == 'n':
return
while choice == 'r':
clearList()
def completeList(wordList):
print(wordList)
exit()
def clearList():
wordList.clear()
main()
main()
There's lots of issues with your code, but the main reason why your word is not being appended to your list is because mutable default arguments don't generally do what you want.
Instead just perform everything in a single function.
def main():
inputFunc()
def inputFunc():
running = True
wordList = []
while running:
print("To make a sentence, enter one word at a time... ")
wordInput = input("Enter word... : ")
wordList.append(wordInput)
while True:
choice = input("(y = Yes, n = No, r = Reset List)Another word?: " )
if choice == 'y':
break
elif choice == 'n':
running = False
break
elif choice == 'r':
wordList = []
break
print(wordList)
if __name__ == "__main__":
main()
The detailed answer is The first time you call inputFunc() inside main() you pass an empty list:
def main():
wordList = []
inputFunc(wordList=[])
When you call it again via recursion inside inputCalc(choice) you call inputFunc() without passing any arguments thus using a different list, the pre-initialized list.
def inputCalc(choice):
while choice == 'y':
inputFunc()
I can't figure out how to add certain values to a list for each individual key. I have a few types (b,m,t,d,c) which are the keys, and then I want to add costs of those items to a list that is the value of the dictionary each time I go through the loop.
This is what I have so far:
a={}
allitemcostb=[]
allitemcostm=[]
allitemcostt=[]
allitemcostd=[]
allitemcostc=[]
n=4
while n>0:
itemtype=raw_input("enter the item type-b,m,t,d,c:")
itemcost=input("enter the item cost:")
if itemtype="b":
allitemcostb.append(itemcost)
a[itemtype]=allitemcostb
if itemtype="m":
allitemcostm.append(itemcost)
a[itemtype]=allitemcostm
if itemtype="t":
allitemcostt.append(itemcost)
a[itemtype]=allitemcostt
if itemtype="d":
allitemcostd.append(itemcost)
a[itemtype]=allitemcostd
if itemtype="c":
allitemcostc.append(itemcost)
a[itemtype]=allitemcostc
else:
print "Sorry please enter a valid type"
n=n-1
print a
It keeps giving me error messages, whether it be something isn't defined, or improper syntax.
Thanks
Instead of a[itemtype] = allitemcostb, which simply sets that key's value to a new cost, you need to create a list if that key doesn't exist yet or add it to the existing list if it does. Do this with the setdefault() method.
The following uses just a dictionary with itemtype:[itemcost, itemcost...] and no separate lists, dispenses with the manually-incremented while loop in favor of a for loop with an xrange, and replaces the large branching structure with a more direct structure (instead of "if it's a, do a," it does "do whatever it is"). The line if itemtype in ('b', 'm', 't', 'd', 'c'): checks that the entered itemtype is a single-character string representing an available option. If the entered itemcost can't be converted to a float, the error is caught and the user is prompted to try again.
a={}
n=4
for i in xrange(n):
itemtype = raw_input("enter the item type-b,m,t,d,c:")
itemcost = raw_input("enter the item cost:")
try:
itemcost = float(itemcost)
except ValueError:
print "Sorry, please enter a valid cost."
break
if itemtype in ('b', 'm', 't', 'd', 'c'):
a.setdefault(itemtype, []).append(itemcost)
else:
print "Sorry, please enter a valid type."
print a
try this:
a = {}
all_item_cost_b=[]
all_item_cost_m=[]
all_item_cost_t=[]
all_item_cost_d=[]
all_item_cost_c=[]
n = 4
while n > 0:
item_type = input("enter the item type-b,m,t,d,c:")
item_cost = input("enter the item cost:")
if item_type == "b":
all_item_cost_b.append(item_cost)
a[item_type] = all_item_cost_b
elif item_type == "m":
all_item_cost_m.append(item_cost)
a[item_type] = all_item_cost_m
elif item_type == "t":
all_item_cost_t.append(item_cost)
a[item_type] = all_item_cost_t
elif item_type == "d":
all_item_cost_d.append(item_cost)
a[item_type] = all_item_cost_d
elif item_type == "c":
all_item_cost_c.append(item_cost)
a[item_type] = all_item_cost_c
else:
print("Sorry please enter a valid type")
n = n - 1
print(a)
Give us a feedback. Don't forget to mark as answered, if this solves your problem.
Cheers.
Here are two solutions.
The fist one is not so strict. it will allow the user to enter any value for the itemtype but not for the itemcost
a={}
n=4
while (n>0):
itemtype = input("enter the item type-b,m,t,d,c:")
itemcost = input("enter the item cost:")
while(True):
try:
itemcost = float(itemcost)
break;
except ValueError:
print ("Sorry, please enter a valid cost.")
itemcost = input("enter the item cost:")
if itemtype.lower() in "b m t d c".split():
a[itemtype] = a.get(itemtype,list())+[itemcost]
n-=1
print (a)
This second form will be strict for both user inputs and will keep prompting till the user enters the expected value
a={}
n=4
while (n>0):
itemtype = input("enter the item type-b,m,t,d,c:")
##user enters a wrong value
while(itemtype.lower() not in "b m t d c".split() ):
print ("Sorry, please enter a valid item.")
itemtype = input("enter the item type-b,m,t,d,c:")
itemcost = input("enter the item cost:")
##user enters a wrong value
while(True):
try:
itemcost = float(itemcost)
break;
except ValueError:
print ("Sorry, please enter a valid cost.")
itemcost = input("enter the item cost:")
a[itemtype] = a.get(itemtype,list())+[itemcost]
n-=1
print (a)
I have created a class with two functions inside of it. These functions run forever in a loop at the bottom of the code. However, the first function creates a dictionary and the user adds values to this dictionary. The second function is meant to import the dictionary and add 10 to each value. However, when I run this code, I get an error stating that 'Materials is not defined'. How am I supposed to properly use the dictionary in both functions?
Here is my code:
class materialsClass:
def materialsChange(self):
while True:
q1 = raw_input("Type 'edit' to add or change a material, or 'continue' to continue: ")
if q1 == 'edit':
while True:
q2 = raw_input("Type 'add' to add a new material, 'edit' to edit amount of a material: ")
if q2 == 'add':
x = str(raw_input("Enter the Material: "))
y = int(0)
Materials = {x:y}
break
elif q2 == 'edit':
x = str(raw_input("Enter your Material: "))
y = int(raw_input("Enter your Change: "))
Materials[x] += y
break
else:
print "Please Type an Option"
elif q1 == 'continue': break
else:
print "Type an Option!"
print Materials
def materialCounter(self):
for k in Materials: Materials[k] += 10
print Materials
while True:
obj=materialsClass()
obj.materialsChange()
obj.materialCounter()
You cannot use a variable local to a method within another method. You need to define the variable in the class scope and make it an instance variable. For example:
class materialsClass:
def __init__(self):
self.Materials = dict()
def materialsChange(self):
...
self.Materials[x] = y
(in place of Materials = {x:y})
def materialCounter(self):
for k in self.Materials:
self.Materials[k] += 10
print self.Materials
Also note that when the interpreter runs the line
Materials = {x:y}
it replaces the Materials dictionary with a new one and you are not actually adding a new material in the dictionary. That's why you should write:
self.Materials[x] = y
instead. This will add a new material to the dictionary.
Variables inside the functions are in local namespace so you can not use Materials inside the second function as it has been defined in first one ! you can initial Materials in the enclosing class scope instead :
But note that you need to initial your variable inside the __init__ function:
class materialsClass:
def __init__(self):
self.Materials=dict()
def materialsChange(self):
while True:
q1 = raw_input("Type 'edit' to add or change a material, or 'continue' to continue: ")
if q1 == 'edit':
while True:
q2 = raw_input("Type 'add' to add a new material, 'edit' to edit amount of a material: ")
if q2 == 'add':
x = str(raw_input("Enter the Material: "))
y = int(0)
self.Materials = {x:y}
break
elif q2 == 'edit':
x = str(raw_input("Enter your Material: "))
y = int(raw_input("Enter your Change: "))
self.Materials[x] += y
break
else:
print "Please Type an Option"
elif q1 == 'continue': break
else:
print "Type an Option!"
print self.Materials
def materialCounter(self):
for k in self.Materials: self.Materials[k] += 10
print self.Materials
To build on some of the other answers. You have to create a dictionary under the class and the way you were adding items to the dictionary was incorrect so I have changed that. You also have to create a class in the proper way for it to work. I have checked this code and it works for me anyway. I hope this helps.
class materialsClass(object):
def __init__(self): # create a new class
self.materials = {} # create a new dictionary under this class
def materialsChange(self):
while True:
q1 = raw_input("Type 'edit' to add or change a material, or 'continue' to continue: ")
if q1 == 'edit':
while True:
q2 = raw_input("Type 'add' to add a new material, 'edit' to edit amount of a material: ")
if q2 == 'add':
x = str(raw_input("Enter the Material: "))
y = int(0)
self.materials[x] = y # this is how to add items to dictionaries sequentially
print self.materials
break
elif q2 == 'edit':
x = str(raw_input("Enter your Material: "))
y = int(raw_input("Enter your Change: "))
self.materials[x] = y
print self.materials
break
else:
print "Please Type an Option"
elif q1 == 'continue': break
else:
print "Type an Option!"
print self.materials
def materialCounter(self):
for k in self.materials:
self.materials[k] = self.materials[k] + 10
print self.materials
obj=materialsClass() # you do not need to create the class again and again, just once is fine
while True:
obj.materialsChange()
obj.materialCounter()