943,571 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Marked Solved
  • Views: 829
  • Python RSS
Sep 21st, 2009
0

Using the OR function

Expand Post »
Hi folks
I have just completed my first programme with help from yourselves.
I cant understand why the code , if x ==1 or 2, wouldn't work in my programme below

python Syntax (Toggle Plain Text)
  1. # Convert C to F or F to C and return with result
  2.  
  3. select = True
  4. while select:
  5. x = int(raw_input ('To convert Celsius to Farenheit, enter 1\nTo convert Farenheit to Celsius, enter 2\n'))
  6. if x == 1 or x == 2:
  7. select = False
  8. else:
  9. print 'Only options are 1 or 2'
  10.  
  11. #Convert C to F
  12. if x == 1:
  13. def Tc_to_Tf ():
  14. Tc = input ("What is the Celsius Temperature ? " )
  15. Tf = 9.0/5.0 * Tc + 32
  16. return Tf
  17. Tf = Tc_to_Tf ()
  18. #.2f instructs Python that placeholder holds float number with 2decimal places.
  19. print 'The temperature is %.2f Degrees Fahrenheit' %(Tf, )
  20.  
  21. #Convert F to C
  22. if x == 2:
  23. def Tf_to_Tc ():
  24. Tf = input ("What is the Fahrenheit Temperature ? " )
  25. Tc = (5.0/9.0)*(Tf - 32)
  26. return Tc
  27. Tc = Tf_to_Tc ()
  28. print 'The temperature is %.2f Degrees Celsius' %(Tc, )

Many thanks in anticipation. I included the whole programme as I would value any comments on my methods.
Graham
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
chico2009 is offline Offline
18 posts
since Sep 2009
Sep 21st, 2009
0

Re: Using the OR function

try

x ==1 or x == 2
your version is always true
x ==1 or 2
since 2 is not 0 so anything or'd with a true value is true
Last edited by gerard4143; Sep 21st, 2009 at 1:34 pm.
Reputation Points: 499
Solved Threads: 366
Postaholic
gerard4143 is offline Offline
2,195 posts
since Jan 2008
Sep 21st, 2009
0

Re: Using the OR function

I would do
Python Syntax (Toggle Plain Text)
  1. if x in [1,2]:
Reputation Points: 64
Solved Threads: 56
Posting Whiz in Training
jice is offline Offline
225 posts
since Oct 2007
Sep 21st, 2009
1

Re: Using the OR function

Click to Expand / Collapse  Quote originally posted by chico2009 ...
Hi folks
I have just completed my first programme with help from yourselves.
I cant understand why the code , if x ==1 or 2, wouldn't work in my programme below

python Syntax (Toggle Plain Text)
  1. # Convert C to F or F to C and return with result
  2.  
  3. select = True
  4. while select:
  5. x = int(raw_input ('To convert Celsius to Farenheit, enter 1\nTo convert Farenheit to Celsius, enter 2\n'))
  6. if x == 1 or x == 2:
  7. select = False
  8. else:
  9. print 'Only options are 1 or 2'
  10.  
  11. #Convert C to F
  12. if x == 1:
  13. def Tc_to_Tf ():
  14. Tc = input ("What is the Celsius Temperature ? " )
  15. Tf = 9.0/5.0 * Tc + 32
  16. return Tf
  17. Tf = Tc_to_Tf ()
  18. #.2f instructs Python that placeholder holds float number with 2decimal places.
  19. print 'The temperature is %.2f Degrees Fahrenheit' %(Tf, )
  20.  
  21. #Convert F to C
  22. if x == 2:
  23. def Tf_to_Tc ():
  24. Tf = input ("What is the Fahrenheit Temperature ? " )
  25. Tc = (5.0/9.0)*(Tf - 32)
  26. return Tc
  27. Tc = Tf_to_Tc ()
  28. print 'The temperature is %.2f Degrees Celsius' %(Tc, )

Many thanks in anticipation. I included the whole programme as I would value any comments on my methods.
Graham
I can't see a problem with the code you've posted!

However if you were using this before:
PYTHON Syntax (Toggle Plain Text)
  1. if x==1 or 2:

Then as gerard has said, the if statement would always evaluate to True...

for example if the user entered '4' as their first choice, the if statement would be evaluated like this:
Evaluating the left hand side of the or statement...
x is not equal to 1, so x==1 evaluates to False (4 is definitely not equal to 1!).

So to the interpreter; after the first part of the evaluation, your if statement looks kinda like this:
"if False or 2:"

Now it evaluates the right hand side of the or statement...
Because '2' is simply a value and not a boolean expression which evaluates to True or False or a boolean variable, this side will always evaluate to True.

What's going on here is at this point the interpreter will see "if False or 2" and will think "2?? Yes, 2 is definitely 2 so for the right hand side of the expression I'll return True!"
so your if statement now looks like this:
"if False or True:"

Now, if you paid any attention in class, you'd know that 'OR' statements (and logical OR gates in electonics) evaluate to/output True if one or more of the sides of the expression (or one or more of the inputs in electronics) evaluates to True.

Therefore the statement "if x==1 or 2:" will always evaluate to True because of the right hand side of your original expression...hence your original problem.

And it doesn't matter what values you put into any of the boolean operations (if, while, or, and, not etc..).
If any side of any of the boolean operations is not a boolean expression or a boolean variable, then it will always evaluate to true...

The only exception is if the value is 0, then the interpreter returns False...Negative values also evaluate to True!

try this:
PYTHON Syntax (Toggle Plain Text)
  1. if 0:
  2. print "0 is True"
  3. else:
  4. print "0 is False"
  5.  
  6. if -1:
  7. print "-1 is True"
  8. else:
  9. print "-1 is False"

Here's a final example:
PYTHON Syntax (Toggle Plain Text)
  1. sentinel=True # a boolean variable...we'll use this in a bit!
  2. value = 24 #and a number
  3.  
  4. # OK, we want to check that value is greater than -1
  5. # and less than or equal to 23...
  6. if value>-1 and 23:# oops, the right hand part of this always evaluates to true
  7. print "1. True" # this gets printed...Doh!
  8. else:
  9. print "1. False" # when we want this!
  10.  
  11. if -1 and value<=23: # Oops, now the left hand part always evaluates to True
  12. print "2. True"
  13. else:
  14. print "2. False" # returns false, but it's still wrong! ^^
  15.  
  16. # What we meant was..
  17. if value>-1 and value<=23: #phew now we're ok. Both sides are valid boolean expresions
  18. print "3. True..."
  19. else:
  20. print "3. False..." # should return false!
  21.  
  22. # Something slightly different:
  23. # Here we're using the value of a variable on one side, but it's safe
  24. # to do so because it's a boolean variable!
  25. # if sentinel is true and value is greater than 23 return true...
  26. if sentinel and value>23: # both sides of the 'or' are boolean
  27. print "4. True...." # Yaay!
  28. else:
  29. print "4. False..."

Hope that clears things up for you once and for all!

Cheers for now,
Jas.
Last edited by JasonHippy; Sep 21st, 2009 at 3:01 pm. Reason: edits
Reputation Points: 590
Solved Threads: 123
Practically a Master Poster
JasonHippy is offline Offline
672 posts
since Jan 2009
Sep 21st, 2009
0

Re: Using the OR function

Defining and then calling the functions under the if() statements serves no purpose. Stripped to the minimum, it would be:
Python Syntax (Toggle Plain Text)
  1. #Convert C to F
  2. if x == 1:
  3. Tc = input ("What is the Celsius Temperature ? " )
  4. print 'The temperature is %.2f Degrees Fahrenheit' % \
  5. (9.0/5.0 * Tc + 32 )
And generally, it would be more along the lines of this to avoid a double compare on "x", although there is nothing wrong with the way you did it.
Python Syntax (Toggle Plain Text)
  1. def Tc_to_Tf ():
  2. Tc = input ("What is the Celsius Temperature ? " )
  3. print 'The temperature is %.2f Degrees Fahrenheit' %(9.0/5.0 * Tc + 32 )
  4.  
  5. def Tf_to_Tc ():
  6. Tf = input ("What is the Fahrenheit Temperature ? " )
  7. print 'The temperature is %.2f Degrees Celsius' %((5.0/9.0)*(Tf - 32) )
  8.  
  9. ##--------------------------------------------------------------------------------------------------
  10. ## "select" is a python function and should not be used as a variable
  11. selection = True
  12. while selection:
  13. x = int(raw_input ('To convert Celsius to Farenheit, enter 1\nTo convert Farenheit to Celsius, enter 2\n'))
  14. if x == 1:
  15. Tc_to_Tf ()
  16. selection = False
  17. elif x == 2:
  18. Tf_to_Tc ()
  19. selection = False
  20. else:
  21. print 'Only options are 1 or 2'
Finally, check your arithmetic.
This subtracts 32 from Tf and then multiplies
(5.0/9.0)*(Tf - 32)

This multiplies Tc by 9/5 and then adds 32
9.0/5.0 * Tc + 32

When in doubt, use parens.
Last edited by woooee; Sep 21st, 2009 at 4:00 pm.
Reputation Points: 741
Solved Threads: 691
Nearly a Posting Maven
woooee is offline Offline
2,302 posts
since Dec 2006
Sep 21st, 2009
0

Re: Using the OR function

Just a littel change from the good suggestion from woooee.
Type a letter
Never trust the user,there are always someone that dont follow instruction well.
If you want to look into this it`s called Exceptions handling
The other choice is to write the menu so that you dont need exceptions handling.

Python Syntax (Toggle Plain Text)
  1. ##--------------------------------------------------------------------------------------------------
  2. ## "select" is a python function and should not be used as a variable
  3. selection = True
  4. while selection:
  5. try:
  6. x = int(raw_input ('To convert Celsius to Farenheit, enter 1\nTo convert Farenheit to Celsius, enter 2\n'))
  7. if x == 1:
  8. Tc_to_Tf ()
  9. selection = False
  10. elif x == 2:
  11. Tf_to_Tc ()
  12. selection = False
  13. else:
  14. print 'Only options are 1 or 2'
  15.  
  16. except:
  17. print 'No letter please'
Last edited by snippsat; Sep 21st, 2009 at 5:31 pm.
Reputation Points: 280
Solved Threads: 278
Master Poster
snippsat is offline Offline
770 posts
since Aug 2008
Sep 21st, 2009
1

Re: Using the OR function

I made an attempt on user friendly data entry with just such a simple temperature converter program, see:
http://www.daniweb.com/forums/showth...595#post992595
Reputation Points: 961
Solved Threads: 211
Nearly a Posting Maven
sneekula is offline Offline
2,413 posts
since Oct 2006
Sep 21st, 2009
0

Re: Using the OR function

Note that you have a similar problem with the arithmetic. In the first function you subtract 32 from t and multiply by 5/9. In c2f you multiply t by 9/5 and then add 32. Perhaps this is the correct way to do it and I'm wrong, in which case appologies to the OP. I just use 9C + 160 = 5F for both conversions and solve for the unknown variable.
Python Syntax (Toggle Plain Text)
  1. def f2c(t):
  2. """given t Fahrenheit return Celsius"""
  3. return 5/9.0 * (t - 32)
  4.  
  5. def c2f(t):
  6. """given t Celsius return Fahrenheit"""
  7. return 9/5.0 * t + 32
Last edited by woooee; Sep 21st, 2009 at 7:57 pm.
Reputation Points: 741
Solved Threads: 691
Nearly a Posting Maven
woooee is offline Offline
2,302 posts
since Dec 2006
Sep 21st, 2009
0

Re: Using the OR function

I always test for -40, it should be the same for both. Snee's approach seems to work correctly.

Or even simpler, 0 C gives 32 F, and 32 F should give 0 C. Something you can do by just looking at the two formulas.
Last edited by vegaseat; Sep 21st, 2009 at 11:09 pm.
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Sep 23rd, 2009
0

Re: Using the OR function

Hi Folks
Thanks to all of you for your help, it is much appreciated
Graham
Reputation Points: 10
Solved Threads: 0
Newbie Poster
chico2009 is offline Offline
18 posts
since Sep 2009

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: wxpython, mysql query
Next Thread in Python Forum Timeline: python unit conversion





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC