和我一起学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 可以配合range()使用

for i in range(10):
    print i

print 0~9

for loop 遍历dictionary

d = {'x': 9, 'y': 10, 'z': 20}
for key in d:
    if d[key] == 10
        print "This dictionary has the value 10!"

 

 

while 循环

先检查condition是否为true,为ture就继续循环

loop_condition = True

while loop_condition:
    print "I am a loop"
    loop_condition = False

while/else 

 while/else 不同于if/else 当循环的条件为False,else语句块会被执行也就是循环从未被执行或在循环正常结束时,都会执行else,如果循环被中断,return、break了,则不执行else。

 

import random

print "Lucky Numbers! 3 numbers will be generated."
print "If one of them is a '5', you lose!"

count = 0
while count < 3:
    num = random.randint(1, 6)
    print num
    if num == 5:
        print "Sorry, you lose!"
        break
    count += 1
else:
    print "You win!"

 

当执行到break,就不执行else 

若循环正常结束,执行else

 

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

  

break/continue

break 跳出循环

count = 0

while True:
    print count
    count += 1
    if count >= 10:
        break #exit the current loop.

 

 

 

 

posted @ 2014-07-11 15:46  to be crazy  阅读(1160)  评论(0编辑  收藏  举报