Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Conditional Expression | Python Ternary Operator
Conditional Statements in Python

Conditional ExpressionConditional Expression

At times, we may need to assign different values to a variable based on specific conditions. Achieving this efficiently can be done in just one line of code. Let's explore a few approaches to grasp this concept more effectively.

Example 1:

Example 2:

Have you observed the distinction? The second method is not only more elegant but also more convenient, condensing it into just one line instead of four!

Conditional expressions, also known as Python's ternary operator, act as decision-making tools and adhere to the following syntax:

Let's practice!

Task

Your friend wants to choose the car to buy, and you can help. He has a certain amount of money for this purchase. We know how much both cars cost.

  1. Assign the brand name your friend will buy to the variable car_to_buy;
  2. The decision is based on the car's cost and your friend's amount of money;
  3. Print the car's brand that suits the condition;
  4. Your friend has an amount that is enough at least for one car.

Note

We will compare the amount of money with the cost of the more expensive car.

Fill in the blanks, please.

Everything was clear?

Section 4. Chapter 1
toggle bottom row
course content

Course Content

Conditional Statements in Python

Conditional ExpressionConditional Expression

At times, we may need to assign different values to a variable based on specific conditions. Achieving this efficiently can be done in just one line of code. Let's explore a few approaches to grasp this concept more effectively.

Example 1:

Example 2:

Have you observed the distinction? The second method is not only more elegant but also more convenient, condensing it into just one line instead of four!

Conditional expressions, also known as Python's ternary operator, act as decision-making tools and adhere to the following syntax:

Let's practice!

Task

Your friend wants to choose the car to buy, and you can help. He has a certain amount of money for this purchase. We know how much both cars cost.

  1. Assign the brand name your friend will buy to the variable car_to_buy;
  2. The decision is based on the car's cost and your friend's amount of money;
  3. Print the car's brand that suits the condition;
  4. Your friend has an amount that is enough at least for one car.

Note

We will compare the amount of money with the cost of the more expensive car.

Fill in the blanks, please.

Everything was clear?

Section 4. Chapter 1
toggle bottom row
some-alt