-1

I am new in Python and I am doing an exercise in which I am supposed to convert from Celsius to Fahrenheit and viceversa. I am trying to do it trough a function which should process the user input and convert it. I am unfortunately stuck because it just partially works and I cannot understand where the problem is. Here my code:

Temperature = int(input("Give an int as temperature"))

Unit = input("insert 'C' or 'F' as unit")

Mix_input = [(Temperature, Unit)] 



def convert_f_c(x):
    for t, u in x:
        if u == "C" or "c":
            F = round((1.8 * t) + 32)
            print("Converted Temp:{}F".format(F))
        elif u == "F" or "f":
            C = round((t-32)/ 1.8)
            print("Converted Temp:{}C".format(C))
        else:
            print("You typed something wrong")


convert_f_c(Mix_input)

If I enter a temperature in Celsius, it works as expected:

Give an int as temperature 60
insert 'C' or 'F' as unit c
Converted Temp:140F

But with the temperature in Fahrenheit, I get a wrong output:

Give an int as temperature 45
insert 'C' or 'F' as unit F
Converted Temp:113F

It happens also with lower case:

Give an int as temperature 45
insert 'C' or 'F' as unit f
Converted Temp:113F

the expected output would be:

Give an int as temperature 45
insert 'C' or 'F' as unit f
Converted Temp:7.2C

Also if I enter something different, I don´t get the error message: "You typed something wrong", as expected, but:

Give an int as temperature 145
insert 'C' or 'F' as unit r
Converted Temp:293F
Franz Biberkopf
  • 191
  • 1
  • 11

2 Answers2

4

You did:

if u == "C" or "c":

and

elif u == "F" or "f":

Due to operator priority these works actually as:

if (u == "C") or "c":

and

elif (u == "F") or "f":

as all non-empty string are truthy in python, these condition are always met. To avoid this you might do:

if u == "C" or u == "c":

or

if u in ["C", "c"]:

or

if u.lower() == "c":

(and same way with elif). in is membership, lower turn str into lowercase version.

Daweo
  • 31,313
  • 3
  • 12
  • 25
1

Change if u == "C" or "c" to if u == "C" or u== "c"

just or "c" will always be truthy, which is why you get the error (same for elif u == "F" or "f")

drops
  • 1,524
  • 1
  • 11
  • 20