using and vs or in statments - python

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

Related

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

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

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

Error with if statement and multiple conditions

I'm having a problem with if statement that's checking if input is correct.
It when I input M or F it prints out "Wrong input" and I don't understand it very clearly.
def check(aw,iw):
if abs(aw-iw)<5 :
print "Your weight is normal."
elif abs(aw-iw)>5 and abs(aw-iw)<15 :
print "Your weight is about normal."
else:
print "Your weight is not normal."
return
print "Enter your gender (M/F)"
gender=raw_input()
if gender!='M' or gender!='F':
print "Wrong input."
else:
if gender=='M':
w=raw_input("Enter your weight (kg) :")
h=raw_input("Enter your height (cm) :")
idw=110-h
check(w,idw)
else:
w = raw_input("Enter your weight (kg) :")
h = raw_input("Enter your height (cm) :")
idw = 110 - h
check(w, idw)
Every input is either not equal to M or not equal to F (e.g., M is not equal to F). Instead you need to check if your input is not equal to M and not equal to F:
if gender != 'M' and gender != 'F':
# Here ------^
print "Wrong input."
Or, more elegantly, use the not in operator:
if gender not in ('M', 'F'):
print "Wrong input."
This line is incorrect:
if gender!='M' or gender!='F':
It will always resolve to False since gender can never be both M and F.
You can use in instead:
if gender in ('M', 'F'):
Alternatively:
if (gender != 'M') and (gender != 'F'):
Also, remove the line gender=int(gender): it should always fail.
I hope you have already got your answer in the previous answers to your question. i would just like to add the fact you appreciate some visualizations to the simple problem that you have faced but very delicate one for every beginner.
You have or doing this-
when you write
M
python checks if
M is !=(not equal to) M
but M is equal to M. so it results in false and then checks if
M != F
and sees its true. The or operation thus does the following-
true + true = true
true + false= true
false + true = true ....... this one
false + false = false
As your one resembles the 3rd one it returns true and python says "wrong input".
if you write and then it goes something like-
is
M!=M
returns false, and
M!=F
returns true.
In and its like-
true + true= true
true + false= false
false + true= false
false + false= false
So python returns false for the if statement and follows what you want it to do in the next lines of code. I hope it makes it very clear.
And remove gender=int(gender) its not necessary because python can recognize M and F as char and you need not turn it into integer value or ascii here.
Remove the line
gender=int(gender)
and make changes to
if gender!='M' or gender!='F':
as
if gender!='M' and gender!='F':
Also, you should use <= to include limits in your evaluation.
def check(aw,iw):
if abs(aw-iw)<=5 :
print "Your weight is normal."
You can shorten elif abs(aw-iw)>5 and abs(aw-iw)<15:, since if abs(aw-iw)<5 is not true, then it will always be higher than 5.
#Instead of elif abs(aw-iw)>5 and abs(aw-iw)<15:
elif abs(aw-iw)<=15:
print "Your weight is about normal."
else:
print "Your weight is not normal."
return
Instead of:
print "Enter your gender (M/F)"
gender=raw_input()
gender=int(gender)
You should use:
gender = raw_input('Enter yor gender (M/F)')
Where int(gender) would cause an error, since the input you want from gender=raw_input() gives a string in letters.
You should change that or for an and, since if using or, if your input is 'M', then gender != 'F' will give True and it will run the if condition.
#Instead of if gender!='M' or gender!='F':
if gender!='M' and gender!='F':
print "Wrong input."
Here you should use int(raw_input()) for your variables to be evaluated as integers and be able to add or subtract them. And since you are doing the same code wether it's M or F, there is no need to write another if: else: condition.
else:
w = int(raw_input("Enter your weight (kg) :"))
h = int(raw_input("Enter your height (cm) :"))
idw = 110 - h
check(w, idw)

Overrided if statement [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 7 years ago.
This is a piece of code I was trying to make one day:
proceed = 0
print """Welcome to Magyck and Monsters
A text-based RPG"""
charactor_name = raw_input("What is your name? ")
print "Welcome ", charactor_name
while proceed == 0:
gender_answer = raw_input("Are you male or female? ")
if gender_answer == "male" or "MALE" or "mALE" or "Male":
charactor_gender = "male"
proceed = 1
elif gender_answer == "Female" or "FEMALE" or "female" or "fEMALE":
charactor_gender = "female"
proceed = 1
else:
print "Sorry, I could not understand you."
proceed = 0
if proceed == 1:
print "You are a ", + charactor_gender
It was supposed to be a text-based RPG game, the problem is, when i run it, no matter what I enter for the gender, I get get the printed message "You are a male" as if it overrided the first if statement and somehow made it true. The way it is supposed to work is that during a loop you would be asked a question, then check if the answer really made any sense and assign it a specific value that would not change. if the answer did not make any sense, it was supposed to say "Sorry, I could not understand you." and loop back to the question. I am fairly new to coding and would appreciate any input.
The line if gender_answer == "male" or "MALE" or "mALE" or "Male": will always be true.
What you are checking is if gender_answer equals "male" or if one of the other options are true where the other options are tested for their truthiness. As any non-empty string is True, the condition becomes gender_answer == "male" or True which will always be true.
Use if gender_answer in ("male", "Male", "MALE", "mALE"): instead or better yet if gender_answer.lower() == "male":.
You need to make a complete condition.
if gender_answer == "male" or gender_answer=="MALE" or gender_answer=="mALE" or gender_answer=="Male":
Same solution for the elif.
Because "male" (or any string) is considered to be true, you go into the if. You need to compare it every times.

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