Each time I enter a restaurant name and then go to print the list, it does not stay inside that list. I also need to be able to use the randomize command so that Randomize() will generate a random number and use it as an index to print the restaurant at that index to the screen.
while(True):
getInput=input("Enter a restaurant name: ")
list=[]
list.append(getInput)
if(str(getInput) == "List"):
print(list)
elif(str(getInput) == "Quit"):
break;
I end up getting this:
Enter a restaurant name: Name
Enter a restaurant name: Names
Enter a restaurant name: List
['List']
Enter a restaurant name:
I need to be able to enter a restaurant and then be able to pull up that certain restaurant with a number. I just started Python a couple of months ago. Thank you!
Couple things:
You don't want to use a name like "list" because it's a function and type in Python which can make things confusing so instead name it something like "my_list".
And your issue was every loop you were starting the list from scratch. You want to move that list outside the loop instead.
my_list = []
while True:
getInput = input("Enter a restaurant name: ")
my_list.append(getInput)
if getInput == "List":
print(my_list)
elif getInput == "Quit":
break
Edit:
To answer your comment question, you can add in a number using a manual counter if you wanted (for simplicity and understandability):
my_list = []
id = 0
while True:
getInput = input("Enter a restaurant name: ")
my_list.append(f'{id}_{getInput}')
id += 1
if getInput == "List":
print(my_list)
elif getInput == "Quit":
break
You are creating a new list each time the loop repeats. Instead you should create the list before the loop even starts.
Related
I seem to receive an error every time I try to remove an item from the dictionary. Here's my code:
print(" MY NEW AND IMPROVED GROCERY LIST ")
def grocerylist():
hist_grocery = []
grocery = True
while grocery:
choice = str(input("\n=====================\nWhat would you like to do? \n1 - Add an item\n2 - Remove an item "
"\n3 - Print entire list\n4 - Calculate cost\n5 - Exit program\nChoice: "))
if choice == "1":
print("=====================\nADD AN ITEM\n")
information = input("Give the following information: \nItem name: ")
price = input("Item price: ")
quantity = input("Item quantity: ")
grocery_list = {"Item name": str(information), "price": float(price), "quantity": int(quantity)}
hist_grocery.append(grocery_list)
** elif choice == "2":
print("=====================\nREMOVE AN ITEM\n")
remove_item = str(input("What would you like to remove? \nItem name: ")).format() # format function
grocery_list = [i for i in hist_grocery if str(i).lower() != remove_item]
**
elif choice == "3":
print("=====================\nPRINTING LIST...")
if hist_grocery == []:
print("The grocery list is empty!")
else:
[print(items, end="\t ") for items in grocery_list.values()]
Here's what I inputted: enter image description here
Tried removing the item egg but it became an error.
Here's what the terminal says:
enter image description here
I tried creating another for loop but somehow I got confused along the process. What should I change in my code?
Your error isn't with deleting an item it's with printing the items.
Since you didn't choose option 1 first there is no existing object grocery_list. I'm speculating a bit here but I assume the interpreter sees the for-each loop and assumes that it must be a list, which doesn't have a .values() method so it gives you this error.
I would try declaring an empty dictionary before your first if block.
The error has almost nothing to do with the "delete" option. The error is in the "print" option. If you look in the code for choice 2, you see that grocery_list = [i...], which is definitely a list. As the error clearly states, you cannot use .values() with a list, like when you tried to do so in the 3rd option, where [...for items in grocery_list.values()].
PS: Please don't post your error as a picture. It makes it easier for all those involved if it's typed out in the actual question.
Have written below program, but how to avoid the system checking the two argument when enter is pressed, we are using the enter key to exit the while loop.
while True: # need to exit the while loop thru one <Enter>
itemcode, quantity = input("Enter item code and quantity (Press <Enter> key to end): ") .split()
if itemcode == " " : #got two argument, one enter will crash the system, how to amend it
return
if itemcode not in orderdict.keys():
print("Invalid item code! Try again.")
continue
if itemcode in orderdict.keys():
orderdict [itemcode] = orderdict
#print("{:4s} {:<3d} {:<3d} X {:<3d} ".format(itemcode, [0], [1], [3]))
else :
input ()
break
Your problem is that the first line is hardcoded in such a way that the program expects two, and exactly two, values separated by a space. If you give it less than two (and simply hitting "enter" means giving it zero values), or more than two, this causes a traceback because the expected number of values isn't there.
If you don'T trust your users to enter the correct number of values, then I think you can avoid a crash either with a try/exception block, or a simple loop that repeats promtping the user for input until the number of entered values is exactly two:
while True:
entry_list = input("Enter item code and quantity (Press <Enter> key to end): ") .split()
if len(entry_list) == 2:
itemcode = entry_list[0]
quantity = entry_list[1]
break
You can start to ask the user to enter only the value of the item and check this value if it is an enter key, then break the loop. Otherwise, check the value of the item if it is within the keys if so, then ask the user for the corresponding quantity. I think you need to replace orderdict
with the corresponding quantity for the item entered by the user.
orderdict = {"car":50,"plane":60,"bus":100} # example
while True:
itemcode = input("Enter item code and quantity (Press <Enter> key to end): ")
if itemcode == "" :
break
elif itemcode not in orderdict:
print("Invalid item code! Try again.")
else:
orderdict [itemcode] = input("Enter the quantity: ")
Note: you do not need to write orderdict.keys(), you can use only the name of a dictionary to iterate through the keys of orderdict.
i just started programming in Python and i'm trying to do a program that prints names n times through a while loop, the condition is when the user input yes the program keeps adding n names to a list, if the users inputs something else it simply prints all the elements added in the list
eg: list_input = "Enrique"
count = 3 #Times
lista = ['Enrique', 'Enrique', 'Enrique']
def nameTries():
list_input = input("Enter the name:")
lista = []
count = int(input("How many times you want to repeat it?"))
lista.append(f'{list_input * count}')
confirm = input("Wanna add more? yes/no")
while confirm == "yes":
list_input = input("Enter the name:")
count = int(input("How many times you want to repeat it?"))
lista.append(f'{list_input * count}')
confirm = input("Wanna add more? yes/no")
if confirm != "yes":
print(lista)
break
else:
print(lista)
the problem is it's adding ONLY in an element of the list like this:
>>>['EnriqueEnriqueEnrique']
how can i solve this? Thanks in advance.
the append method only adds 1 element to a list. If you want to add several elements at once, you must concatenate, which is done with the + operator.
Also, your looping procedure is not very "sexy" because the instructions are the same two times. You could do it better like this :
def nameTries():
lista = []
while True:
list_input = input('Enter the name: ')
count = int(input('How many times you want to repeat it? '))
lista += [list_input] * count
confirm = input('Wanna add more? (y/n): ')
if confirm != 'y':
return lista
>>> nameTries()
Enter the name: Enrique
How many times you want to repeat it? 3
Wanna add more? (y/n): y
Enter the name: Pedro
How many times you want to repeat it? 5
Wanna add more? (y/n): n
['Enrique', 'Enrique', 'Enrique', 'Pedro', 'Pedro', 'Pedro', 'Pedro', 'Pedro']
I am having a trouble of making a while-loop to store all inputs in the list and break the loop while it inputs "quit" and then show ALL the inputs that users have done. my codes are as followings but it only shows ["quit"] after all.
while True:
list_names = []
enter_names = input("what's the name ")
list_names.append(enter_names)
if enter_names == "quit":
break
print(list_names)
You main problem is that you need to make the list before the loop. Otherwise it will be recreated each time it loops. It's also a good habit to format the input as well.
#Need to create list before loop
list_names = []
while True:
names = str(raw_input("what's the name "))
list_names.append(names)
if names == "quit":
break
print(list_names)
Below is the code I am currently working with. Im trying to make it so I can add a second piece of data after the name so it reads (name1,data1),(name2,data2),(name3,data3). Is there a function that allows me to do this?
ListOfNames = []
while True:
Name = input('Input Band Member')
if Name != "":
ListOfNames.append(Name)
else:
break
You can store the information in two separate lists if you will and zip them together with zip() in the end.
You can try like so:
namel = []
bandl = []
while True:
n = input("Enter Name: ")
if n != '':
d1 = input("Enter data1: ")
namel.append(n)
bandl.append(d1)
else:
break
print(list(zip(namel, bandl)))
Demo output:
Enter Name: Rupee
Enter data1: India
Enter Name: Dollar
Enter data1: USA
Enter Name:
[('Rupee', 'India'), ('Dollar', 'USA')]
Or if you make sure the user enters 2 values separated by comma, you can try it like so:
l = []
while True:
n = input("Enter Name: ")
if n!='':
l.append(n.split(','))
else:
break
print(l)
Demo run:
Enter Name: Rupee, India
Enter Name: Dollar, USA
Enter Name:
[['Rupee', ' India'], ['Dollar', ' USA']]
You don't need a special function, just append a list instead of a string:
ListOfNames.append([Name, data])
Or, if you don't know what the data will be until later:
ListOfNames.append([Name])
and then:
ListOfNames[x].append(data)
Where x is the index of whatever list you want to append to.
Alternatively, if you prefer to build up the two lists independently first, you can use zip() to merge them them.
zip(ListOfNames, data_list)
That may or may not be more appropriate depending on your program's structure. Without knowing how or when or in what order your data_list is gathered, it's hard to say.