If-else in one line in Python

The if-else statement is one of the common statements of many programming languages like Python, C/C++, and Java. It is a conditional statement and is used to perform some action based on a condition.

With the if-else statement, we run a block of code based on the evaluation of a provided condition. If the condition is True, the code from the if block is executed, otherwise the code from the else block is executed.

We can also have an if-else ladder where we can use multiple elif statements to evaluate many conditions.

In some other programming languages, there also exists a ternary operator which can be thought of as a compact form of the if-else statements in one line. Python does not support this operator. However, we can use the if-else in one line in Python.

The syntax for if-else in one line in Python

To use the if-else in one line in Python, we can use the expression: a if condition else b. In this expression, a is evaluated if the condition is True. If the condition is false, then b is evaluated.

Let us use this as an example.

Output:

X is 10

In the above example,

  • The value of variable x is assigned using the single line if-else statement.
  • Since the condition is True, the value of x is assigned as 10.
  • We again use the if-else to print the value of x.
  • Since the condition is False, the expression of the else statement is evaluated.

This is the traditional way to use the if-else in one line in Python. There are other ways also to emulate this. However, it is not recommended to use these because there is less consistency and usually both the expressions are evaluated first.

Using tuples to emulate if-else in one line in Python

A tuple can store multiple items in Python. We can use tuple-indexing to emulate if-else in one line in Python. The expression for this is given as: (b,a)[condition]

We will use a tuple with two values. The value a is evaluated if the condition is True, and b for when it returns False.

See the code below.

Output:

10

The above code returns the value of x as 10 because the given condition is True.

Using dictionaries to emulate if-else in one line in Python

A dictionary contains key-value pairs. It can be used to perform if-else in one line in Python. This method is similar to the previous one. The expression used in this method: {True:a, False:b}[condition].

We will have a dictionary containing two keys, True and False. These keys will have some value associated with them. A condition will be evaluated in the [] and based on the returned Boolean value the corresponding element will be accessed.

We implement this in the code below.

Output:

10

The condition in the above example returns True. Hence, the value associated with the key True is retrieved from the dictionary.

Using and and or operator to emulate if-else in one line in Python

The and and or are logical operators in Python. The and operator returns True when both values are True and the latter returns True if at least one value is True.

We can use them to emulate if-else in one line in Python using the following expression. condition and a or b. In this expression, a is evaluated when the condition is True and b when it is False. However, this is not a consistent method.

The inconsistency arises when the value of a is False. During that case, b will be evaluated every time. Still, it can be used in simple cases.

For example,

Output:

10

Conclusion

This tutorial demonstrated the basics of the if-else statement and how to use if-else in one line in Python. We also demonstrated several methods to emulate the behavior of if-else in one line. These methods included the use of tuples, dictionaries, and logical operators.

Although these methods work similarly to if-else in one line in Python, their downside is that both the conditions are evaluated first before going to the condition. This is avoided in the if-else statements as one block is ignored based on the condition. Therefore, one should focus on the main syntax of if-else statement to use it in one line.

That’s all about If-else in one line in Python.

Was this post helpful?


import_contacts

You may also like:

Related Posts

  • 29 June

    Get Day Name from Date in Python

    Table of ContentsUse the Calendar Module to Get the Name of the Day in PythonUse the strftime() Method to Get the Name of the Day in PythonUse Pandas Timestamp Method to Get the Name of the Day in PythonUse the weekday() Method to Get the Name of the Day in PythonUse the isoweekday() Method to […]

  • 27 June

    Fill Array with Random Numbers in Python

    Table of ContentsFill array with random numbers in PythonWays to fill array with random numbers in PythonUsing the numpy.random.randint() function to fill array with random numbers in PythonUsing the numpy.random.Generator.integers() function to fill array with random numbers in PythonUsing the random.randint() function to fill array with random numbers in PythonConclusionWas this post helpful? Fill array […]

  • 25 June

    Convert Roman Number to Integer in Python

    Table of ContentsHow to Convert Roman Number to Integer in PythonHow to convert roman number to integer in python?Using the if...else statement to convert roman number to integer in Python.Using classes and a dictionary to convert roman number to integer in Python.Using the roman module to convert roman number to integer in Python.ConclusionWas this post […]

  • 11 June

    Remove Single Quotes from String in Python

    Table of ContentsRemove single quotes from string in Python.How to remove single quotes from string in Python?Using the replace() function to remove single quotes from string in Python.Using a for loop to remove single quotes from string in Python.Using the join() function to remove single quotes from string in Python.Using the re module functions to […]

  • 11 June

    Escape Backslash Character in Python

    Table of ContentsEscape backslash character in python.How to use escape backslash character in python?Using the escape backslash character in python to represent whitespace characters.Using the escape backslash character in python to turn special characters into ordinary characters.Using the escape backslash character in f-strings in Python.Using the escape backslash character in raw strings in Python.Was this […]

  • 11 June

    Break out of function in Python

    Table of ContentsBreak out of function in PythonHow to break out of function in Python?Using the return statement to break out of function in PythonUsing the try and except block to break out of function in PythonUsing the sys.exit() function to break out of function in PythonConclusionWas this post helpful? In this post, we will […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.