Arvutiteaduse instituut
  1. Kursused
  2. 2025/26 sügis
  3. Programmeerimise alused (MTAT.03.236)
EN
Logi sisse

Programmeerimise alused 2025/26 sügis

  • Home Page
  • Introduction
  • Expressions
  • Conditional Execution
  • Functions
  • Iterations
  • Strings
  • Files
  • Lists
  • Graphics?
< previousTable of Contentsnext >

3.3 CONDITIONAL LOGIC

The if statement allows for the conditional execution of code. It can be used to alter the order of execution in a program. It enables a program to execute certain blocks of code based on whether a specified condition is True or False. It helps us to solve more complex problems gracefully.

IF STATEMENT

The basic syntax of an if-statement in Python is as follows.


if condition:
    # Block of code to execute if the condition is True

  • The condition is an expression that evaluates to True or False.
  • The colon (:) after the condition is required and signifies the start of the block of code that will execute if the condition is True.
  • The code block under the if statement must be indented. As mentioned in the previous chapter, Python uses indentation to define blocks of code.

A simple example:


has_drivers_license = True
if has_drivers_license:
    print("You are eligible to drive.")

When evaluating the condition, Python will check whether the value of the has_drivers_license variable is True or False. If it is True, the print statement within the if block will be executed.

This is how a flowchart of such a program would look. It describes the steps involved in the execution of the program. It demonstrates that first the test condition is evaluated and a decision is made according to the truth value of the condition. If the condition is true, then the body of the if statement is executed, otherwise the program skips to the statement after the if statement.

Flowchart. If-statement flowchart. geeksforgeeks.org

ELSE CLAUSE

You can use an else clause to execute a different code block when the if condition is False. The else clause states what the program should do if the condition was not met. Here’s a brief example. Note that the else block is only triggered if the initial condition after if is evaluated to False.


age = 15
if age >= 18:
    print("You are eligible to vote in the EU Parliament elections")
else:
    print("You are not eligible to vote yet in the EU Parliament elections! Wait a few more years”)

To give you a better sense of the order of operations of if-else statements, here's a flowchart of execution steps. As we can see it's quite similar to the if statement flowchart. If the if condition is @True, the body of the if statement will be executed. However, now we can add an additional code block that will be executed even when the if condition is False. The else body will only be executed when if is False.

Flowchart. If-else statement flowchart. geeksforgeeks.org

THE ELIF CLAUSE

The elif clause allows you to check multiple conditions sequentially within an if-else block. When you have more than two possible outcomes based on different conditions, elif allows you to handle these. All the conditions are checked sequentially, and there can be as many elif blocks as you need. However, when your solution comprises too many elif statements, you should ask yourself whether the path you’ve taken to solve the problem is the best. The else clause at the end is also optional. However, in most cases, you will want to communicate something to the user in case none of the previous conditions are met.


traffic_light = "yellow"

if traffic_light == "green":
    print("Go")
elif traffic_light == "yellow":
    print("Caution")
elif traffic_light == "red":
    print("Stop")
else:
    print("Invalid traffic light signal")

Here's a flowchart to visualize the execution flow of this example. The elif statement allows us to add more various conditions that we would want to check for. An elif statement will executed conditions preceding it have been False. The else statement is only executed if neither the if or elif conditions are met.

Flowchart. If-elif statement flowchart. geeksforgeeks.org

NESTED CONDITIONAL STATEMENTS

Nested if statements allow for more complex decision-making processes within your programs. A nested if statement is an if statement inside another if (or elif) statement. This structure enables programmers to check multiple conditions and make decisions based on those conditions in a hierarchical manner.


number = 10

if number > 0:
    print("The number is positive.")
    if number % 2 == 0:
        print("The number is even.")
    else:
        print("The number is odd.")
else:
    print("The number is not positive.")


Here's a flowchart of the execution of this program. Here we see that we want to check for two conditions, whether the number is positive and whether it is even. First Python evaluates the condition of the outer if statement. If that is True, the program proceeds to the body of the outer if statement. It prints out to the console the message The number is positive. and proceeds to the next if statement. If the number is even, the inner if statement body is executed. If it's not even, then the inner else statement is triggered. Next, the program proceeds to the statement below the outer if block. The outer else statement is only triggered if the number is not positive.

Flowchart. Nested if statement flowchart. geeksforgeeks.org

However, it’s important to note that nested if statements can make your code hard to understand and maintain. Hence, you should always be careful and only use nested statements if necessary.

KEY THINGS TO REMEMBER

  • elif can only be used after an if statement and before an else statement.
  • You can use as many elif statements as you need to cover different conditions.
  • Only the first True condition's block among the if and elif@@ statements will execute, and Python will skip the rest, including the else block, if present.
  • Make sure to use nested statements only when necessary.

SELF-CONTROL EXERCISES

< previousTable of Contentsnext >

  • Arvutiteaduse instituut
  • Loodus- ja täppisteaduste valdkond
  • Tartu Ülikool
Tehniliste probleemide või küsimuste korral kirjuta:

Kursuse sisu ja korralduslike küsimustega pöörduge kursuse korraldajate poole.
Õppematerjalide varalised autoriõigused kuuluvad Tartu Ülikoolile. Õppematerjalide kasutamine on lubatud autoriõiguse seaduses ettenähtud teose vaba kasutamise eesmärkidel ja tingimustel. Õppematerjalide kasutamisel on kasutaja kohustatud viitama õppematerjalide autorile.
Õppematerjalide kasutamine muudel eesmärkidel on lubatud ainult Tartu Ülikooli eelneval kirjalikul nõusolekul.
Courses’i keskkonna kasutustingimused