would like to say I still feel fairly new too python in general. But I have a movie recommender system that I have been working on, and the way I have it setup is for the user to enter a movie in the console and then it spits out 10 recommendations and ask for another movie.
When a misspelled movie is entered, it gives error message KeyError: 'Goodfellas' and it stops running.
I would like for it to just start the loop over, until the user ends the loop using my break word. Here is my code for reference.
while True:
user_input3 = input('Please enter movie title: ')
if user_input3 == 'done':
break
print(get_input_movie(user_input3))
get_input_movie() is the function I am using to "select" the top 10 movies. Is this possible? Was not able to find much online. Thanks!
Also I am pulling data from a pandas dataframe and using TfidfVectorizer for my similarity.
Look at try-except and continue:
while True:
user_input3 = input('Please enter movie title: ')
if user_input3 == 'done':
break
try:
print(get_input_movie(user_input3))
except KeyError:
continue
To continue after an KeyError exception you should use a try block inside your loop, example:
try:
... # Here goes your code that can result in a KeyError exception
except KeyError:
continue
Related
My code works fine for the salesperson to enter the following criteria until the file is created with one list after being prompted to continue or quit writing the .txt file.
def write_text():
print("Welcome to a Costco Hotel Text Creator.")
print('-'*20) #This serves no purpose but to make the terminal look cleaner.
new_file = input("Enter a new file name: ")
while True: #In the loop where the sales person must enter the following criteria for the new text.
with open(new_file, "w") as f:
f.write(str(input("Enter a member's name: ")))
f.write(str(";")) #Makes it easier and logical to seperate the text by semicolon.
print("The members services are: ")
services = ['Conference','Dinner','Lodging','Membership Renewal']
for service in services:
print(f"{service.capitalize() : <14}") #Capitalizes the string, but not allowed to type exactly.
f.write(str(input("Enter the hotel services. Type exactly shown: ")))
f.write(str(";")) #Makes it easier and logical to seperate the text by semicolon.
f.write(str(input("Enter the price: ")))
f.write(str(";")) #Makes it easier and logical to seperate the text by semicolon.
f.write(str(input("Enter the full date (MM/DD/YYYY): ")))
print('-'*20) #This serves no purpose but to make the terminal look cleaner.
exit = input("Are you done writing the text file? If yes, please type 'yes' to exit")
if exit == 'yes': #If the person typed 'no' then it exits before entering the sales system.
print("Exiting the saved file.")
break
write_text()
My result:
Sammy;Conference;20.00;09/25/2022
Expected result:
Sammy;Conference;20.00;09/25/2022
Johnny;Conference;25.00;09/25/2022
Tony;Conference;30.00;09/25/2022
The list goes on until the user can enter 'yes' to quit. I already have the function that allows reading the text file to sum the revenue per category. Any help and advice is appreciated. Thank you!
When you use with open(...) as .. it closes the file as soon as you exit the code block, and since you are using the w file mode you are overwriting your previous entries every time your loop goes back to the top. You also don't need to wrap input statements with str(). The return value of input will always be a string.
One solution would be to simply put the while true loop inside of the the with open( ) block. You will also need to add a line break at the end of the loop.
def write_text():
print("Welcome to a Costco Hotel Text Creator.")
print('-'*20) # This serves no purpose but to make the terminal look cleaner.
new_file = input("Enter a new file name: ")
with open(new_file, "w") as f:
while True: # In the loop where the sales person must enter the
f.write(input("Enter a member's name: ") + ";")
print("The members services are: ")
services = ['Conference','Dinner','Lodging','Membership Renewal']
for service in services:
print(f"{service.capitalize() : <14}") # Capitalizes the string, but not allowed to type exactly.
f.write(input("Enter the hotel services. Type exactly shown: ") + ";")
f.write(input("Enter the price: ") + ";")
f.write(input("Enter the full date (MM/DD/YYYY): ") + "\n")
print('-'*20)
exit = input("Are you done writing the text file? If yes, please type 'yes' to exit")
if exit == 'yes': # If the person typed 'no' then it exits before entering the sales system.
print("Exiting the saved file.")
break
write_text()
You can also combine the ";" with the text from the input statement to cut back on calls to write. This also makes it look cleaner and more readable as well.
You could also just use the a/append file mode, but closing and reopening the file over and over again doesn't seem like the better option.
Update
If you want to verify that the user input matches a certain word you can do something like this, lets say you want to validate that the user input one of the listed services correctly
print("The members services are: ")
services = ['Conference','Dinner','Lodging','Membership Renewal']
for service in services:
print(f"{service.capitalize() : <14}") # Capitalizes the string, but not allowed to type exactly.
while True:
response = input("Enter the hotel services. Type exactly shown: ")
if response in services:
f.write(response + ';')
break
else:
print("Incorrect entry please try again.")
I would recommend taking this functionality and putting it into a separate function so that you can apply the logic to all of your input statements.
I am a complete python novice, learning how to code using some training videos (which have me using Python 2). In working through one exercise, I generated the below code to create a url dictionary. The video dictated that with the below code, inputting a blank input would lead to the break and end the sequence, but instead, I am taken to the "an error has occurred" message within the except code. This happens regardless of whether I type in an incorrect url or blank. What have I done wrong in the code that has caused this?
Secondly, when I reach the stopproceed function in the code and type in anything other than 1, the loop returns an error message rather than continuing as I had intended.
Any help anyone can provide would be very helpful to a total newb who does not yet have the knowledge to troubleshoot for themselves! Thanks!
while urltoread != '':
try:
urltoread = input("Please enter the next url to crawl ")
if urltoread == "":
print "OK, good loop!"
break
shortname = input("Please input a short name for this url "+ urltoread)
webfile = urllib2.urlopen(urltoread).read()
crawlweblinks[shortname] = webfile
except:
print "An error has occured, dummy",sys.exc_info()[0]
stoporproceed = input("Enter 1 to Stop, or enter anything else to continue")
if stoporproceed ==1 :
print "You got it!\n"
break
else:
print "On we go!\n"
continue
print "This line is inside the while loop"
print "This line is outside the while loop"
print crawlweblinks.keys()
I am trying to code a program that asks the user what the value of a variable is, opens a file, searches for a word, and then checks to see if the number after that word is equal to the user inputted variable, which means I have to get rid of the spaces in between that specific word and the number after it. Unfortunately, I am having some problems with my code and can’t figure out why it will not work. I am sorry if the question I am asking is fairly simple, I haven't coded in python in over a year and am extremely rusty to say the least.
def getword1(prompt):
while True:
filestr1 = input(prompt)
def getword2(prompt):
while True:
filestr2 = input(prompt)
def getword3(prompt):
while True:
filestr3 = input(prompt)
def openfile(prompt, missingfileerror):
"""Opens a file"""
while True:
try:
filestr = input(prompt)
return open(filestr)
except FileNotFoundError:
print(missingfileerror)
uservariable1 = getword1("What is the value of the first variable? If not applicable, please enter 0")
variable1search = ("Word1", uservariable1)
uservariable2 = getword2("What is the value of the second variable? If not applicable, please enter 0")
variable2search = ("Word2", uservariable2)
uservariable3 = getword3("What is the value of the third variable? If not applicable, please enter 0")
variable3search = ("Word3", uservariable3)
file = openfile("Enter the name of the file that contains the variables.")
if uservariable1 == ("0"):
print("No uservariable1")
else:
if variable1search in file:
print("The variable values match.")
else:
print("The variable values do not match.")
if uservariable2 == ("0"):
print("No uservariable2")
else:
if variable2search in file:
print("The variable values match.")
else:
print("The variable values do not match.")
if uservariable3 == ("0"):
print("No uservariable3")
else:
if variable3search in file:
print("The variable values match.")
else:
print("The variable values do not match.")
file.close()
When I run the code in terminal, the code asks my first question, but after I give it an answer, it is stuck in a loop of asking me the same first question over and over again. I also cannot remember how to properly use the .strip() function in this instance. I am searching for a string as my variable because the value of the variable will include a comma, such as 750,000 or 2,000. If I can strip the comma and also maybe a $ sign from the opened file, I would be able to search for an int instead of a string. Thanks for your time!
Remove the while loop from the openfile function. It has no use.
def openfile(prompt, missingfileerror):
"""Opens a file"""
try:
filestr = input(prompt)
return open(filestr)
except FileNotFoundError:
print(missingfileerror)
NB. One other slight problem with your setup is that you should always close files that you've opened. But in this function, you cannot do that anymore, because the code after return will not be executed (if there are no errors).
Another problem is that your code is not DRY (look up the principle). You've duplicated many functions that are almost identical. There is probably a way to do this in 1/3 of the code.
Another problem is that you have added while loops in getword<x> as well, they are not needed either.
To answer your first point, the code is getting stuck asking the first question repeatedly because of your while True in getword1().
There is an also an awful lot wrong with the rest of your code:
Unnecessary while loops everywhere
You don't return anything from your getword() functions, (so uservariable1 etc. will end up as None)
You don't need 3 separate getword() functions, one would do
Actually, you don't really need any, (if you're not going to do any validation), you could just write uservariable1 = input("What is the value ...") etc.
if variable2search in file will never return True - you need to iterate over the file's contents
If you do want to do some user input validation, you could try something like:
def getword(prompt):
while True:
foo = input(prompt)
if <some evaluation criteron here>:
return foo #Return input and break out of while loop
I suggest reading up on while and file access, as a minimum.
Finally, try writing your code in small chunks and proving each bit works before moving on to the next, it's easier to debug that way.
first post here on stack overflow :D
Firstly, at school currently i'm working on a little door entry system and most of the code (only short maybe 30 lines max) is at the school pc - however ive just downloaded Anaconda because i cant get python to download and im using Spyder,
And im trying to sort out a little error im getting so i can fix it at school, pretty much i want to allow the user to enter a code that will be stored into the 'code' variable and then if the 'code' is in the 'database' variable the door will open if not it'll tell you access is denied and loop the program for the next person/next attempt - What i have here to post is the bare minimum of my program but its pretty much the part im struggling with - i have had the program working multiple times with the codes being presented seperately but im looking on making them into a list instead for easier usability - and its a challenge thats been set
while True:
code = input ('Please enter your user ID ')
database = ['001','002','003']
if code == database:
print ('access granted')
else:
print ('Acess denied')
Thats my code so far :D
You want in not ==:
database = ['001','002','003'] # create once
while True:
code = input('Please enter your user ID ')
if code in database:
print ('access granted')
break # break if code is in our list
print ('Access denied') # or print access denied and ask again
You are currently comparing a list to a string as in if "001" == ['001','002','003'] etc.., in tests for membership as in is this element contained in my list.
On another note for small datasets it is irrelevant but when doing a lookup over larger sized datasets using a set is a very efficient way to test for membership:
database = {'001','002','003'} # set literal
If you don't want to break an are not validating forget the while and just ask the user once:
def get_access(db):
code = input('Please enter your user ID ')
if code in db:
print('access granted')
return True
print('Access denied') # or print access denied and ask again
return False
Then to use the function:
database = {'001','002','003'}
granted = get_access(db)
if granted:
.............
If you do want to loop indefinitely you need the else:
while True:
code = input('Please enter your user ID '):
if code in db:
print('access granted')
else:
print('Access denied')
Here is my version:-
database = ('001', '002', '003')
while input('Please enter your user ID ') not in database:
print ('Acess denied')
print ('access granted')
As the other answer said you need to be testing if the input is in (or not in) the database list.
I apologize for my earlier questions as they were vague and difficult to answer. I am still fairly new to programming and am still learning the ins and outs of it all. So please bear with me. Now to the background information. I am using python 3.3.0. I have it loaded onto the Eclipse IDE and that is what I am using to write the code and test it in.
Now to the question: I am trying to learn how to create and use dictionaries. As such my assignment is to create a price matching code that through user interface will not only be able to search through a dictionary for the items (which are the keys and the locations and prices which are the values associated with the keys.) So far I have created a user interface that will run through well enough without any errors however (at least within the IDE) When I run through and input all of the prompts the empty dictionary is not updated and as such I cannot then make a call into the dictionary for the earlier input.
I have the code I have written so far below, and would like if someone could tell me if I am doing things correctly. And if there are any better ways of going about this. I am still learning so more detailed explanations around code jargon would be useful.
print("let's Price match")
decition = input("Are you adding to the price match list?")
if decition == "yes":
pricematchlist = {"Snapple":["Tops",99]}
location = input("Now tell me where you shopped")
item = input("Now what was the item")
price = input("Now how much was the item")
int(price)
pricematchlist[item]=location,price
print(pricematchlist)
else:
pricematchlist = {"Snapple":["Tops",99]}
reply = input("Ok so you want to search up a previous price?")
if reply == "yes":
search = input("What was the item?")
pricematchlist.item(search)
These are a few minor changes. For dictionaries: you are using them correctly.
print("let's Price match")
pricemathlist = {"Snapple":["Tops", 99]} # assign it here
decition = input("Are you adding to the price match list?").lower() #"Yes"-->"yes"
if decition == "yes":
# pricematchlist = {"Snapple":["Tops",99]}
# If this whole code block is called repeatedly, you don't want to reassign it
location = input("Now tell me where you shopped")
item = input("Now what was the item")
price = int(input("Now how much was the item"))
# int(price) does nothing with reassigning price
pricematchlist[item]=location,price
print(pricematchlist)
else:
reply = input("Ok so you want to search up a previous price?").lower()
if reply == "yes":
search = input("What was the item?")
print pricematchlist[search] # easier way of accessing a value