[ 今天来简单看看Python语句的控制结构:条件判断与循环,其实也就是If-Else与While和For的使用,基本的语法同C差不多,但是由于Python中的弱格式书写,从而没有了C中的
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 andthere 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)[我在学习协同过滤,遇到这样一段代码 {代码...} 比较困惑的是下面这段代码,为什么sum里面可以写for 循环呢,这个是什么意思,为什么我写了个类似的函数就会报错 {代码...
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:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
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[第五章 条件、循环和其他语句 注意:注意代码的缩进,否则会报错,因为是通过缩进来区分代码块的。用Tab或者两个空格或四个空格,但应保持一致,不要混用,决定用tab