《趣学Python编程》第一部分整理

来源:互联网 发布:英国男装品牌 知乎 编辑:程序博客网 时间:2024/05/16 15:31
1,Python的基本计算,变量,模块使用,if和else,循环; 

2,使用函数和模块重用你的代码 
>>>list(range(0,5)) 
[0,1,2,3,4] 
使用def(即define定义的缩写)来设计函数 
>>>def  testfunc(fname, lname) 
            print('hello  %s  %s'  %  (fname, lname)) 
>>>testfunc('Mary', 'Smith') 
hello  Mary  Smith 
另外,在定义函数的时候要了解到函数中各变量的作用域,即在函数中的变量只能在函数中使用,而在函数执行结束后便不能再用。 

3,使用模块 
>>>import  time 
>>>print(time.asctime()) 
即输入当前时间 
>>>import  sys 
>>>print(sys.stdin.readline()) 
即输入什么,输出就是什么。 
>>> 
>>>silly_age_joke() 
How  old  are  you? 
10 
What  is  13  +  49  +  84  +  155?  A  headache! 
>>>silly_age_joke() 
How  old  are  you? 
15 
Huh? 

4,海龟与高级海龟行走 
 import  turtle

5,Python的内建函数 
abs()返回绝对值 
bool()返回布尔值 
dir()可以返回关于任何值的信息,也基本可以用于任何东西,包括字符串,数字,函数,模块,对象,还有类。 
eval()把一个字符串作为参数并返回它作为一个Python表达式的结果。 
exec() 
float()把字符串或者数字转换为浮点数 
int()把字符串或者数字转换为整数 
len()返回一个对象的长度,如字符串的字符个数 
max()返回列表,元组或字符串中最大的元素 
min()返回列表,元组或字符串中最小的元素 
range()返回顺序数 
sum()返回和 
open()写入文件,打开文件

6,keyword关键字模板 
>>>import  keyword 
>>>print(keyword.iskeyword('if')) 
True 
>>>print(keyword.kwlist)可列出所有关键字 

7,random模块获取随机数 
>>>import  random 
>>>print(random.randint(1,100)) 
random.choice()随机选择列表中的一个元素 
random.shffle()给列表洗牌,打乱顺序 

8,sys模块控制shell程序,主要有exit,stdin,stdout和ersion变量
>>>import  sys 
>>>sys.exit() 
退出shell程序 
>>>import  sys 
>>>sys.stdin()
sys.stdin.write()和sys.stdin.readline()的不同在于readline可用一个参数指定读取多少个字符 
sys.stdout.write()输出 
sys.version即python的版本号 

9,time模块来得到时间 
time.time()表示当前距离1970年1月1日的秒数 
time.asctime()表示当前时间 
time.localtime()表示当前年月,时间 
time.sleep(1)程序延迟1s,即休眠1s

10,高级海龟制图 
>>>import  turtle 
>>>t=turtle.Pen() 
切记此处的P为大写 
>>> t=turtle.Pen() 
>>> t.forward(50) 
>>> t.left(90) 
>>> t.forward(50) 
>>> t.left(90) 
>>> t.forward(50) 
>>> t.left(90) 
>>> t.forward(50) 
>>> t.reset() 
绘制正方形 
也可以如下: 
>>> for x in range(1,5): 
    t.forward(50) 
    t.left(90)
另外,t.reset()表示重新设置; 
也可以进行填色, 
>>>t.begin_full() 
>>>t.circle(10) 
>>>t.end_full() 
绘制填色的圆 
其中填色函数有三个参数,红色,绿色和蓝色的混搭即为RGB,通过t.color(1,0,0)绘制出红色图样 
还有不同的红,例如t.color(0.5,0,0),t.color(0.9,0,0)等 
0 0
原创粉丝点击