Python学习笔记一
前言:Python系列学习笔记参考的是简明 Python 教程(Swaroop, C. H. 著,沈洁元 译),谢谢^_^
一、缩进
这意味着同一层次的语句必须有相同的缩进。每一组这样的语句称为一个块。
如何缩进
不要混合使用制表符和空格来缩进,因为这在跨越不同的平台的时候,无法正常工作。我 强烈建议 你在每个缩进层次使用 单个制表符 或 两个或四个空格 。
选择这三种缩进风格之一。更加重要的是,选择一种风格,然后一贯地使用它,即 只 使用这一种风格。
二、变量
变量不需申明类型,即可使用,所有变量的作用域是它们被定义的块,从它们的名称被定义的那点开始。
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)
type()可以获取变量类型。float()、int()、string() 可以实现变量类型的转换
type()的应用举例 >>> type(eee)
<type 'str'>
raw_input()可实现用户输入,获取数字串。例子:
inp = raw_input(‘Europe floor?’)
usf = int(inp) + 1
print 'US floor', usf
输出为:
Europe floor? 0
US floor 1
三、控制流
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