COMPLEX STATE­MENTS



Life isn't easy in itself, but if we fill life with complex conditions, it will become... simpler!

The most common complex statement is made with negation not. Recipe: take a statement and negate it.

For example, the simple statement TODAY IS A WEEKEND will turn into the complex statement TODAY IS NOT A WEEKEND.

There is one more way to create a complex statement by uniting two simple statements through the connectives and, or.

TODAY IS A WEEKEND, I HAVE A BICYCLE are simple statements. Having connected them with and, you will get a complex statement:

TODAY IS A WEEKEND and I HAVE A BICYCLE.

Thus, if it is a weekend and there is a bicycle, go boldly for a ride.

Complex statement is made from a simple statement by adding negation not, or from several statements (two or more) connected with the connectives and, or.

Meanwhile, negation can be applied to any statement connected with and, or.

And that's what I want to say to you:

if (TODAY IS A WEEKEND and I HAVE A BICYCLE): I go cycling

There is a bicycle. There is no weekend. I'm sitting home. Moreover, it's raining outside the window, and the noise of the raindrops mutes the noise of the cars on the road. It's night. Amazing!


LOGICAL OPERA­TORS


There are three logical operators. I'll list them in priority order. What is priority order of logical operators? In mathematics, expressions in brackets are considered priority (performed first). Then goes multiplication, division and, in the end, addition, subtraction.

For example, (2 + 3) * (4 - 2 * 2) = 0. Is it right? Are you good at math? Check your answer with Python and write:

if ((2 + 3) * (4 - 2 * 2) == 0): print("Right!") else: print("Wrong!")

There are also rules of logical operations priority in complex statements. They are about the following operators:

  1. Inverse or negation is made with not. It has the first priority except for expressions in brackets, of course.
  2. Logical (boolean) multiplication or conjunction is made with and. It has the next priority after the negation.
  3. Logical (boolean) addition or disjunction is made with or. It has the last priority.

So, the complex statements are constructed with these logical connectives. The value of the complex statement is determined with truth tables.


TRUTH TABLES


Frankly speaking, you may avoid learning the truth tables if you have logical thinking developed. Check yourself.

Find the integer that is not less than 80 and not greater than 150 and not less than 90 or equal to 150. There could be dozens of numbers. Find, at least, one.

Answer

Firstly, the number 90, due to it is "not less" than 90

Secondly, the number 150, because it's indicated "or equal to 150"

Thirdly, all numbers greater than 90 and less than 150 will suit too, for example, 91, 92... 148, 149

That is, the right answer is one of the range: 90, 91, 92, 93, 94... until, 148, 149, 150.


If your answer is correct, it's cool. Developed logical thinking will significantly facilitate programming. If there are some difficulties, you will have to learn truth tables.

The truth table is a table with logical values, by using which you can find out whether a complex statement is true or false.

The complex statement may take only two values: 1 (true) or 0 (false). Therefore, all cells of the tables are 0 or 1.

Be diligent and learn the truth tables. From my experience, many people believe it's too complicated. You will have to strive. And then you will succeed!


THE TRUTH TABLE FOR NOT


To complete the picture, let's take the statement "Today is a weekend". It may be true or false.

Inverse rule: if a statement is true, it will become false. If a statement is false, it will become true. That is, the inverse "does the opposite".

The table is formed in this way: we take a character (like a variable) and assign a logical statement to it. You've already known that variables may take any value that data type allows to take. It works the same way with the tables - we consider any logical statement and indicate it as a character.

In our example it will be as follows:

A = Today is a weekend

The application of the inverse:

A = not A

If we interpret this into usual speech, then the statement "Today is a weekend" will turn into "Today is not a weekend". That is to say, the statement will become opposite: if basic one is true, it is turned into false and vice versa.

If we speak about the table, here it goes:

A not A
0 1
1 0

How to read truth tables?

Usually, variable names are indicated at the top of the columns. It could be one name (as in the example above) or two (as in the examples below). The name of the variable means any simple logical statement. For example, A = "TODAY IS A WEEKEND" or B = "KNOWLEDGE IS THE LIGHT".

Since we have the operation not, only one statement is needed. We'll indicate it as the A variable. And then we'll implement the operation not to the statement.

  1. Now let's translate: if А is 0, i.e. False, then after the operation "not A" is completed, A will become True, i.e. A will take the value 1. This is the first line of the table.
  2. If А is 1, i.e. True, then after the operation "not A" is completed, A will become False, i.e. 0. This is the last line of the table.

The design of the table without any strange values and mathematics:

"Today is a weekend" not "Today is a weekend"
Today is a weekend Today is not a weekend
Today is not a weekend Today is a weekend

I hope this information will help you to understand easily the next truth tables. There will be two of them.



THE TRUTH TABLE FOR AND


The logical connective and, a.k.a. conjunction, is applicable to connect two simple statements.

Conjunction rule: the value of the complex statement, connected with and, is true only when two simple statements, included in it, are true.

Let's take A for the first logical statement:
A = "Moscow is the capital of Russia".

And B for the second one:
B = "The Moon is a satellite of the Earth.".

Then the statement А and B will be true. Check it by yourself. I will ask you and will demand only "yes" or "no" answers:
- Moscow is the capital of Russia and The Moon is a satellite of the Earth?

What will you answer?

And what will you answer now:
- Moscow is the capital of Russia and the Earth is flat?

Итак, у нас новенькое:

A = Moscow is the capital of Russia
B = The Earth is flat

Then the result of the complex logical statement A and B will be False, because A is true, but B is false. I hope, there is no doubt that the statement B "The Earth is flat" is false. At least, it is more familiar. Regrets to Mike Hughes.

The truth table for and:

A B A and B
0 0 0
0 1 0
1 0 0
1 1 1

The last line: the statement A and B will become true only when both A and B are true.

It reminds the results of multiplication 0 х 0 = 0, 0 х 1 = 0, 1 х 0 = 0, 1 х 1 = 1, doesn't it? That's why conjunction is called logical multiplication. It will be easier to remember.


THE TRUTH TABLE FOR OR


The logical connective or, a.k.a. disjunction, is applicable to connect two simple statements.

Disjunction rule: the value of the complex statement, connected with or, is false only when two simple statements, included in it, are false.

The truth table for or:

A B A or B
0 0 0
0 1 1
1 0 1
1 1 1

Disjunction is also called logical addition. Look at the truth table: the last column contains the result of the addition. The last line (1 + 1 = 1) could cause some misunderstanding, but keep calm, you'll soon get used to it.



PRACTI­CAL IMPLEMEN­TATION


Complex statements allow to verify several parameters simultaneously. The statement can appear in a condition or be assigned to a variable.

We need to check whether the value of the day variable is between 1 and 7 inclusive. Two programs below are equal, indeed:

day = 3 if (day >= 1 and day <= 7): print("The number is in the range")

Here we check the value of the statement (day >= 1 and day <= 7) directly in the condition. It is permitted, and programmers use this method frequently.

In this case, all the statement will be true only when the day variable is not less than 1 and (at the same time) is not greater than 7.

Remember the truth table for and: the result is true only when 1 and 1. The same thing is here: two simple statements day >= 1, day <= 7 must be true simultaneously.

The second program. Its meaning completely repeats the meaning of the previous one:

day = 3 res = (day >= 1 and day <= 7) if (res): print("The number is in the range")

In this program, we do not immediately determine whether the statement is true or not. The string res = (day >= 1 and day <= 7) means that the statement (day >= 1 and day <= 7) is assigned to the variable res. And only after that if will check the value of the res. In the event that res is true, the condition will "work" and will display the inscription "The number is in the range" on the screen.

Type the program (preferably deal with the second). Change the value of the day variable until you understand it perfectly.

Remark: using brackets while writing a statement, for example (day >= 1 and day <= 7), isn't necessary. I do this because it helps me to perceive statements in brackets better. They stand out from the general background. It's very useful in the programs with much code.

You may also write: (day >= 1) and (day <= 7). There is no difference in terms of logic. There is a difference only in terms of human perception of the text.

Complex statements, made with the logical connectives not, and, or, significantly facilitate the control of the values, different conditions, making code simple and readable. The main thing as always is to figure them out.


FIND THE NUMBER


Let's make a program that will solve the previous problem.

Find the number that isn't less than 80 and isn't greater than 150 and isn't less than 90 or is equal to 150. There are dozens of the numbers. Find, at least, one.

The solution is:

print("""Find an integer that isn't less than 80 and isn't greater than 150 and isn't less than 90 or is equal to 150. There could be dozens of numbers. Find, at least, one.""") x = int(input("Enter a number: ")) # Pay attention to the sign \ at the end of the line below. # This is an operator of the line break (line continuation) in Python. # It is identical to lite-- # rary word wrap. By using \ , you can split long lines # into smaller units. # The sign # indicates a comment. All written after it # won't be executed. You may not type # comment lines. res = (not(x < 80) and not(x > 150) \ and not(x < 90) or (x == 150)) if (res): print("You guessed it!") else: print("Unfortunately, wrong number...") input("Press ENTER to escape...") quit()

Look! There is something new in the text! Let's learn:

1. Triple quotes of the function print() mean that the text will be multi-line. If you use """ before the text and """ after, you may rest assured that Python will display the text on the screen in strict accordance with the location of the text in the body of the program. All hyphenation will be done. It is convenient for multi-line output, e.g. for instructions.

But don't forget to "close" the text by triple quotes either.

print("""This text will be displayed in five lines""")

2. The "empty" input() function in the last line. It's necessary to cause delay. It will be discussed a little below.

3. quit(). The interpreter exit. When Shell reaches the command, it will ask politely:

Feel free to click OK - Python will close the Python Shell window, but will open it the next time it starts.


RUNNING A PROGRAM ON WINDOWS


Locate the file with your program in regular Windows Explorer. No need to load it in Python, just double-click on it.

If you installed the programming language exactly as it was said in the "Python" chapter, then the program will launch, and you will see the result as in Python Shell.

Open the program file with simple text editor, for example, Microsoft Notepad (I recommend Notepad++), and delete penultimate line: input("Press ENTER to escape...").

Launch it again by double-click on it in Windows Explorer. Enter a number... and? What happened?

For those who did not do that

After entering any number, the program will be closed immediately. If your computer has a fast enough processor, then you won't even notice the program output "You guessed it!" or "Unfortunately, wrong number..."

It happens because the console window with the results closes immediately when the last command is executed.

It turns out, input("Press ENTER to escape...") stops program running and waits for entering any value or just pressing Enter.

At the same time, the result of the input, i.e. the line that we can type, does not get anywhere, it is "not remembered" by the computer because the result of the input("Press ENTER to escape...") function isn't assigned to any variable, that is, we didn't write the name of the variable on the left, e.g. s = input("Press ENTER to escape...")




IS IT A WEEKEND?


Do you remember? Feel old yet?

day = int(input("Enter the number of the day of the week: ")) if (day == 1): print("Today is a weekend. We go cycling.") elif (day < 1): print("The number of the day is incorrect.") elif (day > 7): print("The number of the day is incorrect.") else: print("Today is a weekday.")

We'll rewrite the program using complex statements:

day = int(input("Enter the number of the day of the week: ")) if (day < 1 or day > 7): print("The number of the day is incorrect.") elif (day == 1): print("Today is a weekend. We go cycling.") else: print("Today is a weekday.")

The code became shorter. Brevity is the soul of wit, as you know.


DOES THE DRIVER VIO­LATES THE RULES?


There is one more program we can rewrite rightfully:

speed = int(input("Enter vehicle speed: ")) if (speed > 200): print("It isn't a plane. The entered speed is incorrect.") elif (speed > 60): print("The driver violates the rules! Fine him, FINE!") elif (speed == 0): print("The vehicle isn't moving. Like a stone. A stationary stone.") elif (speed < 0): print("The speed can't be negative. We are deeply sorry.") else: print("The driver doesn't violate the rules. The driver is good. Be like him.")

Try to make it by yourself. Reduce the program by using complex statements.

Answer

speed = int(input("Enter vehicle speed: ")) if (speed > 60 and speed <= 200): print("The driver violates the rules! Fine him, FINE!") elif (speed > 200): print("It isn't a plane. The entered speed is incorrect.") elif (speed == 0): print("The vehicle isn't moving. Like a stone. A stationary stone.") elif (speed < 0): print("The speed can't be negative. We are deeply sorry.") else: print("The driver doesn't violate the rules. The driver is good. Be like him.")

Hmm, hmmm, and what has changed? Essentially nothing. The thing is that the program checks the speed in each range separately. Therefore, it is impossible to reduce it with complex statements, we'll have to check all the ranges (speed < 0, 0, 1-60, 61-200, 201 and higher)

However, I added a complex statement :)


Perhaps, it's time to put complex statements aside. You'll face them in the vastness of programming, but we have to move on. There is a lot of fun ahead!


© 2019-2024 Viktor Trofimov
© 2019-2024 Translation and adaptation by Danil Shentsov
[ Top page ]