Home > Back-end >  using and vs or in statments
using and vs or in statments

Time:12-28

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

CodePudding user response:

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..

CodePudding user response:

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