Python学习[02]

来源:互联网 发布:51单片机按键 编辑:程序博客网 时间:2024/05/17 07:35

[02]Learn Python——Conditionals & Control Flow


1.Compare Closely

Let’s start with the simplest aspect of control flow: comparators. There are six:

Equal to (==)
Not equal to (!=)
Less than (<)
Less than or equal to (<=)
Greater than (>)
Greater than or equal to (>=)
Comparators check if a value is (or is not) equal to, greater than (or equal to), or less than (or equal to) another value.

2.To Be and/or Not to Be

Boolean operators compare statements and result in boolean values. There are three boolean operators:

and, which checks if both the statements are True;
or, which checks if at least one of the statements is True;
not, which gives the opposite of the statement.

"""     Boolean Operators------------------------      True and True is TrueTrue and False is FalseFalse and True is FalseFalse and False is FalseTrue or True is TrueTrue or False is TrueFalse or True is TrueFalse or False is FalseNot True is FalseNot False is True"""

3.This and That (or This, But Not That!)

Boolean operators aren’t just evaluated from left to right. Just like with arithmetic operators, there’s an order of operations for boolean operators:

not is evaluated first;
and is evaluated next;
or is evaluated last.
For example, True or not False and False returns True.

4.Conditional Statement Syntax

if is a conditional statement that executes some specified code after checking if its expression is True.

Looking at the example above, in the event that some_function() returns True, then the indented block of code after it will be executed. In the event that it returns False, then the indented block will be skipped.

if some_function():  # block line one  # block line two  # et cetera

The else statement complements the if statement. An if/else pair says: “If this expression is true, run this indented code block; otherwise, run this code after the else statement.”

if 8 > 9:  print "I don't printed!"else:  print "I get printed!"

elif is short for “else if.” It means exactly what it sounds like: “otherwise, if the following expression is true, do this!”

if 8 > 9:  print "I don't get printed!"elif 8 < 9:  print "I get printed!"else:  print "I also don't get printed!"