Python入门
学习语言三原则:
- 实践是提高编程能力和问题解决能力最好办法。
- 程序应该是具有可读性的短文。
- 编写程序前请深思熟虑。
运行Python的平台是Ubuntu 14.04 LTS.
1 第一个Python程序
#calculate the area and circumference of a circle from its radius.
#Step1: prompt for a radius
#Step2: apply the area formula
#Step3: Print out the results
import math
radiusString = raw_input("Enter the radius of your circle: ")
radiusInteger = int(radiusString)
circumference = 2 * math.pi * radiusInteger
area = math.pi *(radiusInteger **2)
print "The circumference is:",circumference,\
", and the area is: ",area
你将得到如下的输出:
2 Python的命令行
我们可以建立.py脚本创建Python程序, 同时我们也可以直接在Python的命令行输入代码, 这样做的好处是, 我们能看到Python每一步执行过程, 有助于程序理解,
>>> import math
>>> radiusString = raw_input("Enter the radius of your circle: ")
Enter the radius of your circle: 20
>>> radiusString
'20'
>>> radiusInteger = int(radiusString)
>>> radiusInteger
20
>>> radiusString
'20'
>>> math.pi
3.1415926535897931
>>> circemference = 2* math.pi * radiusInteger
>>> circemference
125.66370614359172
>>> area = math.pi * radiusInteger ** 2
>>> area
1256.6370614359173
>>> math.pi * radiusInteger ** 2
1256.6370614359173
>>> print"Circumference: ", circumference, ", area: ", area
>Circumference: 125.663706144 , area: 1256.63706144
>>>
3 Python的基础
3.1 模块
#import module # load the module
import math
3.2 缩进与空白
缩进是Python非常重要的概念, Python没有{ }
分割语句, 采用缩进分割语句, 同一个缩进表示属于同一个语句块.
point = 10
seconds = 20
if points > seconds:
print "True!"
print "it's True?"
#这条语句与下面这条语句不一样
if points > seconds:
print "True!"
print "it's True?"
- 有缩进的语句表示同属于一个语句块.
3.3 Python关键字
Python关键字 | ||||
---|---|---|---|---|
and | del | from | not | while |
as | elif | global | or | with |
assert | else | if | pass | yield |
break | except | import | class | |
is | return | def | for | lambda |
try |
3.4 Python运算符
用于数学运算.
Python运算符 | ||||||
---|---|---|---|---|---|---|
+ | - | * | ** | / | // | % |
<< | >> | & | | | ^ | ~ | |
< | > | <= | >= | == | != | <> |
+= | -= | *= | /= | //= | %= | |
&= | |= | ^= | >>= | <<= | **= |
3.5 Python标点符号
用于分隔不同的元素.
Python标点符号 | |||||
---|---|---|---|---|---|
( | ) | [ | ] | { | } |
, | : | . | ` | = | ; |
‘ | “ | # | \ | @ |
3.6 数字
- 整数
Python中的整型为int
.123
,1000000000000L
- 浮点数
Python中的浮点数为float
.25.567
,2.99e8
- 复数
Python支持复杂的复数类型.2 + 3j
.
3.7 其他类型
布尔类型
Python中的布尔类型为True
,False
.[注意] 对大小写敏感.
字符串
Python中字符串类型为str
, 单引号''
和双引号" "
没差别.- 列表
列表类型为list
:[3, 3.56, 'abc'].
- 字典
字典的类型为dict
:{"Jones":3471124, "Larson": 3472289, "Smith": 3471288}
4 一个好玩的海龟绘图
Python2.6引入了一个简单的绘图工具Turtle Graphics
.
#Draw a 5-pointed star
import turtle
turtle.forward(100)
turtle.right(144)
turtle.forward(100)
turtle.right(144)
turtle.forward(100)
turtle.right(144)
turtle.forward(100)
turtle.right(144)
turtle.forward(100)