python基础——控制语句

来源:互联网 发布:vimeo视频下载 mac 编辑:程序博客网 时间:2024/06/16 15:01

条件语句

num = input("Enter a number:")if num > 0:    print "The number is positive"elif num < 0:    print "The number is negative"else:    print "The number is zero"
需要注意:
1)冒号不能忘;

2)if语句中除了False/None/0/""/()/[]/{}表示假,其它都为真;

3)可以用于if语句中的比较运算符:

x == yx < yx > yx >= yx <= yx != yx is yx is not yx in yx not in y
尤其需要注意后面四个。

以上表达式还可以通过and/or/not连接起来。

while循环语句

count = 10while count:    print count    count -= 1  # python中没有count--这样的用法

for循环语句

aList = [1, 2, 3, 4]for num in aList:    print num

跳出循环

breakcontinue

循环语句中的else

aList = [1, 2, 3, 4]for num in aList:    if num > 10:        print num        breakelse:       # 如果循环中没有执行break语句,则到最后会运行else中的内容    print "No number bigger than 10"
结果是打印:

No number bigger than 10

pass语句

表示什么都不做:

num = 0if num > 0:    print "The number is positive"elif num == 0:    pass        # 表示不做什么处理else:    print "The number is negative"

0 0
原创粉丝点击