1 The if statement:
The syntax of the if statement is:
if
expression:
statement(s)
Note:
In Python, all the statements indented by the same number
of character spaces after a programming construct are considered to be
part of a single block of code. Python uses indentation as its method of
grouping statements.
相同的缩进组成一个block块。
关于if条件语句,有几个重要的点:
1 if 后面加表达式后一定要有冒号:。否则语法通不过;
2 如果是同一个block里面的语句,缩进一定要相同;
单条件语句:
if ( expression == 1 ) : print "Value of expression is 1"
和if条件语法基本类似。可以写成单行。
2 else语句:
The else statement is an optional statement and there could be at most only one else statement following if .
The syntax of the if...else statement is:
if expression:
statement(s)
else:
statement(s)
3 elif 语句
The elif statement allows you to check multiple expressions for truth value and execute a block of code as soon as one of the conditions evaluates to true.
Like the else , the elif statement is optional. However, unlike else, for which there can be at most one statement, there can be an arbitrary number of elif statements following an if.
The syntax of the if...elif statement is:
if expression1: |
Note: Python does not currently support switch or case statements as in other languages.
Python目前不支持case 和switch语句。
注意:Python不支持在条件中用=赋值,而在C/C++中这种做法是允许的。
python中对表达式的计算的基本原则是:
所有f非0的值都被认为true,而所有为0的值为false
python中and or 和not比较特殊的地方,这些值并不只返回1 0,比如对于a and b 如果a为true 则整个表达式的值为b
对于a or b 如果a的值为false,则整个表达式的值为b