Python入门

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

你将得到如下的输出:
Ee01

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
  • Python有非常非常多的模块,获取模块与了解模块功能最好的方法是,参考Python官方文档: Python标准库
  • Python开源社区,免费提供了6500多个Python模块: Python索引包

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关键字
anddelfromnotwhile
aselifglobalorwith
assertelseifpassyield
breakexceptimportprintclass
isreturndefforlambda
try

3.4 Python运算符

用于数学运算.

Python运算符
+-***///%
<<>>&|^~
<><=>===!=<>
+=-=*=/=//=%=
&=|=^=>>=<<=**=

3.5 Python标点符号

用于分隔不同的元素.

Python标点符号
()[]{}
,:.`=;
#\@

3.6 数字

  1. 整数
    Python中的整型为int. 123 , 1000000000000L
  2. 浮点数
    Python中的浮点数为float. 25.567 , 2.99e8
  3. 复数
    Python支持复杂的复数类型. 2 + 3j .

3.7 其他类型

  1. 布尔类型
    Python中的布尔类型为True,False.

    [注意] 对大小写敏感.

  2. 字符串
    Python中字符串类型为str, 单引号''和双引号" "没差别.

  3. 列表
    列表类型为list: [3, 3.56, 'abc'].
  4. 字典
    字典的类型为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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值