A certainl part of an if() structure never gets executed.

  • Thread starter Íéêüëáïò Êïýñáò
  • Start date
Í

Íéêüëáïò Êïýñáò

Code:
if not re.search( '=', name ) and not re.search( '=', month ) and notre.search( '=', year ):
cur.execute( '''SELECT * FROM works WHERE clientsID = (SELECT id FROM clients WHERE name = %s) and MONTH(lastvisit) = %s and YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', (name, month, year) )
elif not re.search( '=', month ) and not re.search( '=', year ):
cur.execute( '''SELECT * FROM works WHERE MONTH(lastvisit) = %s and YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', (month, year) )
elif not re.search( '=', year ):
cur.execute( '''SELECT * FROM works WHERE YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', year )
else:
print('''<h2>Ðþò íá ãßíåé áíáæÞôçóç áöïý äåí åðÝëåîåò ïýôå ðåëÜôç ïýôå ìÞíá Þ ôïõëÜ÷éóôïí ôï Ýôïò?''')
print( '''<meta http-equiv="REFRESH" content="5;/cgi-bin/pelatologio..py">''' )
sys.exit(0)

data = cur.fetchall()
	
hits = money = 0
	
for row in data:
hits += 1
money = money + row[2]

.......
.......
selects based on either name, month, year or all of them


The above if structure works correctly *only* if the user sumbits by form:

name, month, year
or
month, year

If, he just enter a year in the form and sumbit then, i get no error, but no results displayed back.

Any ideas as to why this might happen?
 
M

Mark Lawrence

Code:
		if not re.search( '=', name ) and not re.search( '=', month ) and not re.search( '=', year ):
			cur.execute( '''SELECT * FROM works WHERE clientsID = (SELECT id FROM clients WHERE name = %s) and MONTH(lastvisit) = %s and YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', (name, month, year) )
		elif not re.search( '=', month ) and not re.search( '=', year ):
			cur.execute( '''SELECT * FROM works WHERE MONTH(lastvisit) = %s and YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', (month, year) )
		elif not re.search( '=', year ):
			cur.execute( '''SELECT * FROM works WHERE YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', year )
		else:
			print('''<h2>Ðþò íá ãßíåé áíáæÞôçóç áöïý äåí åðÝëåîåò ïýôå ðåëÜôç ïýôå ìÞíá Þ ôïõëÜ÷éóôïí ôï Ýôïò?''')
			print( '''<meta http-equiv="REFRESH" content="5;/cgi-bin/pelatologio.py">''' )
			sys.exit(0)

		data = cur.fetchall()

		hits = money = 0

		for row in data:
			hits += 1
			money = money + row[2]

......
......
selects based on either name, month, year or all of them


The above if structure works correctly *only* if the user sumbits by form:

name, month, year
or
month, year

If, he just enter a year in the form and sumbit then, i get no error, but no results displayed back.

Any ideas as to why this might happen?

On the grounds that you can't possibly have made a coding error I'd say
this is a Python bug which should be reported here bugs.python.org.

--
"Steve is going for the pink ball - and for those of you who are
watching in black and white, the pink is next to the green." Snooker
commentator 'Whispering' Ted Lowe.

Mark Lawrence
 
M

MRAB

Code:
		if not re.search( '=', name ) and not re.search( '=', month ) and not re.search( '=', year ):
			cur.execute( '''SELECT * FROM works WHERE clientsID = (SELECT id FROM clients WHERE name = %s) and MONTH(lastvisit) = %s and YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', (name, month, year) )
		elif not re.search( '=', month ) and not re.search( '=', year ):
			cur.execute( '''SELECT * FROM works WHERE MONTH(lastvisit) = %s and YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', (month, year) )
		elif not re.search( '=', year ):
			cur.execute( '''SELECT * FROM works WHERE YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', year )
		else:
			print('''<h2>Ðþò íá ãßíåé áíáæÞôçóç áöïý äåí åðÝëåîåò ïýôå ðåëÜôç ïýôå ìÞíá Þ ôïõëÜ÷éóôïí ôï Ýôïò?''')
			print( '''<meta http-equiv="REFRESH" content="5;/cgi-bin/pelatologio.py">''' )
			sys.exit(0)

		data = cur.fetchall()

		hits = money = 0

		for row in data:
			hits += 1
			money = money + row[2]

......
......
selects based on either name, month, year or all of them


The above if structure works correctly *only* if the user sumbits by form:

name, month, year
or
month, year

If, he just enter a year in the form and sumbit then, i get no error, but no results displayed back.

Any ideas as to why this might happen?
What are the values of 'name', 'month' and 'year' in each of the cases?
Printing out ascii(name), ascii(month) and ascii(year), will be helpful.

Then try stepping through those lines in your head.
 
R

Rick Johnson

Umm, "Niko". (Superfluous Unicode Removed)

The code you have written is very difficult to read because you are doing too much inside the conditional and you're repeating things!. For starters you could compile those regexps and re-use them:

## BEGIN SESSION ##
py> import re
py> s = """\
.... hello.
.... I'm a little
.... multiline
.... string"""
....
py> repr(s)
"hello.\nI'm a little \nmultiline\nstring"
py> prog = re.compile(r'e\s*\n')
py> prog.findall(s)
['e \n', 'e\n']
## END SESSSION ##

Secondly you could wield the power of the built in function "all" to make your first "run-on-condition" a bit nicer:

## BEGIN SESSION ##
py> lst = [True, True, False]
py> all(lst)
False
py> if all([True, True, False, True]):
.... print('Doing something')
.... else:
.... print("Shucks. I suppose i'll just twiddle my thumbs!")
....
Shucks. I suppose i'll just twiddle my thumbs!
## END SESSION ##

Lastly, you should write some helper functions to format the command (OUTSIDE OF THE CONDITIONAL) so you can shorten those atrociously long lines!
 
A

alex23

Code:
[/QUOTE]

http://pythonconquerstheuniverse.wordpress.com/2009/09/10/debugging-in-python/

"Hey, I have a problem, here is my code, you work it out" is not a
valid debugging technique.
 
N

nagia.retsina

Τη ΤετάÏτη, 12 Ιουνίου 2013 1:43:21 Ï€.μ. UTC+3, ο χÏήστης MRAB έγÏαψε:
Code:
[/QUOTE]
[QUOTE]
if not re.search( '=', name ) and not re.search( '=', month ) andnot re.search( '=', year ):[/QUOTE]
[QUOTE]
cur.execute( '''SELECT * FROM works WHERE clientsID = (SELECT id FROM clients WHERE name = %s) and MONTH(lastvisit) = %s and YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', (name, month, year) )[/QUOTE]
[QUOTE]
elif not re.search( '=', month ) and not re.search( '=', year ):[/QUOTE]
[QUOTE]
cur.execute( '''SELECT * FROM works WHERE MONTH(lastvisit) = %s and YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', (month, year) )[/QUOTE]
[QUOTE]
elif not re.search( '=', year ):[/QUOTE]
[QUOTE]
cur.execute( '''SELECT * FROM works WHERE YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', year ) 

			print('''<h2>Πώς να γίνει αναζήτηση Î±Ï†Î¿Ï Î´ÎµÎ½ επέλεξες οÏτε πελάτη οÏτε μήνα ή τουλάχιστον το έτος?''')[/QUOTE]
[QUOTE]
print( '''<meta http-equiv="REFRESH" content="5;/cgi-bin/pelatologio.py">''' ) 


		data = cur.fetchall() 

		hits = money = 0 

		for row in data:[/QUOTE]
[QUOTE]
hits += 1[/QUOTE]
[QUOTE]
money = money + row[2] [QUOTE]
......[/QUOTE]
[QUOTE]
......[/QUOTE]

selects based on either name, month, year or all of them [QUOTE]

The above if structure works correctly *only* if the user sumbits by form:
name, month, year

month, year
If, he just enter a year in the form and sumbit then, i get no error, but no results displayed back.
Any ideas as to why this might happen?

What are the values of 'name', 'month' and 'year' in each of the cases?

Printing out ascii(name), ascii(month) and ascii(year), will be helpful.



Then try stepping through those lines in your head.[/QUOTE]

i hav epribted all values of those variables and they are all correct.
i just dont see why ti fails to enter the specific if case.

is there a shorter and more clear way to write this?
i didnt understood what Rick trie to told me.

can you help me write it more easily?
 
R

Rick Johnson

is there a shorter and more clear way to write this?
i didnt understood what Rick trie to told me.

My example included verbatim copies of interactive sessions within the Python command line. You might understand them better if you open the Python command line and type each command in one-by-one. Here is an algoritm that explains the process:

open_command_window()
whilst learning or debugging:
type_command()
press_enter()
observe_output()
if self.badder.is_full:
take_potty_break()
close_command_window()

Utilizing the power of interactive sessions, for learning and debugging, should be a cornerstone fundamental of your programming "work-flow" when writing code in an interpreted language like Python.
 
M

MRAB

Τη ΤετάÏτη, 12 Ιουνίου 2013 1:43:21 Ï€.μ. UTC+3, ο χÏήστης MRAB έγÏαψε:
On 11/06/2013 21:20, Îικόλαος ΚοÏÏας wrote: [snip]

What are the values of 'name', 'month' and 'year' in each of the cases?
Printing out ascii(name), ascii(month) and ascii(year), will be helpful.

Then try stepping through those lines in your head.

i hav epribted all values of those variables and they are all correct.
i just dont see why ti fails to enter the specific if case.

is there a shorter and more clear way to write this?
i didnt understood what Rick trie to told me.

can you help me write it more easily?
What are the values that are printed?
 
A

alex23

Utilizing the power of interactive sessions, for learning and debugging,
should be a cornerstone fundamental of your programming "work-flow" when
writing code in an interpreted language like Python.

Unfortunately with Ferrous, the process is more like:

if error:
post_to_python_list()
while error:
if time_elapsed == one_hour:
bump_post()
 
C

Cameron Simpson

| > What are the values of 'name', 'month' and 'year' in each of the cases?
| >
| > Printing out ascii(name), ascii(month) and ascii(year), will be helpful.
| >
| > Then try stepping through those lines in your head.
|
| i hav epribted all values of those variables and they are all correct.
| i just dont see why ti fails to enter the specific if case.

Gah!
_Show_ us the values!
And _specify_ which part of the if-statement should run.
 
C

Chris Angelico

Unfortunately with Ferrous, the process is more like:

if error:
post_to_python_list()
while error:
if time_elapsed == one_hour:
bump_post()

Not quite.

while people_paying_me_money():
while not error:
code_per_rfc_2795()
while error:
post_to_python_list()
while sucker_count < 3:
if time_elapsed >= one_hour: # level-triggered, not edge-triggered
bump_post()

You have to include the coding phase. How else would he get into an error state?

ChrisA
 
R

Rick Johnson

Via copy & paste.

Now that's more like it Alex!

If you move to my side the Python world could experience a cataclysmic polar shift. Which may not necessarily be a bad thing, however, I've noticed that these folks stress easily -- hmm, maybe their undergarments are just tootight???
 
R

Rick Johnson

Now that's more like it Alex!

Opps, it seems i falsely interpreted Chris's post as directed towards me, and then with that false assumption in mind i went on to falsely interpreted reply to Chris. Folks if your not already ignoring me this might be a good time to start <|:eek:).

At this time i think we should just forget about my mistake and and return to the request for internship in his new "open sore"sss project.
 
M

Michael Torrie

Code:
		if not re.search( '=', name ) and not re.search( '=', month ) and not re.search( '=', year ):[/QUOTE]

What do each of these functions return?  When you print out
re.search('=', name) what happens?

When you're debugging you should print each of these out.  Also make a
standalone program (NOT A CGI SCRIPT) for debugging.  You can test
various inputs by simply going:

name = "My test name"
month = "Thirteenth"
year = "2013"

One thing I do is to make my code into functions and then at the bottom
of each script I have something like this:

if __name__ == "__main__":
# run some test code here
# or alternatively do the CGI stuff depending on what
# mode you're in.

You could even put in debugging flags (apologies to Rick who recently
raved against needing to resort to this sort of thing).

Consider this code:
---------- do_something.py -----------------------
debug = False

def do_something(name, month, year):
if debug:
print re.re.search( '=', name )
print not re.search( '=', month )
print not re.search( '=', year )
if not re.search( '=', name ) and not re.search( '=', month ) and
not re.search( '=', year ):
print "gonna do query"
# code follows

if __name__ == "__main__"
debug = True
do_something("bob", None, 2012)
do_something(None, None, None)
do_something("big", "Octember", 2067)
# other use cases here

-------------------------------------------------

Then in your cgi script itself, you just do this:
----------- my_cgi_script.py -------------------
import do_something

# handle cgi stuff
# get name, month year
dosomething.dosomething(name, month, year)
------------------------------------------------
Now to test your code you can just run the module directly with python,
and once you've got it working, the CGI will also work, since it pulls
in the same code.

If this concept is new to you, I strongly urge you to stop development
and read through a good python tutorial or get a good python book.
 
M

Michael Torrie

----------- my_cgi_script.py -------------------
import do_something

# handle cgi stuff
# get name, month year
dosomething.dosomething(name, month, year)

Make that do_something.do_something
 
A

alex23

It seems silly to fire up a regular expression compiler to look for a
single character.
    if name.find('=') < 0 and month.find('=') < 0 and year.find('=') < 0:

If truthiness is the only concern, I prefer using `in`:

if '=' in name and '=' in month ...
 
C

Chris Angelico

First of all i have changed the code to the following because using a
regex
to detect a single char was an overkill.

if '=' not in name and '=' not in month and '=' not in year:

It'd be courteous to acknowledge those who made that suggestion, most
notably alex23 who posted it in almost that exact form.

ChrisA
 
D

Denis McMahon

The above if structure works correctly *only* if the user sumbits by
form:

name, month, year or month, year

If, he just enter a year in the form and sumbit then, i get no error,
but no results displayed back.

Any ideas as to why this might happen?

Yes, I know exactly why this is happening.

It is for one of two reasons. You may determine which one using the
following secret code which I stole from the illuminati in 1836:

import random

reason = { 1: "Input data is not as expected by coder", 2: "Flow control
logic not performing as coder expects", 3: "Badger Badger Badger Badger
Badger Badger Badger Badger Mushroom", 4: "Please try again", 5:
"Snaaaaake", 6: "Grumpy cat says fix your own damn code", 7: "I'll be
back" }

print reason[ random.choice( reason.keys() ) ]

Note - this only has a small chance of actually doing what you want (ie
giving a possibly accurate answer), but it sounds as if that's a level of
precision you're used to working with anyway.

On a slightly more serious note, if you can't apply yourself to debugging
a case of "the program logic isn't doing what I expect" for some value of
program logic that you coded, that may be a hint that:

a) you don't actually understand what the program logic is doing

b) you shouldn't be writing logic so complex that you can't see how to
debug it

c) your logic is overly convoluted and complex

d) all of the above

So perhaps you need to scrub the logic altogether, and start again taking
smaller steps.

You could also perhaps do with a lesson in De Morgan's theorem:

not a and not b and not c = not ( a or b or c )

not a or not b or not c = not ( a and b and c )

and sometimes the alternative form is easier to understand

Now, looking at your code here are two important questions:

(1) What is the initial values of name, month and year?
(2) Which block is actually being executed?

Bear in mind that if a branch other than one you expect to be executed is
executing, the fail condition might not be what you think it is.
Specifically, is it possible that the code is executing the wrong branch
and tripping up when it tries to generate or perhaps execute the sql
statement empty strings, or just not getting any result from the sql
because of the empty strings?

Hint - take the code from the current file, apply a liberal smattering of
print statements, and test it for various values of month, year and name.

def test(name, month, year):
print "name, month, year ::", name, month, year
if not re.search( '=', name ) and not re.search( '=', month ) and
not re.search( '=', year ):
print "branch 1"
elif not re.search( '=', month ) and not re.search( '=', year ):
print "branch 2"
elif not re.search( '=', year ):
print "branch 3"
else:
print "branch 4"

# testing logic for 8 possible input conditions

test("=", "=", "=")
test("=", "=", "x")
test("=", "x", "=")
test("=", "x", "x")
test("x", "=", "=")
test("x", "=", "x")
test("x", "x", "=")
test("x", "x", "x")
 
Î

Îικόλαος ΚοÏÏας

The above if structure works correctly *only* if the user sumbits by
form:

name, month, year or month, year

If, he just enter a year in the form and sumbit then, i get no error,
but no results displayed back.

Any ideas as to why this might happen?

Yes, I know exactly why this is happening.

It is for one of two reasons. You may determine which one using the
following secret code which I stole from the illuminati in 1836:

import random

reason = { 1: "Input data is not as expected by coder", 2: "Flow control
logic not performing as coder expects", 3: "Badger Badger Badger Badger
Badger Badger Badger Badger Mushroom", 4: "Please try again", 5:
"Snaaaaake", 6: "Grumpy cat says fix your own damn code", 7: "I'll be
back" }

print reason[ random.choice( reason.keys() ) ]

Note - this only has a small chance of actually doing what you want (ie
giving a possibly accurate answer), but it sounds as if that's a level of
precision you're used to working with anyway.

On a slightly more serious note, if you can't apply yourself to debugging
a case of "the program logic isn't doing what I expect" for some value of
program logic that you coded, that may be a hint that:

a) you don't actually understand what the program logic is doing

b) you shouldn't be writing logic so complex that you can't see how to
debug it

c) your logic is overly convoluted and complex

d) all of the above

So perhaps you need to scrub the logic altogether, and start again taking
smaller steps.

You could also perhaps do with a lesson in De Morgan's theorem:

not a and not b and not c = not ( a or b or c )

not a or not b or not c = not ( a and b and c )

and sometimes the alternative form is easier to understand

Now, looking at your code here are two important questions:

(1) What is the initial values of name, month and year?
(2) Which block is actually being executed?

Bear in mind that if a branch other than one you expect to be executed is
executing, the fail condition might not be what you think it is.
Specifically, is it possible that the code is executing the wrong branch
and tripping up when it tries to generate or perhaps execute the sql
statement empty strings, or just not getting any result from the sql
because of the empty strings?

Hint - take the code from the current file, apply a liberal smattering of
print statements, and test it for various values of month, year and name.

def test(name, month, year):
print "name, month, year ::", name, month, year
if not re.search( '=', name ) and not re.search( '=', month ) and
not re.search( '=', year ):
print "branch 1"
elif not re.search( '=', month ) and not re.search( '=', year ):
print "branch 2"
elif not re.search( '=', year ):
print "branch 3"
else:
print "branch 4"

# testing logic for 8 possible input conditions

test("=", "=", "=")
test("=", "=", "x")
test("=", "x", "=")
test("=", "x", "x")
test("x", "=", "=")
test("x", "=", "x")
test("x", "x", "=")
test("x", "x", "x")

Thank you but i already foudn out what the problem was, i just don't
known how to fix it. Here is is again:


Here is the defines of those variables. as you can see are all tuples

# populate names, months, years
names.add( '==========' )
months = ( '==========', 'ΙανουάÏιος', 'ΦεβÏουάÏιος', 'ΜάÏτιος',
'ΑπÏίλιος', 'Μάϊος', 'ΙοÏνιος',
'ΙοÏλιος', 'ΑÏγουστος', 'ΣεπτέμβÏιος', 'ΟκτώβÏιος',
'ÎοέμβÏιος',
'ΔεκέμβÏιος' )
years = ( '==========', 2010, 2011, 2012, 2013 )


========================

i used print( name, month, year ) and noticed that all values
returned as expected when selected fro drop-down menus and submitted.

But when it comes to select '==========' from month instead of
'==========' to be submitted a zero gets submitted and i think the
problem is the way i'm filling up months into the drop down menu which is:


for i, month in enumerate(months):
print('<option value="%s"> %s </option>' % (i, month) )


the if case does not execute because of the way it checks for None entry
which is: elif '=' not in year:

but if enumerate yields 0 instead of '==========' then elif '=' not in
year of course fails.

So, i must tell:

for i, month in enumerate(months):
print('<option value="%s"> %s </option>' % (i, month) )

to somehow return '==========' instead of 0 but don't know how.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top