Add yes/no confirmation in python 3.X [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a function that allows a user the ability to add data via input. I would like to add a confirmation step that will allow them to answer yes or no to continue. If they select no it should allow them to restart the function of adding data to the list. I also want to make sure they answer with Y, YES, y, yes, N, NO, n, no. What would be the best way to accomplish this? I've tried several solution I've found online but I end up not being able to get out of the loop of asking yes or no. Thanks in advance.
def item_list(): # Create a list
items = []
item_int = 0
while 1:
item_int += 1
item = input("\nEnter item %d or Press Enter: " % item_int)
if item == "":
break
items.append(item)
return items
items = item_list()
print(items)

answer = input("Continue?")
if answer.lower() in ["y","yes"]:
# Do stuff
else if answer.lower() in ["n","no"]:
# Do other stuff
else:
# Handle "wrong" input

My answer would be extension of #B. Plüster but it allows slightly bigger range of the inputs and prevent rejections of case-sensitive typos:
answer = input("Continue?")
if answer.upper() in ["Y", "YES"]:
# Do action you need
else if answer.upper() in ["N", "NO"]:
# Do action you need

You could create a wrapper function which calls your other function. In the wrapper function, use another loop to confirm items.
# wrapper function
def item_list_wrapper():
while True:
# call your function at the start of each iteration
final_items = item_list()
# confirm with the user
print('\nThese are your items:', ', '.join(final_items))
user_input = input('Confirm? [Y/N] ')
# input validation
if user_input.lower() in ('y', 'yes'):
break
elif user_input.lower() in ('n', 'no'): # using this elif for readability
continue
else:
# ... error handling ...
print(f'Error: Input {user_input} unrecognised.')
break
return final_items
# your original function
def item_list():
items = []
item_int = 0
while 1:
item_int += 1
item = input("\nEnter item %d or Press Enter: " % item_int)
if item == "":
break
items.append(item)
return items
Then call it as you'd normally call it.
items = item_list_wrapper()
print(items)
In the item_list_wrapper function, note that the line with items = item_list() will renew the list every time. If you want the user to continue adding existing items, you could switch the order of commands around.
def item_list_wrapper():
final_items = item_list() # call the function at the start
while True:
# confirm with the user
print('\nThese are your items:', ', '.join(final_items))
user_input = input('Confirm? [Y/N] ')
# input validation
if user_input.lower() in ('y', 'yes'):
break
elif user_input.lower() not in ('n', 'no'):
# ... error handling ...
print(f'Error: Input {user_input} unrecognised.')
break
# call your function at the start of each iteration
new_items = item_list()
# add new items to previous items
final_items += new_items
return final_items

Don't know whether this is efficient enough.
items = list()
tr = [" Y", "YES", "y", "yes"]
fs = ["N", "NO", "n", "no"]
item_int = 0
def item_list(): # Create a list
global item_int
global items
response = input("\nDo you want to enter data: ")
if response == "":
return
if response in tr:
item_int += 1
item = input("\nEnter item %d or Press Enter: " % item_int)
items.append(item)
elif response in fs:
item_int=0
print("List cleared!")
items.clear()
item_list()
item_list()
print(items)

Related

Breaking a running user input on auto completion when a certain condition is given

I've got an auto completion function that listen on key. There is an edge case in which the given list to complete from is way too long. So I want to limit the output of possible options and ask the user whether he wants to see the whole amount of possibilities.
Let's say I have this completion function and my_list has about 4000 items.
import readline
my_list = [...]
def completer(text, state):
options = [x for x in my_list if x.startswith(text)]
if state < len(options):
return options[state]
else:
return None
readline.parse_and_bind("tab: complete")
readline.set_completer(completer)
while True:
ans = input("Please select one from the list above: ")
if ans == 'exit':
break
print(ans)
I tried to put the condition inside of def completer() like
def completer(text, state):
options = [x for x in my_list if x.startswith(text)]
if state < len(options):
if len(options) > 50:
question = input(f"Do you want to see all {len(options)} possibilities? ")
if question.lower(0) == "y":
return options[state]
else:
return None
else:
return options[state]
else:
return None
Unfortunately this doesn't work, because there is no way calling the input() function inside the input() function. Do you guys got an idea how to implement this?

sharing a data between two functions in python

so i have a code which loops until the user types cancel and allows the user to input things into a list and then see the list if they want to. but i have a problem wherein if i want to see the list the user has to input again and the data i typed when i added to the list is gone. here is the code pls help me im pretty new to python.
answer=""
def addlist():
list=input("what would you like to add? ")
print("added successfully")
return list
def showlist():
list=addlist()
print(list)
while answer !="cancel":
answer=input("what would you like to do?, 1 for add to list, 2 for show list, cancel to close")
if answer=="1":
addlist()
elif answer=="2":
showlist()
else:
print("wrong value")
So we've got a few problems here:
addlist doesn't actually create a list, it creates a string.
showlist depends on addlist, when really we should be looking for a common list that we toss everything into (assuming you actually want to work with a list)
Your indentation in your while loop is incorrect
def addlist():
item = input("what would you like to add?")
return item
def showlist(mylist):
print(mylist)
mylist = []
answer = ""
while answer != "cancel":
answer = input("what would you like to do?, 1 for add to list, 2 for show list, cancel to close")
if answer == "1":
add_item = addlist()
mylist.append(add_item)
print("added successfully")
elif answer == "2":
showlist(mylist)
else:
print("wrong value")
That above seems to do the trick.
You seem to have a grasp on return statements, so how about you pass each of those functions a common list as I did mylist and have them do stuff with that.
I changed addlist to actually just get the item we want to add to the list and then return that item and append it outside of the function. In showlist I pass mylist to it via: showlist(mylist) and then print the list I get in that function.
You should create a list element in order to append your items in it. You can see more here. One way to do what you want is like this:
answer = ""
temp_list = []
def addlist():
item = input("what would you like to add? ")
temp_list.append(item)
print("added successfully")
def showlist():
print(temp_list)
while answer != "cancel":
answer = input(
"what would you like to do?, 1 for add to list, 2 for show list, cancel to close")
if answer == "1":
addlist()
elif answer == "2":
showlist()
else:
print("wrong value")

Adding items to shopping List Python

I'm learning Python and I'm trying to make shopping List
where you can add items
first it will ask you to add the items if the shopping list is empty
it will be added automatically if not it will ask you where you would like
to put the item (index)
but also I'm trying to make the program exit in certain condition like DONE
or HELP or SHOW but even that i put a condition for that but it's not working can anyone help me with this
hope I explained enough
import os
shopping_list =[]
# Function for clearing the screen
def clear_screen():
os.system("cls" if os.name == "nt" else "clear")
def show_help():
print("Enter 'Done' if you finish adding item \n Enter 'Show' to show your items \n Enter 'Help' toshow this help ")
# Function to show the items that you've entered to the list
def show_item():
clear_screen()
index = 1
for item in shopping_list:
print("{} {}.".format(index,item))
index += 1
# Function to add items to the list
def add_to_list():
while True:
new_item = input("Please enter the item that you would like to add to your shopping list ")
if shopping_list and ((new_item.upper() != "DONE") or (new_item.upper() != "HELP") or (new_item.upper() != "SHOW")):
position = input("Where you would like to add {} to the list \n press 'Enter' if you want to add to the end of the list".format(new_item))
position = abs(int(position))
shopping_list.insert(position - 1 , new_item)
show_item()
else:
if new_item.upper() == "DONE":
break
elif new_item.upper() == "SHOW":
show_item()
continue
elif new_item.upper() == "HELP":
show_help()
continue
else:
shopping_list.append(new_item)
show_item()
show_help()
add_to_list()
Welcome to stackoverflow. I think your logic statement is wrong, you need and instead of or. Right now all you need for the statement in the parentheses to be true, is that new_item.upper() is at least not one of those three words. It actually can't equate to False since two of the three are always true.
((new_item.upper() != "DONE") or (new_item.upper() != "HELP") or (new_item.upper() != "SHOW"))
If you have for example done the first statement is False ,but the other two are True, adding up to True in or-Statements.
>>> new_item = 'done'
>>> print((new_item.upper() != "DONE") or (new_item.upper() != "HELP") or (new_item.upper() != "SHOW"))
True

loop through python list index

I Have a list, and every time I enter "N" in my program I want the list to print the contents of the next index.
categories = ["Produce", "Meat", "Dairy" ,"Misc"]
...
elif item == "N":
for d in categories[:1]:
d = categories[0]
d += 1
print(d)
I understand that the above code is trying to add an integer to a string and throwing the error. What I haven't been able to figure out is how to increment the index.
I have looked at a few other posts concerning similar problems but it the solutions aren't clicking for me out of context.
Sample output of what it should look like
Add Item to list
Produce
>>Tomatoes
>>Grapes
Meat
>>Hamburger
Dairy
>>
Entire program
def add_item():
exit_list = ["F", "Finished"]
lists = []
start = input("Would you like to add an item to the list? Y/N")
print("Add Item to list")
categories = ["Produce", "Meat", "dairy","snacks/boxed goods", "Cans", "Misc"]
print(categories[0])
while start in ('y', 'Y'):
item = input(">>")
if item in exit_list:
break
elif item == "N":
for d in categories[:1]:
i = 0
i +=1
d = categories[i]
print(d)
elif item:
lists.append(item)
else:
print("ok")
print(lists)
return lists
add_item()
This code will keep track of an index and increment it each time it's used:
i = 0
categories = ["hey", "1", "2" ,"3"]
...
elif item == "N":
print(categories[i])
i += 1
And note that this code will eventually go out of bounds. If you want to wrap around you can do e.g. % len(categories) on i.
Most of the time it is possible, if not better, to avoid using index in Python. One way in your case would be to use a generator on your list. The following code will quit when the user enters q, print the next item when the user enters n, and do nothing if the input is something else.
categories = ["hey", "1", "2" ,"3"]
user_input = None
# Transform your list into an iterator
categories = iter(categories)
# While the user doesn't want to quit
while user_input != "q":
# The user's input is transformed to lower case
user_input = input("What do you want to do ? ").lower()
if user_input == "n":
try:
# We print the next value on the iterator i.e. the next
# value in your list
print(next(categories))
except StopIteration:
# Raised when the iterator reached the end i.e. when we
# have printed all the values in the list
print("You've printed all the list!")
break
One possible output is:
What do you want to do ? hello # Nothing happens here
What do you want to do ? n
hey
What do you want to do ? n
1
What do you want to do ? n
2
What do you want to do ? n
3
What do you want to do ? n
You've printed all the list!
Note that this example is using Python3+
def add_item():
exit_list = ["F", "Finished"]
lists = []
start = input("Would you like to add an item to the list? Y/N")
print("Add Item to list")
categories = ["Produce", "Meat", "dairy","snacks/boxed goods", "Cans", "Misc"]
print(categories[0])
i=0
while start in ('y', 'Y'):
item = input(">>")
if item in exit_list:
break
elif item == "N":
i +=1
print(categories[i])
elif item:
lists.append(item)
else:
print("ok")
print(lists)
return lists
add_item()

Python Nested If

hey im making a simple little grocery list on Python. I know it's not the most eloquent... but I am just learning the syntax right now. I want to get into learning Django.
list = []
def makeList():
listing = True
while listing:
addTo = raw_input("Add to list: ")
if addTo == 'q':
listing = False
else:
list.append(addTo)
def checkList():
if check in list:
print "Yay there is " + check + " here"
else:
print "No you have not added that..."
addAnother = raw_input("Would you like to add it? ")
if str.lower(addAnother) == "yes":
list.append(check)
elif str.lower(addAnother) == "no":
print "Okay then here is your list."
print list
else:
print check
makeList()
check = raw_input("What item: ")
checkList()
I know its pretty complex and hard to understand O_o... but you can see that the nested if statement is not registering when you run it.
What is making it do this? I think that's the best way to ask this.
I've rewritten it a bit to make it cleaner and more Pythonic;
def get_list(prompt, halt):
lst = []
while True:
item = raw_input(prompt)
if item == halt:
return lst
else:
lst.append(item)
def check_list(lst, item):
if item in lst:
print('Yay there is {} here'.format(item))
return True
else:
print('No you have not added {}'.format(item))
return False
def get_yesno(prompt):
while True:
yesno = raw_input(prompt).lower()
if yesno in {'y', 'yes'}:
return True
elif yesno in {'n', 'no'}:
return False
def main():
mylist = get_list('Add to list:', 'q')
check = raw_input('Look for item:')
if not check_list(mylist, check):
if get_yesno('Would you like to add it?'):
mylist.append(check)
print(mylist)
if __name__=="__main__":
main()
Some style tips:
Don't use list as a variable name; it's a built-in function, and you don't want to overwrite it.
Global variables are almost always a bad idea; passing data around explicitly makes it much easier to figure out where bad data is coming from, and makes functions more reusable.
camelCase is generally denigrated; use_underscores for function names instead.
You probably intended to keep going rather than break when you append the new item (or at least print something to indicate success), but the nested if statement works just fine, appends the thing to the list as specified and then the function and program terminate.

Categories