MENU

Python学习笔记(四)

2017 年 12 月 24 日 • Python学习笔记

python的控制流:条件与循环

需要注意的是在python中没有switch选择语句,但是可以使用条件语句来代替,或者使用字典也是个不错的选择:-)

条件语句

条件语句与其它语言保持一致,判断条件不需要加括号,但是需要注意的是条件判断后需要加":"。

说到条件语句就需要谈一下一些条件运算符和逻辑运算符。条件运算符即> < >= <= != ==,逻辑运算符为与或非and or not

money = 100

if money > 50 :
    print 'I am rich'
else:
    print 'I am poor'

不出意外地,当然也存在多重条件语句。

grade = 85

if grade < 60 :
    print '不及格'
elif grade >= 60 and grade < 80 :
    print '及格'
elif grade >= 80 and grade < 90 : 
    print '良好' 
else :
    print '优秀'

循环语句

循环语句分为while循环和for循环,for循环我一般用来作遍历使用,其他场合使用while循环。

count = 5

while count < 5 :
    print count
    
    #python中没有i++这种语句
    count = count + 1

#python中的while语句后可加else语句
else:
    print 'over'

for循环一般用于遍历的场合,比如遍历一个列表。

names = ['Kangkang', 'Mike', 'Maria']

#range大法好,在for循环经常使用
for i in range(0, len(names)) :
    print names[i]