Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use conditional operator in Python

Shulou Source: shulou.com Published: 2022-06-02 08:17:10 09月17日 Update

This article shows you how to use conditional operators in Python, which is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Code implementation

A = 30b = 5cm print ('an is larger!') If a > b else print ('b is larger!') # get a larger value between an and b max = an if a > b else bprint (max)

Code run output:

fifty

Program analysis

# conditional operator (ternary operator)

# Syntax: statement 1 if conditional expression else statement 2

# execution process:

When the # conditional operator is executed, it evaluates the conditional expression first.

# if the result is True, execute statement 1 and return the execution result

# if the result is False, execute statement 2 and return the execution result

For example, the following statement:

# print ('Hello') if False else print ('Hello')

The output result is Hello, because the statement after if is first judged to be false, so print ("Hello") does not execute, then the statement after else is executed.

The above is how to use conditional operators in Python. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Tags: Statements conditions operators operations results code hello content skills knowledge expressions output concise large concise in between that is articles more process Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei macOS NVidia Microsoft Docker