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

Scorri per mostrare il menu

book
Conditional 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:

123456789
age = 23 status = '' if age >= 18: status = 'Adult' else: status = 'Not adult' print(status)
copy

Example 2:

12345
age = 15 status = 'Adult' if age >= 18 else 'Not Adult' print(status)
copy

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:

python

Let's practice!

Compito

Swipe to start coding

Soluzione

Switch to desktopCambia al desktop per esercitarti nel mondo realeContinua da dove ti trovi utilizzando una delle opzioni seguenti
Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 1

Chieda ad AI

expand
ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

book
Conditional 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:

123456789
age = 23 status = '' if age >= 18: status = 'Adult' else: status = 'Not adult' print(status)
copy

Example 2:

12345
age = 15 status = 'Adult' if age >= 18 else 'Not Adult' print(status)
copy

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:

python

Let's practice!

Compito

Swipe to start coding

Soluzione

Switch to desktopCambia al desktop per esercitarti nel mondo realeContinua da dove ti trovi utilizzando una delle opzioni seguenti
Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 1
Switch to desktopCambia al desktop per esercitarti nel mondo realeContinua da dove ti trovi utilizzando una delle opzioni seguenti
Siamo spiacenti che qualcosa sia andato storto. Cosa è successo?
some-alt