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)
Related
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
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")
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:
How can I read inputs as numbers?
(10 answers)
Closed 6 years ago.
I'm starting out in python and just wrote a simple calculator but it seems to have some errors.Pls help me out
a = raw_input("Enter value of a : ")
b = raw_input("Enter value of b : ")
sum = a + b
sub = a - b
mul = a * b
div = a / b
print"1.Addition"
print"2.Subtraction"
print"3.Multiplication"
print"4.Division"
op = raw_input("Enter the operation to be done : ")
if op == 1:
print"Sum is %d" % sum
elif op == 2:
print"Difference is %d" % sub
elif op == 3:
print"Product is %d" % mul
elif op == 4:
print"Quotient is %d" % div
else:
print"Invalid operation"
Error is
TypeError : Unsupported operand type for -: 'str' and 'str'
You are reading strings, and trying them to subtract them as strings. You have to convert them to numbers first. Just add
a = float(a)
b = float(b)
after the user input
Moreover, sum is a builtin function in python, so you'd better use different names for your variables
change the input into an int by putting int() outside of raw_input.
a = int(raw_input("Enter value: "))
raw_input interprets the user input as strings therefore you need to convert the raw input into an int first before processing them
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"):
...