Python: Converting Fahrenheit to Celsius / problem with IF statement [duplicate] - python

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":

Related

Why wont this if statement work? I may be blind but I can't find out why it wont work [duplicate]

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 6 months ago.
input("Welcome to this calculator, press ENTER to continue")
operation = input("Type one : Add Subtract Multiply Divide ");
firstNumber = input("Type the first number you want to " + operation + " ");
secondNumber = input("Type the second number ");
if operation == "add" or "Add":
finalNumber = int(firstNumber) + int(secondNumber); finalNumberString = str(finalNumber); newOperation = "adding "
elif operation == "multiply" or "Muptiply":
finalNumber = int(firstNumber) * int(secondNumber); finalNumberString = str(finalNumber); newOperation = "multiplying "
else:
print("Not Yet Implemented")
print("Your result of " + newOperation + firstNumber + " to " + secondNumber + " was " + finalNumberString)
When I run the script and try to multiply, it ends up adding them and prints "adding" instead of "multiplying"
Welcome to this calculator, press ENTER to continue
Type one : Add Subtract Multiply Divide Multiply
Type the first number you want to Multiply 10
Type the second number 5
Your result of adding 10 to 5 was 15
It works when I change
if operation == "add" or "Add": and elif operation == "multiply" or "Muptiply":
to
if operation == "add" or operation == "Add": and elif operation == "multiply" or operation == "Multiply":

Basic Python if statement logic [duplicate]

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)

Python Function to convert temperature does not work properly [duplicate]

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")

How do I use raw_input() with a user defined function? [duplicate]

This question already has answers here:
How do I read from stdin?
(25 answers)
Closed 17 days ago.
How do I get an input from the user to be used as grade?
def grade_converter(grade):
if grade >= 90:
return "A"
elif grade >= 80:
return "B"
elif grade >= 70:
return "C"
elif grade >= 65:
return "D"
else:
return "F"
raw_input() returns a string, but your function is comparing against integers. Convert your input to an integer before calling grade_converter():
grade = int(raw_input('Enter a grade'))
print grade_converter(grade)
Note that the conversion will raise an exception if you enter something that can't be converted to an integer.
In Python3, raw_input() was renamed to input(). You could just use it as an input to your grade_converter() function:
if __name__ == '__main__':
print('Enter a score')
print('The grade is: ', grade_converter(int(input())))

Python if expression does not work correctly with raw input [duplicate]

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"):
...

Categories

Resources