카테고리
coding

Python conditional statements (using if, dictionary)

Let's take a quick look at Python conditional statements.

if statement

test = 5

if test < 10:
    print("It's True.")

Here is the result:

It's True.

An if statement with only one condition.

Since 10 is less than 5, the condition is true and the phrase ‘It’s True.’ is printed.

test = 15

if test < 10:
    print("The first condition is True.")
elif test < 20:
    print("The second condition is True.")

Here is the result:

The second condition is True.

The above case is an if/elif statement with two conditions.

If there are two or more conditions, you can add them with an elif statement.

Here, 15 is not less than 10, so the first condition is not satisfied, and since it is less than 20, the second condition is satisfied and ‘The second condition is True.’ is output.

If both conditions are not satisfied, nothing is output.

test = 30

if test < 10:
    print("The first condition is True.")
elif test == 20:
    print("The second condition is True.")
else:
    print("Not all are True.")

Here is the result:

Not all are True.

An else statement has been added to handle cases where all conditions are not satisfied.

Since 30 is not less than 10 and not equal to 20, it outputs 'Not all are True.' written in the else statement.

Use of dictionary data type

test = 5

result = {0:"zero", 5:"five", 10:"ten"}.get(test, "default")
print(result)

Here is the result:

five

If you use the dictionary data type, you can perform a function similar to the switch statement that existed based on the C language.

If the data matches the key included in the dictionary, we used the principle to get the value of that key.

If no matching value is found, default is output.

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish