| | |
Using the OR function
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved |
•
•
Join Date: Sep 2009
Posts: 18
Reputation:
Solved Threads: 0
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
Many thanks in anticipation. I included the whole programme as I would value any comments on my methods.
Graham
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)
# Convert C to F or F to C and return with result select = True while select: x = int(raw_input ('To convert Celsius to Farenheit, enter 1\nTo convert Farenheit to Celsius, enter 2\n')) if x == 1 or x == 2: select = False else: print 'Only options are 1 or 2' #Convert C to F if x == 1: def Tc_to_Tf (): Tc = input ("What is the Celsius Temperature ? " ) Tf = 9.0/5.0 * Tc + 32 return Tf Tf = Tc_to_Tf () #.2f instructs Python that placeholder holds float number with 2decimal places. print 'The temperature is %.2f Degrees Fahrenheit' %(Tf, ) #Convert F to C if x == 2: def Tf_to_Tc (): Tf = input ("What is the Fahrenheit Temperature ? " ) Tc = (5.0/9.0)*(Tf - 32) return Tc Tc = Tf_to_Tc () 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
•
•
Join Date: Oct 2007
Posts: 149
Reputation:
Solved Threads: 38
I would do
Python Syntax (Toggle Plain Text)
if x in [1,2]:
•
•
•
•
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)
# Convert C to F or F to C and return with result select = True while select: x = int(raw_input ('To convert Celsius to Farenheit, enter 1\nTo convert Farenheit to Celsius, enter 2\n')) if x == 1 or x == 2: select = False else: print 'Only options are 1 or 2' #Convert C to F if x == 1: def Tc_to_Tf (): Tc = input ("What is the Celsius Temperature ? " ) Tf = 9.0/5.0 * Tc + 32 return Tf Tf = Tc_to_Tf () #.2f instructs Python that placeholder holds float number with 2decimal places. print 'The temperature is %.2f Degrees Fahrenheit' %(Tf, ) #Convert F to C if x == 2: def Tf_to_Tc (): Tf = input ("What is the Fahrenheit Temperature ? " ) Tc = (5.0/9.0)*(Tf - 32) return Tc Tc = Tf_to_Tc () 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
However if you were using this before:
PYTHON Syntax (Toggle Plain Text)
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)
if 0: print "0 is True" else: print "0 is False" if -1: print "-1 is True" else: print "-1 is False"
Here's a final example:
PYTHON Syntax (Toggle Plain Text)
sentinel=True # a boolean variable...we'll use this in a bit! value = 24 #and a number # OK, we want to check that value is greater than -1 # and less than or equal to 23... if value>-1 and 23:# oops, the right hand part of this always evaluates to true print "1. True" # this gets printed...Doh! else: print "1. False" # when we want this! if -1 and value<=23: # Oops, now the left hand part always evaluates to True print "2. True" else: print "2. False" # returns false, but it's still wrong! ^^ # What we meant was.. if value>-1 and value<=23: #phew now we're ok. Both sides are valid boolean expresions print "3. True..." else: print "3. False..." # should return false! # Something slightly different: # Here we're using the value of a variable on one side, but it's safe # to do so because it's a boolean variable! # if sentinel is true and value is greater than 23 return true... if sentinel and value>23: # both sides of the 'or' are boolean print "4. True...." # Yaay! else: 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
There are 10 types of people in this world.....
Those who understand binary .....
And those who don't!
Those who understand binary .....
And those who don't!
•
•
Join Date: Dec 2006
Posts: 1,054
Reputation:
Solved Threads: 297
Defining and then calling the functions under the if() statements serves no purpose. Stripped to the minimum, it would be: 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.
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.
Python Syntax (Toggle Plain Text)
#Convert C to F if x == 1: Tc = input ("What is the Celsius Temperature ? " ) print 'The temperature is %.2f Degrees Fahrenheit' % \ (9.0/5.0 * Tc + 32 )
Python Syntax (Toggle Plain Text)
def Tc_to_Tf (): Tc = input ("What is the Celsius Temperature ? " ) print 'The temperature is %.2f Degrees Fahrenheit' %(9.0/5.0 * Tc + 32 ) def Tf_to_Tc (): Tf = input ("What is the Fahrenheit Temperature ? " ) print 'The temperature is %.2f Degrees Celsius' %((5.0/9.0)*(Tf - 32) ) ##-------------------------------------------------------------------------------------------------- ## "select" is a python function and should not be used as a variable selection = True while selection: x = int(raw_input ('To convert Celsius to Farenheit, enter 1\nTo convert Farenheit to Celsius, enter 2\n')) if x == 1: Tc_to_Tf () selection = False elif x == 2: Tf_to_Tc () selection = False else: print 'Only options are 1 or 2'
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.
Linux counter #99383
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.
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)
##-------------------------------------------------------------------------------------------------- ## "select" is a python function and should not be used as a variable selection = True while selection: try: x = int(raw_input ('To convert Celsius to Farenheit, enter 1\nTo convert Farenheit to Celsius, enter 2\n')) if x == 1: Tc_to_Tf () selection = False elif x == 2: Tf_to_Tc () selection = False else: print 'Only options are 1 or 2' except: print 'No letter please'
Last edited by snippsat; Sep 21st, 2009 at 5:31 pm.
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
http://www.daniweb.com/forums/showth...595#post992595
No one died when Clinton lied.
•
•
Join Date: Dec 2006
Posts: 1,054
Reputation:
Solved Threads: 297
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)
def f2c(t): """given t Fahrenheit return Celsius""" return 5/9.0 * (t - 32) def c2f(t): """given t Celsius return Fahrenheit""" return 9/5.0 * t + 32
Last edited by woooee; Sep 21st, 2009 at 7:57 pm.
Linux counter #99383
![]() |
Similar Threads
- Newbie function question (Python)
- My python program/function! (Python)
- missing function header (C++)
- Function that returns void (C++)
Other Threads in the Python Forum
- Previous Thread: wxpython, mysql query
- Next Thread: python unit conversion
| Thread Tools | Search this Thread |
Tag cloud for Python
abrupt ansi anti apache approximation array backend beginner binary book builtin calculator chmod code converter countpasswordentry curved dan08 dictionaries dictionary drive dynamic examples excel file filename float format function gui heads homework import inches input java launcher library line lines linux list lists loop mouse mysql mysqlquery number numbers numeric output parsing path phonebook plugin pointer port prime programming progressbar projects py2exe pygame pyqt pysimplewizard python random recursion redirect refresh scrolledtext software statictext statistics string strings sum table terminal text textarea thread threading time tkinter tlapse trick tricks tuple tutorial twoup ubuntu unicode urllib urllib2 variable windows wordgame write wxpython






