0

If Else im confused

age = 16 is_male = True weight = 75 if age > 18: if is_male: print("ok") else: print("not ok") elif weight > 72 and weight < 79: print("ok") else: print("not ok") #why does it output true if age is under 18

28th Sep 2024, 12:42 AM
Mohammad Badra
4 ответов
+ 2
Mohammad Badra yes, if-else operates on booleans and all() outputs a boolean. Think of all() as a short version of chained 'and's. It will return True only if the items of the iterable passed to it are all true. It returns false otherwise. You need an iterable inside it, so it's all( (iterable, or tuple of your booleans) ) thus the nested (()). so all((a>b,c==True,d>0 and d<5)) is the same as a>b and c==True and (d>0 and d<5) also, is_male is a boolean, so just passing it by itself is sufficient for it to be evaluated. One last thing is that range can also be used as a min max boundary check. so weight>72 and weight <79 can be rewritten as weight in range(73,79) remember that range includes the starting value, so for >72, you need to start with 73. If it is >=72, start with 72. The end value for range is not included, so use 79 if you want <79 and use 80 if you want <=79.
30th Sep 2024, 1:33 AM
Bob_Li
Bob_Li - avatar
+ 3
Mohammad Badra when indented correctly I get OK on the weight ... Your code also looks beyond age and the if else to the elif of the code as weight ( 75 ) > 72 and less than 79: I currently do not see how you are obtaining "true" when none of your print statements relates to boolean response 🤔 only OK which is never used.
28th Sep 2024, 2:57 AM
BroFar
BroFar - avatar
+ 2
The problem is that you have 3 variables, but you wrote the if-else conditions in a disjointed manner. Perhaps you wanted to print ok only if age>18, is_male==True and weight is between 72 and 79? Then maybe you can write age = 16 is_male = True weight = 75 if all((age>18, is_male,weight in range(73,79))): print('ok') else: print('not ok')
28th Sep 2024, 7:52 AM
Bob_Li
Bob_Li - avatar
+ 1
I thought if else and loops is allways boolean response?
29th Sep 2024, 7:58 PM
Mohammad Badra