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.
Related
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?
so I am writing program based on this instructions:
Write a function to exit the program, which automatically generates usernames based on the first letter of the first and last name and saves the entries in the dictionary.
For example: Brad Pitt --> bpitt
When the user no longer wants to enter names, write STOP.
Then the program asks him: Do you want to leave the program (yes / no)?
If the user enters "yes", the program ends with the greeting "Thank you for using".
If the user enters "no", the program continues to ask for first and last name.
If the user does not enter "yes" or "no", the program asks him if he really wants to leave the program until he enters one of the mentioned options.
At the end the program displays the contents of the dictionary.
I write this:
dict = {}
while True:
x = input('Enter name and surname: ').lower()
if x != 'STOP':
def name(s):
l = s.split()
new = ''
for i in range(len(l) - 1):
s = l[i]
new += s[0]
new += l[-1]
return new
s = x
print(name(s))
dict[x] = (name(s))
elif x == 'STOP':
a = input('Do you want to leave the program (yes / no)? ')
if a == 'Yes':
print('Thank you for using.')
exit()
elif a == 'No':
if x != 'STOP':
def name(s):
l = s.split()
new = ''
for i in range(len(l) - 1):
s = l[i]
new += s[0]
new += l[-1]
return new
s = x
print(name(s))
else:
a = input('Do you want to leave the program (yes / no)? ')
if a == 'Yes':
print('Thank you for using.')
print(dict)
exit()
elif a == 'No':
x = input('Enter name and surname: ')
if x != 'STOP':
def name(s):
l = s.split()
new = ''
for i in range(len(l) - 1):
s = l[i]
new += s[0]
new += l[-1]
return new
s = x
print(name(s))
At first it worked somehow, but not properly. Now I have made a mistake that I cannot find, because I am totally lost. Is there any easier way to write this code including function?
To answer your basic question, yes there is an easier way to write this code including the function. To begin, lets look at your basic coding style.
Using the variable name dict is a bad idea, since this can and will be confused with the builtin dict structure. This can lead to confusion in understand ing the code as well as subtle errors in execution should the compiler confuser your variable for the builtin function.
The creation of the function name is a great idea, since it splits out this operation into a separately executable and testable piece of code. Embedding thise function within the while loop is not such a good idea since it is unnecessary and I believe reduces the efficiency of the overall python script.
exit is a helper function for for the interactive shell and is not needed in this application
The following is my recommendations for improving your script.
def name(s):
l = s.lower().split()
new = ''
for i in range(len(l) - 1):
s = l[i]
new += s[0]
new += l[-1]
return new
def createDict():
names_dict = dict()
while True:
indata = input('Enter name and surname: ')
if indata.lower() == 'stop':
indata = input('Do you want to leave the program (yes / no)? ')
if indata.lower()[0] == 'y':
print('Thank you for using.')
print(names_dict)
break
else:
nm = name(indata)
print(nm)
names_dict[indata] = nm
To run use createDict()
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")
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
So, I'm trying to make something simple:
shopping_list = []
print("Enter 'done' to stop adding items.")
while True:
new_item = input("> ")
if new_item.lower() == "done":
break
shopping_list.append(new_item)
print("Here's your list:")
for item in shopping_list:
print(item)
Can I, instead of printing this, return the list to another file in order to display that file? I'm new to this and am not sure if that's possible (though everything is possible with code, right?). My goal is to get the list to display, and to be saved so I can access it anytime.
For starters, you'll need to put your code inside a function. Or else, you won't be able to "return" anything.
def foo():
....
return shopping_list
So, your code would be something like:
def foo():
while True:
new_item = input("> ")
if new_item.lower() == "done":
break
shopping_list.append(new_item)
return shopping_list
And, you'd call your function like this:
my_shopping_list = foo()
Once the function returns, my_shopping_list is a list of shopping items, you are free to do as you please.
Also notice I removed the print statements from your loop. Please feel free to add them in if you need them, but I assume that's what you didn't want.
Now, when you say file, I assumed you just meant to somewhere else inside the same program. But if you do indeed want to call this function from another python script, here's what you'll do:
A.py:
def foo():
... # entire function definition here
B.py
import A
my_shopping_list = A.foo()
Create two python scripts. The first one houses your foo function. The second one calls it.
Alternatively, if you want to print your shopping list to an actual file (taking your words literally here), you'd do:
foo():
...
with open('cart.txt', 'w') as f:
for i in shopping_list:
f.write(i + '\n')
This writes your items to a file.
If you mean that you want to run the list to a text file outside of your python script you can do the following:
outfile = open(file, "w")
CODE
outfile.write(shoppping_list)
outfile.close()
You can try this way :
def func():
shopping_list = []
print("Enter 'done' to stop adding items.")
while True:
new_item = input("> ")
if new_item.lower() == "done":
break
shopping_list.append(new_item)
return shopping_list
if __name__ == '__main__':
print("Here's your list:")
outfile = open('test.txt', "w")
shopping_list = func()
# outfile.write(shopping_list)
for item in shopping_list:
# print(item)
outfile.write(item + "\n")
outfile.close()