This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
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
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.
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")
Related
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 12 months ago.
Can someone tell me why the code executes the first if statement and not the second one when I enter "p" into the console in python? I expect it to print out the second statement of 45.45
weight = 100 #int(input("Weight "))
conversion = input("kilograms or pounds: ")
if conversion in "k" or "K":
print(weight * 2.2)
elif conversion in "p" or "P":
print(weight // 2.2)
output:
kilo or pounds: p
220.00000000000003
try this
weight = 100 #int(input('Weight '))
conversion = input('kilograms or pounds: ')
if conversion in ['k','K']:
print(weight * 2.2)
elif conversion in ['p','P']:
print(weight // 2.2)
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 1 year ago.
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...
The basic idea is that "l" is a truthy Value
> if unit == "L" or "l":
Before you tweaked your code it returns: you are 27.0kg. and the code still executed the if statement though the unit provided is not "L" or "l" because you didn't specify whether any variable is equal to (comparison operator) "l" or not. So on execution, it always executed True being a truthy value. As it is OR operator if unit=="L" one operand gets true and if unit!="L" still the other operand is always true, so the if statement runs.
If you did the same thing with AND operator , it would have executed the else statement.
Here's an example:
Input:
> if 'l' or 'L':
> print("HI")
> else:
> print("HELLO")
Output:
HI
Here the output is always "HI" as both sides of operator always execute True.
Trying with AND operator:
Input:
> weight = 60 unit = "k"
>
> if unit == "L" and "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")
Output:
You are 132.0lbs
I didn't mean to spoil the logic here. I just mean to show you that with AND operator both sides True will be needed and only "l" executes True so it executes else statement.
Truthy Values:
According to the Python Documentation:
By default, an object is considered true.
Truthy values include:
1.Non-empty sequences or collections (lists, tuples, strings, dictionaries, sets).
2.Numeric values that are not zero.
3.True
I am learning python and I am having a hard time with a practice sheet where I am trying to convert millimeters to inches and vice versa. I am building it off a similar script that converts Fahrenheit to Celsius (and also vice versa).
Here's the script that converts F <-> C:
temp = input("Input the temperature you like to convert? (e.g., 45F, 102C etc.) : ")
degree = int(temp[:-1])
i_convention = temp[-1]
if i_convention.upper() == "C":
result = int(round((9 * degree) / 5 + 32))
o_convention = "Fahrenheit"
elif i_convention.upper() == "F":
result = int(round((degree - 32) * 5 / 9))
o_convention = "Celsius"
else:
print("Input proper convention.")
quit()
print("The temperature in", o_convention, "is", result, "degrees.")
I wrote this, based on the one above:
meas = input("Convert mm to in and vice versa, enter a value (e.g. 10mm, 2in): \n")
num = int(meas[:-2])
i_measType = meas[-2]
if i_measType.upper() == "MM":
result = int((num * (1/25.4)))
o_measType = "in"
elif i_measType.upper() == "IN":
result = int((num * 25.4))
o_measType = "mm"
else:
print("Input proper convention.")
quit()
print(meas, " = ", result, o_measType)
I assume the problem is with the [:-2] and the [-2] because based on what I can understand, this part is used to maybe pull the convention from the number? I thought like if someone enters 44mm, meas[:-2] is used to convert that to 44 and the meas[-2] is mean to call the mm. But I am clearly wrong...
Any help and possibly explanation would be greatly appreciated.
The error is:
ValueError: invalid literal for int() with base 10:
meas[-2] is the 2nd to the last characters in the input string meas, in your case, it can either be 'm' or 'i'. It's a single character.
you can change your if/else conditions to
if i_measType.upper() == "M" ...
or change your i_measType = [-2:]
to fix the problem.
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 3 years ago.
When I try to make the programm asking the user to select the current unit of the temperature, the if unit == "f" or "F" run, even though unit != "f" or "F".
unit = str(input("Is your temperature currently in Fahrenheit(F) or Celsius(C)? Please enter F or C"))
if unit == "f" or "F":
print("Your entered temperature will now be transformed from Fahrenheit to Celsius")
new_tempC = (temp - 32) * 5/9
print(f"{temp} F expressed in Celsis is {new_tempC} C.")
elif unit == "c" or "C":
print("Your entered temperature will now be transformed from Celsius to Fahrenheit")
new_tempF = (temp * 9/5) - 32
print(f"{temp} C expressed in Fahrenheit is {new_tempF} F.")
else:
print("Please enter a valid input.")´´´´
Try:
if "F":
print('Always true!')
if unit == "f" or "F": # The condition "F" is always true, hence this will be executed regardless of the value stored in unit.
Should be:
if unit == "f" or unit == "F":
elif unit == "c" or "C":
Should be:
elif unit == "c" or unit == "C":
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 8 years ago.
This script does not progress passed the first if expression!
If the user enters DD, or F, the script acts as like the if state was true.
choice = raw_input("Cup size for bra: D, DD, or F: ")
if choice == "D" or "d":
band_length = raw_input("Please enter the bra band length for your D size breasts: ")
D_Statistics(band_length)
elif choice == "DD" or "dd":
band_length = raw_input("Please enter the bra band length for your DD size breasts: ")
DD_statistics(band_length)
elif choice == "F" or "f":
band_length = raw_input("Please enter the bra band length for your F size breasts: ")
F_statistics(band_length)
Your if statements will always evaluate to True currently.
if choice == "D" or "d" evaluates to True on either the value of choice equaling "D", or the value of literal "d" being True; and the second part is thus always True.
Instead, use
if choice in ("D", "d"):
...
elif choice in ("DD", "dd"):
...
if choice in ("F", "f"):
...