Python if..else Statement

[ad_1]

Decision-making is one of the most fundamental concepts of computer programming. Python supports the common flow control statements found in other languages, with some modifications. The if control statement is one of the most basic and well-known statements used to execute code based on a specific condition.

In this article, we will go over the basics of the if statement in Python.

Python if Statement #

The most basic form of the if statement in Python is as follows:

The if statement starts with the if keyword followed by the conditional expression.

The EXPRESSION must be followed by (:) colon. If the EXPRESSION evaluates to True, the STATEMENT gets executed. If EXPRESSION returns False, nothing happens; the STATEMENT gets ignored. STATEMENT be any statement, including multiple statements or further nested if statements. To execute no statements, use the pass statement.

The STATEMENT block starts with an indentation and ends with the first unindented line. Most people choose to use either 4-space or 2-space indentation. The official Style Guide for Python Code
recommends using 4-spaces per indentation level and avoiding mixing tabs and spaces for indentation.

Let’s look at the following example script that checks whether a given number is greater than 5.

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

if number > 5:
    print(number, 'is greater than 5.')

Save the code in a file and run it from the command line:

python test.py

The script will prompt you to enter a number. For example, if you enter 10, the conditional expression will evaluate to True (10 is greater than 5), and the print function will be executed.

10 is greater than 5.

Python supports standard comparison operations:

  • a == b – True if a and b are equal.
  • a != b – True if a and b are not equal.
  • a > b – True if a is greater than b.
  • a >= b – True if a is equal or greater than b.
  • a < b – True if a is less than b.
  • a <= b – True if a is equal or less than b.

You can also use the in keyword to check if a value is present in an iterable
(string, list, tuple
, dictionary, etc.):

s = 'linuxize'
if 'ze' in s:
    print('True.')

Here is another example using a dictionary:

d = {'a': 2, 'b': 4}
if 'a' in d:
    print('True.')

When used on a dictionary, the in keyword checks whether the dictionary has a specific key.

To negate the conditional expression use the logical not operator:

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

if not number < 5:
    print(number, 'is greater than 5.')

if..else Statement #

An if..else statement evaluates a condition and executes one of the two statements depending on the result.

The Python if..else statement takes the following form:

if EXPRESSION:
    STATEMENT1
else:
    STATEMENT2

If EXPRESSION evaluates to True, STATEMENT1 is executed. Otherwise, if EXPRESSION returns False, STATEMENT2 is executed. You can have only one else clause in the statement.

The else keyword must end with (:) colon and to be at the same indentation level as the corresponding if keyword.

Let’s add an else clause to the previous example script:

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

if number > 5:
    print(number, 'is greater than 5.')
else:
    print(number, 'is equal or less than 5.')

If you run the code and enter a number, the script will print a different message based on whether the number is greater or less/equal to 5.

if..elif..else Statement #

The elif keyword is short for else if.

The Python if..elif..else statement takes the following form:

if EXPRESSION1:
    STATEMENT1
elif: EXPRESSION2:
    STATEMENT2
else:
    STATEMENT3

If EXPRESSION1 evaluates to True, the STATEMENTS1 is executed. If the EXPRESSION2 evaluates to True, the STATEMENTS2 is executed. If none of the expressions evaluate to True, the STATEMENTS3 is executed.

The elif keyword must end with (:) colon and be at the same indentation level as the corresponding if keyword. You can have one or more elif clauses in the statement. The else clause is optional. If the else clause is not used, and all the expressions evaluate to False, none of the statements is executed.

The conditions are evaluated sequentially. Once a condition returns True, the remaining conditions are not performed, and the program control moves to the end of the if statements.

Let’s add an elif clause to the previous script:

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

if number > 5:
    print(number, 'is greater than 5.')
elif number < 5:
    print(number, 'is less than 5.')
else:
    print(number, 'is equal to 5.')

Unlike most programming languages, Python doesn’t have switch or case statements. A sequence of multiple elif statements can be used as a substitute for the switch or case
.

Nested if Statements #

Python allows you to nest if statements within if statements. Generally, you should always avoid excessive indentation and try to use elif instead of nesting if statements.

The following script will prompt you to enter three numbers and will print the largest number among the numbers.

number1 = int(input('Enter the first number: '))
number2 = int(input('Enter the second number: '))
number3 = int(input('Enter the third number: '))

if number1 > number2:
    if number1 > number3:
        print(number1, 'is the largest number.')
    else:
        print(number3, 'is the largest number.')
else:
    if number2 > number3:
        print(number2, 'is the largest number.')
    else:
        print(number3, 'is the largest number.')

Here is how the output will look like:

Enter the first number: 455 
Enter the second number: 567
Enter the third number: 354
567 is the largest number.

Multiple Conditions #

The logical or and and operators allow you to combine multiple conditions in the if statements.

Here is another version of the script to print the largest number among the three numbers. In this version, instead of the nested if statements, we will use the logical and operator and elif.

number1 = int(input('Enter the first number: '))
number2 = int(input('Enter the second number: '))
number3 = int(input('Enter the third number: '))

if number1 > number2 and number1 > number3:
    print(number1, 'is the largest number.')
elif number2 > number3 and number2 > number3:
    print(number2, 'is the largest number.')
else:
    print(number3, 'is the largest number.')

Conclusion #

The if, if..else and if..elif..else statements allow you to control the flow of the Python execution by evaluating given conditions.

If you have any questions or feedback, feel free to leave a comment.

[ad_2]

Source link

Related Posts

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.