Am 14.06.2017 um 16:20 schrieb William Gan:
Good day Everyone,

I am seeking help on two issues.

ISSUE 1:
Yesterday I posted a problem on this tiny script I wrote for temperature 
conversion (as practice for a newbie). My error was pointed out to me that 
there is a difference in upper and lowercase letters. After correcting that 
error, I remember the tests I ran produced the correct outputs.

However, today I modified only the print instruction a little to try to print 
out ℃ (in the second print clause). When I subsequently ran the script all the 
outputs were executed from the if clause, even when I input other letters 
(Please see below. I have removed the code to print degree C).

print('Enter C for Celsius to Fahrenheit or F for Fahrenheit to Celsius.')
unit = input('Enter C or F: ')
temp = int(input('Enter temperature: '))

if unit == 'C' or 'c':
    f = temp * 9 / 5 + 32
    print(str(temp) + ' C is equivalent to ' + '%.2f' % f + ' F.')
elif unit == 'F' or 'f':
    c = (temp - 32) * 5 / 9
    print(str(temp) + ' F is equivalent to ' + "%.2f" % c + ' C.')
else:
    print('Please enter C or F in upper- or lowercase.')

The if statement block is to convert Celsius to Fahrenheit.
When I entered ‘C’ or ‘c’ and 100 for temperature, the output is correct: 100 C 
is equivalent to 212.00 F.

The elif statement block is to convert Fahrenheit to Celsius.
When I entered ‘f’ or another letter, in this case ‘z’ and ‘g’, and 212 for 
temperature, I got: 212 C is equivalent to 413.60 F.

I have looked at it many times today and could not see the error. Please advise.

Reading other threads in this list might have helped more - this is quite a frequent beginner error.

if myvar == val1 or val2:
    ...

is parsed as

if (myvar == val1) or val2:

That is true if myvar == val1; it is also true if val2 has any value that Python regards as true. This last condition would only be false if val2 were 0, None, an empty list, an empty dictionary, the empty set or another object with some sort of null value. There is no comparison between myvar and val2.

Correct usage would be:

if myvar == val1 or myval == val2:
or
if myvar in (val1, val2):

Because this sort of problem has appeared so often in this list I looked into the official tutorial. There is 5.7, More on Conditions, but I'm not sure if that's enough for a beginner.

HTH
Sibylle


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to