[Tutor] boolean or input trouble
D-Man
dsh8290@rit.edu
Tue, 13 Mar 2001 19:10:02 -0500
On Tue, Mar 13, 2001 at 09:30:40PM +0100, W.W. van den Broek wrote:
| #! /usr/bin/python
| #We gaan is de twee hoofdkenmerken van een dsm depressie diagnose vaststellen
| x = input ("Welk getal is het antwoord op vraag 234 van de SADS?")
| y = input ("Welk getal is het antwoord op vraag 326 van de SADS?")
| if (x > 4) or (y > 4):
| print " Er kan sprake zijn van een depressieve stoornis"
| else:
| print " Er kan geen sprake zijn van een depressie"
|
The only obvious problem I notice is that you use 'input'. Also there
is no try-except block wrapping the input. Suppose I were to type in
'a'? Or 'open( "some_file_to_trash" , "w" )" ? Both would cause the
input function to either fail, or do some unexpected bad things. Try
this instead:
#!/usr/bin/env python
good_input = 0
while not good_input :
try :
x = int( raw_input( "Welk ..." ) )
good_input = 1
except ValueError , error :
print "You didn't enter a valid number, please enter a valid number"
good_input = 0
while not good_input :
try :
y = int( raw_input( "Welk ..." ) )
good_input = 1
except ValueError , error :
print "You didn't enter a valid number, please enter a valid number"
if (x > 4) or (y > 4):
print " Er kan sprake zijn van een depressieve stoornis"
else:
print " Er kan geen sprake zijn van een depressie"
Using raw_input will prevent the interpreter from executing arbitrary
(and possibly harmful!) expressions. Using int() to convert the
string to an integer inside the try-except blocks will allow you to
robustly handle any weird data the users may throw at your program.
HTH,
-D