Python Boolean Logic

Bill BILL_NOSPAM at whoknows.net
Sat Sep 23 01:07:17 EDT 2017


Bill wrote:
> Cai Gengyang wrote:
>> Hey guys, I'm testing this on CodeAcademy, but I cant get the program 
>> to output a result even after pressing the run button. Just wanted to 
>> check if my logic is correct. Thanks alot
> Your answers appear correct, but you could write Python statements to 
> test them (or any you encounter in the future). For instance,
>
> if (20 - 10)  > 15 :
>     print("true")
> else:
>     print("false");
>
> Or,
>
> s='(20 - 10)  > 15'
> b=(20 - 10)  > 15
> print(s, " is ", ("true" if b else "false") );  ## inside parentheses 
> may be removed.
>
> I am new to Python.  Maybe someone here is familiar with an elegant 
> way to get the the value of b directly from the string s? Hmm... It 
> appears that eval() would work (see "Python: Essential Reference", p. 
> 115).  I just read about that for the first time last night! I may try 
> that, for practice,  after I post this.
>
Update: Yes,
b=(20 - 10)  > 15
may be replaced by eval(s).

We can write:

print(s, " is ", ("true" if eval(s)  else "false") )



>
>>
>> # Assign True or False as appropriate on the lines below!
>>
>> # (20 - 10) > 15
>> bool_one = False    # We did this one for you!
>>
>> # (10 + 17) == 3**16
>> # Remember that ** can be read as 'to the power of'. 3**16 is about 
>> 43 million.
>> bool_two = False
>>
>> # 1**2 <= -1
>> bool_three = False
>>
>> # 40 * 4 >= -4
>> bool_four = True
>>
>> # 100 != 10**2
>> bool_five = False
>




More information about the Python-list mailing list