Python ternary operator without else

Ternary Operator Without Else In Python

In this tutorial, we are going to learn about implementing a ternary operator without else in Python. Firstly, let us know about ternary operators.

Ternary Operators:-

To learn more click: Ternary Operator in Python. Python versions 2.5 or later supports ternary operators. Because it was added in Python 2.5. Ternary operators allow testing a condition in a single line. It replaces the multiline if-else conditions by making the code compact.

[on true] if [expression] else [on false]

As a result, we get ‘a’ as output. Because, if the condition is true then it prints the expression before it. If the condition is false then it prints the condition after else keyword. Now let us see how to implement a ternary operator without else keyword.

Implementing ternary operator without else keyword:-

Similarly, we can also implement it without else keyword but with the help of any of the following:- Dictionaries, or lambda function. Let’s see how to implement it.

Implementing with Dictionaries:-

In the above code if the condition in the print statement is true it will print the value of the True key in the dictionary. If the condition is false then it will print the value of the False key in the dictionary. So, as a result, we get ‘a’ as output.

Implementing with Lambda Function:-

x, y = 'a', 'b' print((lambda: y, lambda: x)[x

In the above code if the condition in the function is true it executes the 2nd lambda function. If the condition is false then it executes the first lambda function.

Источник

One line if without else in Python

If you don’t have an else statement, then you can write a one line if statement in Python by removing the line break as follows:

  1. The regular if statement in one line
  2. Using the ternary operator syntax
  3. Shorthand syntax with the and operator

This tutorial shows you examples of writing intuitive one line if statements in practice.

1. One line if statement

In the following example, the if statement prints something if x value is greater than 10 :

 Now here’s how you convert the code into one line if statement:
Yup! Just remove the line break and you’re good to go.

If you have more than one line in the if body, you can use a semicolon to mark the end of the statements. See the example below:

  But keep in mind that this code violates Python coding conventions by defining multiple statements in one line.

It’s also harder to read when you have complex statements inside the if body. Still, the code works well when you have simple conditionals.

2. Ternary operator syntax without else

The Python ternary operator is used to create a one line if-else statement.

It comes in handy when you need to write a short and simple if-else statement as follows:

You can read this article to learn more about how ternary operators work in Python.

You can use the ternary operator to write a one line if statement without an else as follows:

By returning None , Python will do nothing when the else statement is executed.

Although this one line if statement works, it’s not recommended when you have an assignment in your if body as follows:

 Using the ternary operator, you still need to assign the original value of y in the else statement as follows:
The ternary operator doesn’t allow you to discard the else statement, so this code redundantly assigns the value of y to y in the else statement.

It’s better to use a regular if statement as follows:

Using a regular if statement has less repetition and easier to read.

3. Shorthand syntax with the and operator

The and operator can be used to shorthand an if statement because this operator executes the second operand only when the first operand returns True .

Suppose you have an if statement as follows:

 You can use the and operator to rewrite the code above as follows:
The print() function above is only executed when the expression on the left side of the and operator returns True .

But this method also falls short when you need to do an assignment as it will raise an error:

If your conditional involves an assignment, then you need to use the regular if statement.

Conclusion

This tutorial has shown you examples of writing a one line if without else statement in Python.

In practice, writing a one line if statement is discouraged as it means you’re writing at least two statements in one line: the condition and the code to run when that condition is True .

Just because you can, doesn’t mean you should. Writing a regular if statement with line breaks and indents provides you with a clean and consistent way to define conditionals in your code.

I hope this tutorial helps. Happy coding! 👍

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Источник

Inline If in Python: The Ternary Operator in Python

Inline If Python Cover Image

In this tutorial, you’ll learn how to create inline if statements in Python. This is often known as the Python ternary operator, which allows you to execute conditional if statements in a single line, allowing statements to take up less space and often be written in my easy-to-understand syntax! Let’s take a look at what you’ll learn.

The Quick Answer: Use the Python Ternary Operator

Quick Answer - Inline If Python

What is the Python Ternary Operator?

A ternary operator is an inline statement that evaluates a condition and returns one of two outputs. It’s an operator that’s often used in many programming languages, including Python, as well as math. The Python ternary operator has been around since Python 2.5, despite being delayed multiple times.

How Inline If Python Works

The syntax of the Python ternary operator is a little different than that of other languages. Let’s take a look at what it looks like:

Now let’s take a look at how you can actually write an inline if statement in Python.

How Do you Write an Inline If Statement in Python?

Before we dive into writing an inline if statement in Python, let’s take a look at how if statements actually work in Python. With an if statement you must include an if , but you can also choose to include an else statement, as well as one more of else-ifs, which in Python are written as elif .

The traditional Python if statement looks like this:

x = True if x is True: y=10 else: y=20 print(y) # Returns 10

This can be a little cumbersome to write, especially if you conditions are very simple. Because of this, inline if statements in Python can be really helpful to help you write your code faster.

Let’s take a look at how we can accomplish this in Python:

x = True y = 10 if x else 20 print(y) # Returns 10

This is significantly easier to write. Let’s break this down a little bit:

  • We assign a value to x , which will be evaluated
  • We declare a variable, y , which we assign to the value of 10, if x is True. Otherwise, we assign it a value of 20.

We can see how this is written out in a much more plain language than a for-loop that may require multiple lines, thereby wasting space.

Tip! This is quite similar to how you’d written a list comprehension. If you want to learn more about Python List Comprehensions, check out my in-depth tutorial here. If you want to learn more about Python for-loops, check out my in-depth guide here.

Now that you know how to write a basic inline if statement in Python, let’s see how you can simplify it even further by omitting the else statement.

How To Write an Inline If Statement Without an Else Statement

Now that you know how to write an inline if statement in Python with an else clause, let’s take a look at how we can do this in Python.

Before we do this, let’s see how we can do this with a traditional if statement in Python

x = True if x is True: y=10 print(y) # Returns 10

You can see that this still requires you to write two lines. But we know better – we can easily cut this down to a single line. Let’s get started!

x = True if x: y = 10 print(y) # Returns 10

We can see here that really what this accomplishes is remove the line break between the if line and the code it executes.

Now let’s take a look at how we can even include an elif clause in our inline if statements in Python!

How to Write an Inline If Statement With an Elif Statement

Including an else-if, or elif , in your Python inline if statement is a little less intuitive. But it’s definitely doable! So let’s get started. Let’s imagine we want to write this if-statement:

x = 3 if x == 1: y = 10 elif x == 2: y = 20 else: y = 30 print(y) # Returns 30

Let’s see how we can easily turn this into an inline if statement in Python:

x = 3 y = 10 if x == 1 else (20 if x == 20 else 30) print(y) # Returns 10

This is a bit different than what we’ve seen so far, so let’s break it down a bit:

  • First, we evaluate is x == 1. If that’s true, the conditions end and y = 10.
  • Otherwise, we create another condition in brackets
  • First we check if x == 20, and if that’s true, then y = 20. Note that we did not repeated y= here.
  • Finally, if neither of the other decisions are true, we assign 30 to y

This is definitely a bit more complex to read, so you may be better off creating a traditional if statement.

Conclusion

In this post, you learned how to create inline if statement in Python! You learned about the Python ternary operator and how it works. You also learned how to create inline if statements with else statements, without else statements, as well as with else if statements.

To learn more about Python ternary operators, check out the official documentation here.

Источник

Читайте также:  Вывод компьютерного кода на сайте с помощью тега code
Оцените статью