CONDI­TIONS



Conditions are pretty common in our life. To make it clear, a condition can be described as follows: if an event occurs, then we respond to it a certain way.

IF is a keyword in conditional constructs. Simply put, the if statement creates two opposite ways, two opposite blocks, and it depends on the condition which one will be implemented.

Like to choose where to go at the fork of the road: to the right or to the left.

In life it works like this: if today is a weekend, then we go cycling.

The information verified in this example is a "characteristic" of the day of the week - whether it is a weekend or not. Notice that the event (the day has started) must occur and it must be relevant. It's pointless to check whether it was a weekend yesterday, because we can't make a decision to go for a bike ride "yesterday". That's why verified information must be relevant.

One more example: if grandma calls for dinner, then we'll go to dinner. Or won't go. Depends on hunger, food and grandma. The same thing is in programming: if something happens, if specific information becomes true, then we'll fulfill specific actions. If that doesn't happen, the program will ignore us. It won't implement any command.

In programming it's possible to verify through conditional statements only the events that have already happened. In other words, we can reply certainly YES or certainly NO to the question about the event.

The example with the bicycle could be written in algorithmic language in the following way:

A new day has come if TODAY IS A WEEKEND: We go cycling

Do you remember the bool (logical) variable type? It can take the True value or the False value. The logical type plays an important role in conditions. If you have forgotten, then I recommend reading the chapter "Data Types", firstly.

By that logic, the statement "TODAY IS A WEEKEND" will be true any weekend, and it will be false any other day. So we can write it like this in the first variant:

TODAY IS A WEEKEND = True

And the way below in the second variant:

TODAY IS A WEEKEND = False

The most important thing here is to understand that we deal with two sides of some expression. A statement is an expression that we can claim true or false.


STATE­MENT


"TODAY IS A WEEKEND" is a statement. Again, it's because we can confirm it (True) or disprove it (False).

I would like to emphasize that the expression must have the exact YES or exact NO answer. So, we must prohibit any answer but "yes" or "no" when we deal with these statements. There is no way for "perhaps, it's a weekend", "probably weekend", "aah, idk" or "oh, nevermind!"

If today is a weekend, then we extremely sure! Crucial, strong-willed "YES"! Confirmed! Then:

TODAY IS A WEEKEND = True

If today is weekday, then we are confident as well to claim:

TODAY IS A WEEKEND = False

And there is no any third variant.

Today's day here is an event. And it must happen before we try to check it. Right? Right! When you start using conditional constructs in programs, don't forget - we check what has already happened. While coding, it will relate to values, and these values must be assigned before conditional statement, not after it.

But let's return to the statement.

A statement is a simple declarative sentence that we can confirm or disprove by using common sense.

It doesn't include interrogative sentences requiring a detailed answer such as "What time is it?", imperative sentences such as "Let's go to the cinema!", and questions without definite answer. For example, when it rains, the expression "The weather is nice today" isn't objective because someone likes rain, so he will answer "YES", but the person who doesn't like rain will answer "NO, NO GOD, NOOOOOO".

Likewise, the expression "Paris is the capital of Moscow" is a statement. Why?

Because there is no need to find out what Paris is the capital of (if it's even the capital). We should just confirm or disprove the expression. It's a total nonsense. Therefore we say "FALSE", thereby confirming that we deal with a statement.

The expression TODAY IS A WEEKEND is a statement.

And the statement "the expression TODAY IS A WEEKEND is a statement" is true.



HOW TO WRITE A CONDI­TION


If we write the condition with the weekend in Python, it will look like:

if TODAY IS A WEEKEND: We go cycling

The rule says:

If the logical statement is true, then the command (or the block of commands) after a colon will be executed.

It turns out that when the statement "TODAY IS A WEEKEND" is true, the command "We go cycling" is executed.

To write conditional statement in Python, we use the keyword if. Like in real life, so programming (especially in Python) isn't quite sophisticated. General view of the structure is:

if (logical statement): Block of commands

A block of commands is one or more commands in Python, intended with exactly four spaces from the character i of the if keyword.

If you try to write commands intended with 3 of 5 spaces, Python will throw an error. If you write the commands unintended, then they won't form a block and they won't be executed in the condition.

The example of the block of commands:

if (logical statement): print("This is the first command of the block") print("This is the second command of the block") print("And here I just fool around!")

Logical statement is an expression written by the rules of Python. The result of the logical statement could be only True or False. You can make these statements by using such operators >, <, >=, <=, !=, ==. For more details, look at the table in the logical (bool) variables section of the "Data Types" chapter.

When the "logical statement" is true, the block of the three sequential print() commands will be executed. To test it, you may write:

if (True): print("This is the first command of the block") print("This is the second command of the block") print("And here I just fool around!")

Type the program, save it and press F5 for start. Python will display these three lines on the screen.

Change True to False and launch the program once more. Does something appear on the screen? No. That's because we indicated False in brackets, and Python didn't execute print(). Python just ignores. (Ban, get out of the list of friends for ignorance, silly Python!)

The if construct is related to the processing block. Its task is to compare data , i.e. to process data, and to direct program execution in a certain way, to "branch" an algorithm, to create "two paths" in execution. For example, there is a condition in the main menu of CS:GO:

if (THE ICON OF EXIT IS PRESSED): Exit to Windows

When the condition is activated, i.e. the statement "THE ICON OF EXIT IS PRESSED" becomes True, CS:GO stops running.


IS IT A WEEKEND?


Let's get back to bicycles and weekends. Consider this. The computer can't check by itself whether today is a weekend or not. The machine doesn't know what "a weekday", "a weekend" and "a holiday" mean.

To check it, we need something more precise. For example, the number of the day. We particularly know that the first day (Sunday) is a weekend! That is:

if (TODAY == 1): We go cycling

Remember, the operator == compares two values. When they are equal, the result of the statement will be True.

So, ensure that there is at least one command of every known block "Input - Process - Output" and design the algorithm. I suggest the following version:

  1. By using int(input()), we'll ask user to enter the number of the day. We'll store this value in the variable day. Since the number of the day is integer, we must use the function of the type conversion int() with input().
  2. We'll also use if to check:

Don't forget that the interface of the program must be as simple as possible and understandable for a little child of for a granny. There is our code, type it and then launch. Make sure you do everything accurately. The print() commands are intended with four spaces from if they belong to:

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

The result is:

Enter the number of the day of the week: 1 Today is a weekend. We go cycling.

If something goes wrong, check the syntax. All colons, brackets, commas, characters must look like here.


THE ELSE BLOCK


The else block is related to the if statement. It is executed when the main condition with if is false:

if (logical statement): Block of commands №1 else: Block of commands №2

When the logical statement takes the value True, Block of commands №1 is executed

When the logical statement takes the value False, then Block of commands №2 is executed

Let's expand our previous program by adding phrase "Today is a weekday" if the entered day isn't Sunday.

To do this, we should add the else block to the first condition. If the day is 1, then the program will output the message about the weekend. Else it will output the message about the weekday.

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

Analyze what's going on if you enter non-existent day? For example, -1.

Answer

The result of entering -1 into the program is:

Enter the number of the day of the week: -1 Today is a weekday. The number of the day is incorrect.
Why does it work like this? Where does the "extra" inscription come from?

Think about it. When the value is -1, the else block of the if (day == 1): condition is executed, because (-1 == 1) is false.

The program continues to work checking if (day < 1): and if (day > 7):, and it outputs the relevant string when the true value in (day < 1) appears.


Having considered the logical confusion, analyze the code and find the three blocks - data input, data processing and data output.



CONDI­TION INSIDE ANOTHER CONDI­TION


To solve the problem with "extra line", let's take the opportunity to put a new condition inside another conditional statement.

The condition inside another condition is called nested. The nested condition is executed only when "external" condition is executed, i.e. the result of the logical statement is true.

It looks like this:

if (logical statement): Commands of the main condition (if required) if (logical statement): Commands of the nested condition else: (if required) Commands №2 of the nested condition else: (if required) Commands №2 of the main condition

I'll emphasize that blocky structure is defined by four spaces intend. Thus you can create an infinite number of nested conditions, for example:

if (logical statement): if (logical statement): if (logical statement): if (logical statement): if (logical statement): A block of commands, finally!

The main thing is not to get lost in logic and intends. The block of commands in the example above with many nested conditions will be executed only when (select correct answer):

  1. Every logical statement is True.
  2. Every logical statement is False.
  3. No matter what the previous logical statements are. As long as the condition before the block of commands is true, it will be executed.

Answer

1. Every statement must be true, because the next if will run only when the condition before is true.


We'll modify the program so that it doesn't display excess lines:

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

The results of the program (for different values):

Enter the number of the day of the week: 5 Today is a weekday. >>> Enter the number of the day of the week: -1 The number of the day is incorrect. >>> Enter the number of the day of the week: 8 The number of the day is incorrect. >>> Enter the number of the day of the week: 7 Today is a weekend. We go cycling.

Certainly, the code became much more difficult. It requires a little more efforts to figure it out. As soon as you feel that you have grasped the logic and the tricks of condition construct, try to solve the task:

The task: user enters vehicle speed. Define whether the driver exceeds the speed limit 60 km/h. Remember: it's impossible to enter neither negative values nor unbelievably great speed like 300 km/h. If the entered value is 0, then the vehicle isn't moving. The program should display all the information.

Check the answer only when you write your own version:

The program: does the driver violate the rules?

speed = int(input("Enter vehicle speed: ")) if (speed > 300): print("It isn't a plane. The entered speed is incorrect.") else: if (speed > 60): print("The driver violates the rules! Fine him, FINE!") else: if (speed == 0): print("The vehicle isn't moving. Like a stone. A stationary stone.") else: if (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.")




THE ELIF BLOCK


Nested conditions look bulky. We can streamline and make them more understandable by using the elif construction that may be interpreted as "ELSE-IF".

The construction is related to the if block, and it is written before else (if else is used).

The else and elif blocks aren't compulsory. Condition may exist and work successfully without them. Just don't get lost in the indents!

The syntax is:

if (logical statement №1): Block of commands №1 elif (logical statement №2): Block of commands №2 elif (logical statement №...): Block of commands №... elif (logical statement №n): Block of commands № n else: Block of commands ELSE

When you use elif, all logical statements must be different, otherwise elif makes no sense.

The construction elif is the same to else-if, but it's written more understandable. For example, this:

if (logical statement №1): Block of commands №1 else: if (logical statement №2): Block of commands №2 else: Block of commands №3

... is equal to this:

if (logical statement №1): Block of commands №1 elif (logical statement №2): Block of commands №2 else: Block of commands №3

The last is written more accurate and understandable for a programmer. It's important. Soon you will face with the need to analyze quite large blocks of code. The simpler the idea of ​​the algorithm is expressed, the simpler the algorithm is written in the programming language, the easier it is for you. Easier to find mistakes, to correct, to complement or to reduce the program. Pity yourself - write simpler!

If logical statement №1 is false, then logical statement №2 starts being checked. If it's false too, then block of commands №3 after else will be executed.

Else won't be executed if at least one of the logical statements is true.

Let's not waste time and rewrite the code about cycling and weekends. Notice that it became shorter and more comfortable for perception:

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

Here you can see implementation of one of the principles of the Python language, demonstration of "Monty Python's Flying Circus" magic: simplification of unnecessarily complex.


DOES THE DRIVER VIO­LATE THE RULES?


Rewrite the program using elif. The finished text can be viewed only after you create your own version. Or as soon as you reach an impasse, which is unlikely.

The program: does the driver violate the rules?

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


Further we'll deal with complex statements. They are complex not because they are more complicated than the material presented here, but because they consist of several statements and are combined by special logical operators not, and, or. It will be interesting!


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