和我一起学python,控制语句 (life is short ,we need python)

控制语句

if/elif/else 

  if语句和一般编程语言一样,条件为true 执行

  如: if true :

      print ‘true‘         <----if、else下对齐,要使用相同的空格或者tab

    else:

      print ‘false‘

    

     但是,python有自己的特点:

        1. if else 要求严格分层对齐 对于嵌套if、else语句都应当严格分层对齐。

        2.if else 关键字后边一定要加冒号 :

#!/usr/bin/python
‘‘‘
create By to be crazy
All rights Reserved

‘‘‘
score=int(raw_input("Enter your score please\n"))
if (score>0 and score<100 ):
        if(score>90):
          print "your score is A"
        elif(score>60):
          print "your score is B"
        else:
          print "your score is C"
else:
        print "your score is not correct"

可以看出,if嵌套如何匹配else的,第一层if使用一个tab对齐,第二层使用一个空格对齐,切记elif

循环结构 

 

while/for

 

for 适用于list和dictionary的遍历,也可以是字符串遍历

  

word = "Programming is fun!"

for letter in word:
    # Only print out the letter i
    if letter == "i":
        print letter

 

for item in [1, 3, 21]: 
    print item
webster = {
    "Aardvark" : "A star of a popular children‘s cartoon show.",
    "Baa" : "The sound a goat makes.",
    "Carpet": "Goes on the floor.",
    "Dab": "A small amount."
}

# Add your code below!
for key in webster:
    print webster[key]

 

需要注意:不要忘记for语句的冒号  

  

break/continue

try catch else finally

 

 

和我一起学python,控制语句 (life is short ,we need python),布布扣,bubuko.com

和我一起学python,控制语句 (life is short ,we need python)

上一篇:Java 中extends与implements使用方法 (转载)


下一篇:java泛型