Python logical (OR) and comparison (==) [duplicate] - python

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

Related

using and vs or in statments

while gender.capitalize() != "M" and gender.capitalize() != "F" and gender.capitalize() != "Male" and gender.capitalize() != "Female":
print("Not a valid entry: ")
gender = (input("Gender: "))
if gender.capitalize() == "M" or gender.capitalize()== "Male":
print("Hello " + name + " you are " + age + " years old and are a boy")
elif gender.capitalize() == "F" or gender.capitalize()== "Female":
print("Hello " + name + " you are " + age + " years old and are a girl")
this is working code I would just like to know why and works above and or works below im sure it's the != but I'm not sure
I just want a better understanding of when and why to use and vs or
and should be used when all the conditions requirement shoule be met [i.e all conditions must be True]
or should be used when any one condition satisfy the condition [i.e. any one condition should met True]
Ex let's say you wanted a number which should be divisible by 2 and should be greater than 10
Condition you should apply -: if num%2==0 and num>10: as you see and is used because you wanted both criteria to be satisfied
Ex let's say you wanted a number which is greater than 10 or if it is not greater than 10 the number should divisible by 2
Condition you should apply :- if num>10 or num%2==0 as you see or used because any one criteria if satisfied you wanted that number..
In the top line (while) you are asking that the gender variable is non of the values you mention so not (!=) M, F, Male nor Female.
For the bottom two lines either one can be used so for the middle line (if) the value could either be M OR Male.
To conclude if you use AND all the conditions have to be true if you use OR only one of the given conditions have to be true.
Example:
True AND False -> Returns FALSE
True OR False -> Returns FALSE

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

Why doesn't using python's logical operator or in the form of "x == 5 or 4" throw an error?

I wonder why this code will give a result of 3 for count.
s = 'awb'
count = 0
for i in range (0, len(s)):
if s[i] == 'a' or 'b':
count += 1
print ("number of a and b: ", count)
I understand that in order to count the number of a and b, the if statement should look like:
if s[i] == 'a' or s[i] == 'b':
However, I am just curious why the if statement in my original code will result in all the characters in the string being counted?
The expression:
if s[i] == 'a' or 'b'
says if the current index of the string s == 'a' execute the code below this line. The second condition is True ('b' always evaluates to True in the context of truthiness in python). The second condition in the statement will make this if statement True. Therefore, count will always be incremented for each iteration the loop. Within the context of boolean evaluation a literal always evaluates to True. Consider the snippet below:
not not 'b'
If you execute this line of code by itself you'll see that the expression evaulates to True. 'b' was "casted" into a boolean value (True or False). This implicitly happens behind the scenes within the if statement in question.
There is no reason for it to through an error. Writting x == 5 or 4 would be evaluated as (x == 5) or 4 So the left hand of the or will be true when x is 5 but the right hand will always be true since truthyness will say any int thats not 0 is True. Now you may think well whats the point but there are valid use cases.
lets imagine we have a game that always gives a prize on the first go regardless if you were right or not then for each turn after that you only win if your correct.
prize_gauranteed = True
while True:
guess = int(input("Guess: "))
if guess == 5 or prize_gauranteed:
print("You win a prize")
prize_gauranteed = False
else:
print("No prize this time")
OUTPUT
Guess: 10
You win a prize
Guess: 10
No prize this time
Guess: 4
No prize this time
Guess: 5
You win a prize

What's the main difference between 'if' and 'else if'? [duplicate]

This question already has answers here:
Difference between multiple if's and elif's?
(9 answers)
Closed 8 years ago.
For e.g..
According to some experts,
The conditions here are mutually exclusive:
if(n>0):
print "Number is Positive"
if(n<0):
print "Number is Negative"
if(n==0):
print "Number is ZERO"
It would be better to rewrite with elif and else:
if n > 0:
print "Number is Positive"
elif n < 0:
print "Number is Negative"
else:
print "Number is ZERO"
So I just want to ask the question that , Is there any difference between ' if ' and ' elif ' . I know the basic difference between ' if ' and ' elif '. But I just want to know , Why some novice programmers prefer ' elif ' over ' if '?
The first form if-if-if tests all conditions, whereas the second if-elif-else tests only as many as needed: if it finds one condition that is True, it stops and doesn't evaluate the rest. In other words: if-elif-else is used when the conditions are mutually exclusive.
Let's write an example. if you want to determine the greatest value between three numbers, we could test to see if one is greater or equal than the others until we find the maximum value - but once that value is found, there is no need to test the others:
greatest = None
if a >= b and a >= c:
greatest = a
elif b >= a and b >= c:
greatest = b
else:
greatest = c
print greatest
Alternatively, we could assume one initial value to be the greatest, and test each of the other values in turn to see if the assumption holds true, updating the assumed value as needed:
greatest = None
if a > greatest:
greatest = a
if b > greatest:
greatest = b
if c > greatest:
greatest = c
print greatest
As you can see, both if-if-if and if-elif-else are useful, depending on what you need to do. In particular, the second of my examples is more useful, because it'd be easy to put the conditional inside a loop - so it doesn't matter how many numbers we have, whereas in the first example we'd need to write many conditions by hand for each additional number.
You can chain if with elif and finish with an else if none of the conditions in the chain were met. When checking through the statements, it will find the first matching one and execute the instructions within that block, then break from the if/elif/else block
n = 6
if n % 2 == 0:
print('divisible by 2')
elif n % 3 == 0:
print('divisible by 3')
else:
print('not divisible by two or three')
this would print
divisible by 2
However, say you replace that elif above with an if and remove the else clause...
divisible by 2
divisible by 3
the elif chains the statements and chooses the first appropriate one.

Categories

Resources