[Tutor] need help with conditionals
wrobl1rt at cmich.edu
wrobl1rt at cmich.edu
Fri Sep 25 23:09:03 CEST 2009
Hello all,
I am still very new to Python and am working on conditionals. Im stuck on this
problem and I'm sorry if this is something really simple that I'm missing but its
been really frustrating me. Here's a copy of the problem, and sorry if its really
long but its the end question about the logically equivalent expressions I'm
stuck on. Anyways, heres a copy of the problem
-----------------------------------------------------------
To better understand boolean expressions, it is helpful to construct truth tables.
Two boolean expressions are logically equivalent if and only if they have the
same truth table.
The following Python script prints out the truth table for the any boolean
expression in two variables: p and q:
expression = raw_input("Enter a boolean expression in two variables, p and q: ")
print " p q %s" % expression
length = len( " p q %s" % expression)
print length*"="
for p in True, False:
for q in True, False:
print "%-7s %-7s %-7s" % (p, q, eval(expression))
You will learn how this script works in later chapters. For now, you will use it to
learn about boolean expressions. Copy this program to a file named
p_and_q.py, then run it from the command line and give it: p or q, when
prompted for a boolean expression. You should get the following output:
p q p or q
=====================
True True True
True False True
False True True
False False False
Now that we see how it works, let’s wrap it in a function to make it easier to
use:
def truth_table(expression):
print " p q %s" % expression
length = len( " p q %s" % expression)
print length*"="
for p in True, False:
for q in True, False:
print "%-7s %-7s %-7s" % (p, q, eval(expression))
We can import it into a Python shell and call truth_table with a string containing
our boolean expression in p and q as an argument:
>>> from p_and_q import *
>>> truth_table("p or q")
p q p or q
=====================
True True True
True False True
False True True
False False False
>>>
Use the truth_table functions with the following boolean expressions, recording
the truth table produced each time:
not(p or q)
p and q
not(p and q)
not(p) or not(q)
not(p) and not(q)
Which of these are logically equivalent?
-------------------------------------------------
Whenever I try to enter the expressions listed into the prompt it tells me the
string object is not callable....
More information about the Tutor
mailing list