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

Sveip for å vise menyen

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!

Oppgave

Swipe to start coding

Løsning

Switch to desktopBytt til skrivebordet for virkelighetspraksisFortsett der du er med et av alternativene nedenfor
Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 4. Kapittel 1
Vi beklager at noe gikk galt. Hva skjedde?

Spør AI

expand
ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

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!

Oppgave

Swipe to start coding

Løsning

Switch to desktopBytt til skrivebordet for virkelighetspraksisFortsett der du er med et av alternativene nedenfor
Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 4. Kapittel 1
Switch to desktopBytt til skrivebordet for virkelighetspraksisFortsett der du er med et av alternativene nedenfor
Vi beklager at noe gikk galt. Hva skjedde?
some-alt