一、缩进
这意味着同一层次的语句必须有相同的缩进。每一组这样的语句称为一个块。
如何缩进
不要混合使用制表符和空格来缩进,因为这在跨越不同的平台的时候,无法正常工作。我 强烈建议 你在每个缩进层次使用 单个制表符 或 两个或四个空格 。
选择这三种缩进风格之一。更加重要的是,选择一种风格,然后一贯地使用它,即 只 使用这一种风格。
二、变量
变量不需申明类型,即可使用
1 #!/usr/bin/python 2 # Filename: expression.py 3 4 length = 5 5 breadth = 2 6 area = length * breadth 7 print ‘Area is‘, area 8 print ‘Perimeter is‘, 2 * (length + breadth)
三、控制流
1、if..elif..else
1 #!/usr/bin/python 2 # Filename: if.py 3 4 number = 23 5 guess = int(raw_input(‘Enter an integer : ‘)) 6 7 if guess == number: 8 print ‘Congratulations, you guessed it.‘ # New block starts here 9 print "(but you do not win any prizes!)" # New block ends here 10 elif guess < number: 11 print ‘No, it is a little higher than that‘ # Another block 12 # You can do whatever you want in a block ... 13 else: 14 print ‘No, it is a little lower than that‘ 15 # you must have guess > number to reach here 16 17 print ‘Done‘ 18 # This last statement is always executed, after the if statement is executed
2、while...else 当while
循环条件变为False
的时候,else
块才被执行。else块事实上是多余的,因为你可以把其中的语句放在同一块(与while
相同)中,跟在while
语句之后,这样可以取得相同的效果。
1 #!/usr/bin/python 2 # Filename: while.py 3 4 number = 23 5 running = True 6 7 while running: 8 guess = int(raw_input(‘Enter an integer : ‘)) 9 10 if guess == number: 11 print ‘Congratulations, you guessed it.‘ 12 running = False # this causes the while loop to stop 13 elif guess < number: 14 print ‘No, it is a little higher than that‘ 15 else: 16 print ‘No, it is a little lower than that‘ 17 else: 18 print ‘The while loop is over.‘ 19 # Do anything else you want to do here 20 21 print ‘Done‘