Simple usage of condition judgment statements in Python, python statements

Source: Internet
Author: User

Simple usage of condition judgment statements in Python, python statements

The simplest Condition Statement:

if expression:   expr_true_suite

As shown above, if is a keyword, expression is a condition expression, and conditional expressions support multi-condition judgment. You can use the boolean operators and, or, and not to connect. expr_true_suite is a code block. if expression is true, it is executed, if a code block contains only one row, the entire Condition Statement above can be written to one row, but the readability is poor.
Conditional statements with elif and else:

if expression1:   expr1_true_suiteelif expression2:   expr2_true_suiteelif expressionN:   exprN_true_suiteelse:   none_of_the_above_suite

As mentioned above, the syntax is similar to the conditional statements in other languages. elif and else are optional.
Conditional expressions implement ternary operators:
In C/C ++, the ternary operator is as follows (when E is set, X is executed; otherwise, Y is executed )--

E ? X : Y

Ternary operator simulated by python --

(E and [X] or [Y])[0]

Implementation of python ternary operators --

X if E else Y

Let's look at several judgment instances:

>>> if 1 < x < 2:   print('True')     True 

And indicates and

Or indicates or >>> x 2 >>> if x = 2 or x = 3: print (x) 2

If B is true, return a. Otherwise, return c.

a if b else c>>> 'True' if 1 < x <2 els


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.