Conditional if statement in Python. Syntax, else/elif blocks, examples

In the process of learning to program, it is often necessary to create programs that are not so easy to apply in real life. After all, from time to time you have to follow instructions only under certain conditions. To be able to implement this in the program, all languages ​​have control statements. With their help, you can control the flow of code execution, creating loops or performing certain actions only when a certain condition is true.

Today we will talk about the if statement, which checks the current situation for a certain condition, and based on this information, makes decisions about further actions.

Types of Control Statements

In general, if is not the only statement that controls the flow of a program. As well as he himself can be a component of a larger chain of operators.

There are also loops and statements that control the process of its execution. Today we will only talk about the conditional operator and the chains in which it can participate.

In programming, there is such a thing as branching. It is precisely this that means a sequence of commands that is executed only if a certain condition is true. The criteria themselves may be different:

  1. Equality of a variable to a certain value.
  2. Performing a specific action.
  3. Application state (collapsed or not).

The spectrum can be much larger. Conditional statements come in several types:

  1. With one branch. That is, a single check is performed, as a result of which certain actions are performed.
  2. With two or more branches. If criterion 1 is true, then check criterion 2. If it is true, then check 3. And so, perform as many checks as required.
  3. With several conditions. Everything is simple here. The interpreter checks for multiple conditions or one of them.

if statement

The structure of the if statement is similar in all languages. However, in Python, its syntax is somewhat different from all the others:

if condition:

    <входящее выражение 1>

    <входящее выражение 2>

<не входящее выражение>

First, the operator itself is declared, after which the condition under which it starts working is written. The condition can be either true or false.

This is followed by a block with commands. If it immediately follows a criterion to be met, then the corresponding sequence of commands is called an if block. You can use any number of commands in it.

Attention! The indentation within all if block commands must be the same size. The block boundaries are determined by the indents. 

According to the language documentation, the indentation is 4 spaces. 

How does this operator work? When the interpreter sees the if word, it immediately checks the expression against the user-specified criteria. If this is the case, then he starts looking for instructions and following them. Otherwise, all commands from this block are skipped.

If a statement after the condition is not indented, it is not treated as an if block. In our situation, this line is . Therefore, regardless of the result of the check, this line will be executed.

Here is a code snippet for an example of how this operator works.

number = int(input(“Enter a number: “))

if number > 10:

    print(“The number is greater than 10”)

This program prompts the user for a number and checks if it is greater than 10. If so, it returns the appropriate information. For example, if the user enters the number 5, then the program will simply end, and that’s it.

But if you specify the number 100, then the interpreter will understand that it is more than ten, and report it.

Attention! In our case, if the condition is false, the program stops, because no commands are given after the instruction.

There is only one command in the above code. But there are many more of them. The only requirement is to indent.

Now let’s analyze this sequence of commands.

number = int(input(“Write a number: “))

if number > 10:

    print(“first line”)

    print(“second line”)

    print(“third line”)

print(“The line that is executed, regardless of the number entered”)

print(“End application”)

Try to guess what the output will be if you enter the values ​​2, 5, 10, 15, 50.

As you can see, if the number entered by the user is more than ten, then three lines are output + one with the text “Run every time …” and one “End”, and if less than ten, then only one, with a different text. Only lines 3,4,5 will be executed if true. However, the last two lines will be written no matter what number the user specifies.

If you use the statements directly in the console, the result will be different. The interpreter immediately turns on the multi-line mode if, after specifying the verification criterion, press Enter.

Suppose we have written the following sequence of commands.

>>>

>>> n = 100

>>> if n > 10:

After that, we will see that >>> has been replaced by ellipsis. This means that the multiline input mode is enabled. In simple words, if you press Enter, you will be transferred to the input of the second stage of the instruction. 

And in order to exit this block, you need to add one more construction to the block if.

>>>

>>> n = 100

>>> if n > 10:

…     print(«n v 10»)

If the condition is not true, the program ends. This is a problem, since the user may perceive such a program as having closed due to a failure. Therefore, it is necessary to give feedback to the user. For this, a link is used if-else.

expression operator if-else

This operator allows you to implement a link: if the expression matches a certain rule, perform these actions, and if not, then others. That is, it allows you to divide the flow of the program into two roads. The syntax is intuitive:

if  condition:

    # if block

    statement 1

    statement 2

    and so on

else:

    # else block

    statement 3

    statement 4

    and so on:

Let’s explain how this operator works. First, the standard statement is executed in the thread yew, checking whether it matches condition “true” or “false”. Further actions depend on the results of the check. If true, the instruction that is in the sequence of instructions following the condition is executed directly. yew, if it is false, then else

This way you can handle errors. For example, the user needs to enter a radius. Obviously, it can only be a number with a plus sign, or it’s a null value. If it is less than 0, then you need to issue a message asking you to enter a positive number. 

Here is the code that implements this task. But there is one mistake here. Try to guess which one. 

radius = int(input(“Enter radius: “))

if radius >= 0:

    print(“Circumference = “, 2 * 3.14 * radius)

    print(“Area = “, 3.14 * radius ** 2)

    else:

        print(“Please enter a positive number”)

Indentation mismatch error. If и Else must be located without them or with the same number of them (depending on whether they are nested or not).

Let’s give another use case (where everything will be correct with operator alignment) – an application element that checks a password.

password = input(“Enter password: “)

if password == «sshh»:

    print(“Welcome”)

else:

    print(“Access denied”)

This instruction skips the person further if the password is sshh. If any other combination of letters and numbers, then it displays the message “Access denied”.

statement-expression if-elif-else

Only if several conditions are not true, the statement that is in the block is executed. else. This expression works like this.

if condition_1:

    # if block

    statement

    statement

    more statement

elif condition_2:

    # first elif block

    statement

    statement

    more statement

elif condition_3:

    # second elif block

    statement

    statement

    more statement

else

    statement

    statement

    more statement

You can specify any number of additional conditions.

Nested statements

Another way to implement multiple conditions is to insert additional condition checks in the if block.

Operator if inside another condition block

gre_score = int(input(“Enter your current credit limit”))

per_grad = int(input(“Enter your credit rating: “))

if per_grad > 70:

    # outer if block

        if gre_score > 150:

            # inner if block

    print(“Congratulations, you have received a loan”)

else:

    print(“Sorry, you are not eligible for a loan”)

This program does performs a credit rating check. If it is less than 70, the program reports that the user is not eligible for credit. If it is greater, a second check is performed to see if the current credit limit is greater than 150. If yes, then a message is displayed that the loan has been issued.

If both values ​​are false, then a message is displayed that the user does not have the possibility of obtaining a loan. 

Now let’s rework that program a bit.

gre_score = int(input(“Enter current limit: “))

per_grad = int(input(“Enter credit score: “))

if per_grad > 70:

    if gre_score > 150:

        print(“Congratulations, you have received a loan”)

    else:

        print(“Your credit limit is low”)

else:

    print(“Sorry, you are not eligible for credit”)

The code itself is very similar, but nested if also provides an algorithm in case the condition from it turns out to be false. That is, the limit on the card is insufficient, but the credit history is good, the message “You have a low credit rating” is displayed.

if-else statement inside a condition else

Let’s make another program that determines a student’s grade based on test scores.

score = int(input(“Enter your score: “))

if score >= 90:

    print(“Great! Your grade is A”)

else:

    if score >= 80:

print(“Great! Your grade is B”)

    else:

if score >= 70:

    print(“Good! Your grade is C”)

else:

    if score >= 60:

print(“Your grade is D. It’s worth repeating the material.”)

    else:

print(“You failed the exam”)

The application first checks to see if the score is greater than or equal to 90. If yes, then it returns an A grade. If this condition is false, then subsequent checks are performed. We see that the algorithm is almost the same at first glance. So instead of checking inside else better to use a combination if-elif-else.

So the operator if performs a very important function – it makes sure that certain pieces of code are executed only if there is a need for it. It is impossible to imagine programming without it, because even the simplest algorithms require forks like “if you go to the left, you will find it, and if you go to the right, then you need to do this and that.”

Leave a Reply