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()
Related
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
I'm working through the HackerRank 30 days of code and I'm on day 8. The challenge is to take n lines of standard input of the form name phone-number and add these to a dictionary in key : value pairs of the format name : phone-number.
That part was fine.
The next part of the input is an arbitrary number of lines, each containing a name. The task is to print the phone-number of each name or print "Not found" if the name is not in the dictionary.
My trouble lies in determining the end of the input.
The second part of my code is as follows:
counter = 0 # To prevent infinite loop
while 1:
query = input()
if query in phone_book:
print("{}={}".format(query, phone_book[query]))
elif query not in phone_book:
print("Not found")
else:
break
counter += 1
if counter == 10000000:
break
The if and elif statements check whether or not the name is in the dictionary and the else statement is meant to break out of the loop if there is no more input.
However, I get an EOFError: EOF when reading a line error. My code passes all the tests, but I know there should be a better way to deal with the EOF than just setting an upper limit of 10000000 lines (if the input was more than 10000000 lines, I could just increase the counter limit, but I know that is not a good way of doing this).
I've looked at this page: How to find out whether a file is at its `eof`?
But I don't know how to implement this in my code, since the HackerRank input doesn't seem to be in a file from which I can read lines.
How could I manage the EOF issue and eliminate the need for a counter?
NB. The link to the HackerRank page: https://www.hackerrank.com/challenges/30-dictionaries-and-maps/problem
Just iterate over sys.stdin; then there is no need to explicitly check for the end of the input; the iterator will raise StopIteration when it reaches the ed of the input.
import sys
for query in sys.stdin:
query = query.strip()
if query in phone_book:
print("{}={}".format(query, phone_book[query]))
else:
print("Not found")
Seems while learning as I'm going with Python that I'm running into every little roadblock I can.
Even though this is a simply "if" I can't seem to get it to work, and i was wondering if its because my input (pgName) has full stops within the string. e.g com.android.driver.software.
In my example scenario, I will enter com.android.driver.software, what is listed within the Dict.value is com.android.driver.software.7 I thought using the comparison "in" would work in this instance, but it doesn't seem to be handling the logic at all.. What am i doing wrong?
pgName = raw_input("Please enter a package name e.g com.android.driver.software: ")
#while loop that checks user input from pgName to see if it matches any device
#listed in the JSON output and if so printing all the entires for that value.
while True:
try:
jdata = data["result"]["items"][y]["tagValues"]["IdDevicesMap"]["value"]
for device in jdata.values():
if pgName in device:
print jdata[device]
print " "
else:
print 'false'
When i run it everything is false.
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.
I have a directory where csv files are located. The code reads the files and creates histograms based on the data in the files.
I have made this a command prompt code where I can enter the arguments and the code will look through the csv files to see if the arguments I listed are there. I am trying to make it so that an error message comes up when I misspell a command. The following code works if the first argument is spelled correctly and the second is not, but does not display an error message if the first is misspelled and the second is correct. What's wrong?
Example: python untitled14.py "Folder" Are Perimeter DOES NOT DISPLAY ERROR MESSAGE FOR ARE
BUT python untitled14.py "Folder" Perimeter Are DOES DISPLAY ERROR FOR ARE
for x in arguments:
found_match = False
for column in df:
os.chdir(directory)
if x.endswith(column):
found_match = True
#histogram code
continue
else:
pass
if found_match==False:
print files+" " + x + " does not exist"
You have unnecessary things (and some other questionable things) in your loop logic. For example, the three lines continue; else: pass do literal nothing.
The best thing to do would be to refactor your code to call a function that would return True if all the arguments validated. You didn't provide enough code for that, so I would clean the whole thing up with:
for x in arguments:
for column in df:
os.chdir(directory)
if x.endswith(column):
#histogram code
break
else:
print "{0} {1} does not exist".format(files,x)
break #or not, depending on what you want to do
This takes advantage of the somewhat rarely-used for/else to do something if the for loop did not break - which, in your case, is an error.
If you want to really make this re-usable, you should raise an Exception instead of just printing on an error.