dimanche 16 mai 2021

Python logical (OR) and comparison (==)

A weight is given. It could be either in lbs or kg. The code then converts accordingly (ie lbs to kg; kg to lbs). In the code, lbs has the unit inputs: l or L. kg has the unit inputs: k or K.

weight = 60
unit = "k"

if unit == "L" or "l":
    weight_kg = weight * 0.45
    print(f"You are {weight_kg}kg")
else:
    weight_lb = weight * 2.2
    print(f"You are {weight_lb}lbs")

But this returns: you are 27.0kg. The code still executes the if statement though the unit provided is not "L" or "l".

I then tweaked the if statement to this:

if unit == "L" or unit == "l":

and it now gives the correct 132.0lbs.

I have tried looking through online tutorials and my notes, but still don't understand why the first code didn't work and why the second one worked...

Aucun commentaire:

Enregistrer un commentaire