Replacement value not working? - python

So I've got a try/except block set up, which will go through a database dependent on certain conditions:
try:
for searchnumber in itertools.count(0):
print searchnumber
c.execute("""SELECT words from searchterms where onstate = 1 AND progid = %d;""") % searchnumber
searchterms = (c.fetchall())
searchterms = [",".join(x) for x in searchterms]
print searchterms
except:
pass
For some reason, it isn't iterating on progid, in fact, it isn't even getting the first value assigned to it (0). Why would this be? As far as I know, %d should be replaced by the integer value of searchnumber

You're probably hiding a TypeError because you're trying to use the % operator on whatever object or value is equivalent to c.execute("string"). You might've caught it if you hadn't hidden all errors with the bare except. You'll note this is a specific antipattern in the official Python Dos and Don'ts page.

Never use except: pass, it hides information.
The information it's currently hiding is probably a failure from this code:
c.execute("""SELECT words from searchterms where onstate = 1 AND progid = %d;""") % searchnumber

Related

Please help me better understand this one "except"conditional line

I'm about a couple weeks into learning Python.
With the guidance of user:' Lost' here on Stackoverflow I was able to figure out how to build a simple decoder program. He suggested a code and I changed a few things but what was important for me was that I understood what was happening. I understand 97% of this code except for the except: i += 1 line in the decode(). As of now the code works, but I want to understand that line.
So basically this code unscrambles an encrypted word based on a specific criteria. You can enter this sample encrypted word to try it out. "0C1gA2uiT3hj3S" the answer should be "CATS"
I tried replacing the except: i += 1 with a Value Error because I have never seen a Try/Except conditional that just had an operational and no Error clause. But replacing it with Value Error created a never ending loop.
My question is what is the purpose of writing the except: i += 1 as it is.
'Lost' if you're there could you answer this question. Sorry, about the old thread
def unscramble(elist):
answer = []
i = 0
while i <= len(elist):
try:
if int(elist[i]) > -1:
i = i + int(elist[i]) + 1
answer.append(elist[i])
except:
i += 1
return "".join(answer)
def boom():
eword = input("paste in your encrypted message here >> ")
elist = list(eword)
answer = unscramble(elist)
print (answer)
clear()
boom()
The purpose is to advance i by one, skipping the current character in case the cast to int fails, i.e. if elist[i] is not a digit.
There are a couple of errors, than can occur inside the try-Block:
i is out of index, because the while loop runs one index to far.
elist[i] is not a number, which leads to an ValueError
i = i + int(elist[i]) + 1 gets to big, and the next index access leads also to an IndexError
In either way, the except-clause will ignore the next character. And the loop goes on.
An correct implementation wouldn't need any exceptions:
def unscramble(elist):
answer = []
i = 0
while i < len(elist):
i += int(elist[i]) + 1
answer.append(elist[i])
i += 1
return "".join(answer)

List Comprehension python?

I have a function like this:
for product in responseSoup.findAll("offersummary"):
try:
if product.lowestnewprice.formattedprice != None:
price.append(product.lowestnewprice.formattedprice.text)
else:
price.append("")
except:
price.append("")
I am confused how to do the if/else statement with the try/except block? Will list comprehension speed up efficiency?
[product.lowestnewprice.formattedprice for product in responseSoup.findAll("offersummary")]
Here is a very readable solution:
prices = []
for product in responseSoup.findAll("offersummary"):
price = product.get(lowestnewprice, {}).get(formattedprice, {}).get(text)
if price is not None:
prices.append(price)
else:
prices.append('')
If you really don't care about readability, here's a very atrocious looking one-liner:
price = [''
if product.get(lowestnewprice, {}).get(formattedprice, {}).get(
text) is None else
product.lowestnewprice.formattedprice.text
for product in responseSoup.findAll("offersummary")]
They do essentially the same thing, but, in my opinion, the more readable solution is better.
EDIT
I just figured out a much better one-liner:
price = [product.get(lowestnewprice,{}).get(formattedprice,{}).get(text) or ''
for product in responseSoup.findAll("offersummary")]
It's still less readable than the "very readable" solution, but it is not too bad. Now the decision really comes down to a matter of your preference.
try and except blocks are used to see if the following code works. If not and it matches the given error, run that block of code. Else, run the other line of code. For example:
try:
m = raw_input("Please enter an integer")
n = int(m)
except ValueError:
print "Invalid number"
else:
print n
So, the program attempts to assign m the input from the user. Then n is assigned the input as an integer. Now the error chosen is ValueError since if m is a string, the conversion to n will raise that error. If it does, then it does the code in the except block, which is to print "Invalid number". If the conversion is successful, then print n.
Now with your program, you will try the if and else block. If the code doesn't work and it raises the error given in the except block, it will do price.append(""). Else, it will run the code in the else block, which you don't have. You need the else: to work in your try/except block for it to work including a specified error after the keyword except in your except statement.

python requests.get() InvalidSchema error

I'm incredibly new to python, and i'm trying to write something to get the first result returned from Google' "I'm feeling lucky" button. I have a list of 100 items I need it to get urls for. Here's what i have:
import requests
with open('2012.txt') as f:
lines = f.readlines()
for i in range(0, 100):
temp1 = "r'http://www.google.com/search?q=\""
temp2 = "\"&btnI'"
temp3 = lines[i]
temp3 = temp3[:-1]
temp4 = temp1+temp3+temp2
print temp4
var = requests.get(temp4)
print var.url
Now if I print the value in temp4 and paste it into requests.get(), it works as I want it to. However, I get error's every time I try to pass temp4 in, instead of a hard-coded string.
Specifically, I guess you're getting:
requests.exceptions.InvalidSchema: No connection adapters were found for 'r'http://www.google.com/search?q="foo"&btnI''
(except with something else in lieu of foo:-) -- please post exceptions as part of your Q, why make us guess or need to reproduce?!
The problem is obviously that leading r' which does indeed make the string into an invalid schema (the trailing ' doesn't help either).
So, try instead something like:
temp1 = 'http://www.google.com/search?q="'
temp2 = '"&btnI'
and things should go better... specifically, when I do that (still with 'foo' in lieu of a real temp3), I get
http://en.wikipedia.org/wiki/Foobar
which seems to make sense as the top search result for "foo"!-)

Run Time Error Exited with error status 1

The problem is this :
I tried to solve it and I think I did too but when I mailed it for evaluation it says
We have tested your solution, and while doing so we unfortunately
discovered the following error:
Run Time Error
Exited with error status 1
Here is my code :
import re
import sys
def fun():
for ind in ratio:
max_num = ratio_list[0]
if ratio[ind] == max_num:
print ind
ratio_list.remove(ratio_list[0])
hits = []
song = []
n,m = raw_input().split(' ',1)
for i in range(0,int(n)):
h,n = raw_input().split(" ",1)
is_number = isinstance( int(h), int )
is_string = len(n)<=30 and bool(re.match('[a-z_0-9]+$', n))
if not(is_number and is_string):
sys.exit("Error");
hits.append(int(h))
song.append(n)
ratio = {}
ratio_list = []
f_of_i = hits[0]
counter = 1
index = 0
for hit in hits:
ratio_list.append(hit*counter)
ratio[song[index]] = hit*counter
index = index +1
counter = counter +1
ratio_list.sort()
ratio_list.reverse()
for j in range(0,int(m)):
fun()
What am I doing wrong ? I am curious why the solution is unacceptable killing me.
I suspect you're hitting
sys.exit("Error");
As explained in the documentation:
Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1.
Might be worth relaxing your input validation a little? Right now it's so strict it would reject inputs that to me appear within the spec (say if there were two spaces between the play count and the song title).
Another possibility is that your code raises an exception. On my machine this also results in an exit code of 1.
Finally, while not a bug, I think the way you reuse the variable called n is questionable style.

Can't get my loop & match to append to correct list

I´m experiencing problems with my code.
I can´t get it to append to the list not_found as well as it loops twice for some reason.
Can anyone point me in the right direction? The match works for my_track, but it doesn't when it doesn't match.
# coding: utf-8
#!/usr/bin/env python
import spotimeta
import sys
import time
my_tracks = raw_input("Please enter a sentence: ").title().split()
playlist = []
real_playlist = []
not_found = []
def check_track(track_name, my_track, track_href):
if track_name == my_track:
playlist.append(track_href)
return 1
# make sure the user does not input a single word as input
if (len(my_tracks) > 1):
path = my_tracks[1]
else:
sys.exit("Invalid input, please enter a sentence.")
# let's search
for my_track in my_tracks:
match = 0
print "Searching for '%s'\n" % (my_track),
data = spotimeta.search_track(my_track)
for result in data['result']:
if not match == 1:
try:
match = check_track(result["name"],my_track,result["href"])
except Exception, e:
error = "not available"
else:
if data['total_results'] > 0:
not_found.append(my_track)
You should try debugging it. One of the simplest ways of debugging is add the lines:
import pdb
pdb.set_trace()
Then when you run the script it will stop at the set_trace line in the debugger.
Check out http://docs.python.org/library/pdb.html for more information.
From my understanding you're trying to do something like:
for my_track in my_tracks:
print "Searching for '%s'\n" % (my_track),
data = spotimeta.search_track(my_track)
for result in data['result']:
if result['name'] == my_track:
playlist.append(result['href'])
elif data['total_results'] > 0:
not_found.append(my_track)
Will this more or less work for you?
Please help me to understand.
Right off the bat, I'm noticing two things.
First, you're checking data['total_results'] a bit late; if the total results value is greater than zero (wait, what?), then you want to add it to the list immediately and move on without parsing the data. I would, after the call from spotimeta.search_track(), check to see if this is the data you don't want (then subsequently add it into the list).
Second, I'm confused about the intention of your for loop. If you're going through it to only find one item, then you can use the in statement (my_track in result).

Categories

Resources