编程环境:

win7旗舰版

Python 3.2.2(default, Sep  4 2011,09:51:08)

代码来源:(Python菜鸟)

代码内容:

Python基本的输出语句print("String");输入语句input("Please enter what you want to say:")if else语法、while语法、for语句等嵌套语法。

Python语言中函数定义的方法:def function(arg1,arg2):  return S;。

Python的.py文件的调用方法import Myself_OutFlie以及文件中的函数的调用方法。

python基本的文件操作open(test.txt,'r+',100)函数、close()文件流关闭函数、write(b"test.txt",)写操作函数、read("10")读操作函数。

Python的类操作,类的继承,类方法的重写。

Python正则表达式的基本操作和简单的文本处理。

Python和Mysql数据库连接的方法API和基本的操作

  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3. import sys;
  4. import math;
  5. import time;
  6. import string;
  7. print('Hello World!');#打印字符串
  8. #print('爱你!');
  9. print(4+5,4*5,4/5,pow(4,5));
  10. #注意python的语法对文本缩进的格式要求很高,一定要保证
  11. if True:
  12. print ("Answer");
  13. print ("True");
  14. else:
  15. print ("Answer");
  16. print ("False");
  17. #total = item_one + \#连接符
  18. item_two + \
  19. item_three;
  20. print('total');
  21. days = ['Monday','Thuesday','Wednesday','Thursday','Friday'];
  22. print(days[0],days[1],days[2],days[3],days[4]);
  23. x = 'runoob';
  24. sys.stdout.write(x + '\n')
  25. counter = 100;#整形变量
  26. miles = 101.1;#浮点型数据
  27. name = 'mamiao';#字符型变量
  28. print(name,counter,miles);
  29. a,b,c =1,2,"mamiao";#相当于多个变量同时赋值
  30. print(a,b,c);
  31. del a,b,c;#删除多个对象的引用
  32. real=3.001;
  33. image=4.002;
  34. Num_com=complex(real,image)
  35. Length=abs(Num_com);
  36. print("Complex Number is ",Num_com,".The Length is equal to",Length);
  37. str='I want to learn Python every well,but the time seem to be not enough!';
  38. print(str[1:10]);#截取字符串当中的一部分,小标的起始是从左到右,起始0-左
  39. print(str);#输出完整字符串
  40. print(str[0]);#输出字符串中的第一个字符
  41. print(str[2:5]);#输出字符串中第三个至第五个之间的字符串
  42. print(str[2:]);#输出从第三个字符开始的字符串
  43. print(str * 2);#输出字符串两次
  44. print(str + "TEST");#输出连接的字符串
  45. #加号(+)是列表连接运算符,星号(*)是重复操作
  46. tuple = ('GPIO','FLASH','MCPU');#元组,不允许更新
  47. list = ['A','B','C'];#列表,可以更新
  48. A,B=10,11;
  49. B+=1;
  50. if (A>B) and (A==B):
  51. print('A is the big one');
  52. else:
  53. print('B is the big one');
  54. print(A|B,A**B,A^B,~A,A<<2,A>>1);
  55. #Python成员运算符,in 运算符
  56. List = [1,2,3,4,5,10];
  57. if (A in List) and (B in List):
  58. print('Oh,yeal!');#一定要注意啊,目前加入不了utf8的库,所以感叹号一定是英文的感叹号
  59. elif (A not in List) and (B not in List):
  60. print('Ok,There is no one of the Number!');
  61. else:
  62. print('Some number of them is in the List!');
  63. #Python语言中没有 do while语句
  64. M=input("Enter your input:");
  65. print(M+'');
  66. #数据类型转换string--convert--int,eg:int('12')
  67. #数据类型转换int--convert--string,eg:str('12')
  68. count=int(M);
  69. while (count < 10):
  70. print('The count number is equal to:',count);#注意缩进,缩进表示的是当前执行的代码
  71. count+=1;
  72. print('Good bye!');
  73. i = 1
  74. while i < 10:
  75. i += 1
  76. if i%2 > 0: # 非双数时跳过输出
  77. continue
  78. print(i) # 输出双数2、4、6、8、10
  79.  
  80. i = 1
  81. while 1: # 循环条件为1必定成立
  82. print(i) # 输出1~10
  83. i += 1
  84. if i > 10: # 当i大于10时跳出循环
  85. break
  86. #Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串
  87. for letter in 'Python':
  88. print('The letter is: ',letter);
  89. for day in days:
  90. print('Today is:',day);
  91. #通过序列索引迭代来完成对列表等字符串遍历
  92. for index in range(len(days)):
  93. print(days[index]);
  94. #循环嵌套
  95. i = 2
  96. while(i < 100):
  97. j = 2
  98. while(j <= (i/j)):
  99. pass
  100. #Python pass是空语句,是为了保持程序结构的完整性。
  101. #pass 不做任何事情,一般用做占位语句
  102. if not(i%j): break
  103. j = j + 1
  104. if (j > i/j) : print(i," prime num")
  105. i = i + 1
  106. print("Good bye!")
  107. ticks = time.time()#获取当前时间戳
  108. print("The current time is:", ticks)
  109. localtime = time.localtime(time.time())
  110. print('The locate time is:',localtime)
  111. localtime = time.asctime( time.localtime(time.time()))
  112. print('The locate time is:',localtime)
  113.  
  114. #python函数定义
  115. def printme( str1,str2 ):#"打印传入的字符串到标准显示设备上"
  116. print(str1+str2);
  117. return;
  118. printme('Hello world!','I Love Python!')
  119. #两种求和函数:
  120. def sum1( arg1, arg2 ):
  121. # 返回2个参数的和."
  122. total = arg1 + arg2
  123. print("kernel of function : ", total)
  124. return total;
  125. sum2 = lambda arg1,arg2:arg1+arg2;
  126. print('The total is:',sum1(10,20));
  127. print('The total is:',sum2(10,20));
  128. content = dir(math)
  129. print(content);
  130. #调用自己编写的外部库函数,类似于C语言的.c文件source文件,注意调用的方式
  131. import support;
  132. support.print_func("Zara");
  133. #from support import fibonacci#单独引用support.py文件里面的fibonacci函数,其余函数都不调用
  134. #from support import *#调用所有support文件里面的函数模块model
  135.  
  136. a,b=0,10;
  137. for a in range(b):
  138. print(a);
  139. a+=1;
  140.  
  141. #import Python_Library;
  142. #import fibonacci;
  143. #fibonacci_func(10);#retry the function to run
  144.  
  145. #file object = open("file_name","access","Buffer"]);
  146. #filename是文件的名称,access是object操作文件的权限,Buffer是文件是否以寄存器操作来运行
  147.  
  148. #Buffer=1代表使用Buffer,当Buffer是大于1时,限制了Buffer的大小,Buffer=0表示不使用Buffer
  149. #file对象的属性
  150. #file.closed 返回true如果文件已被关闭,否则返回false。
  151. #file.mode 返回被打开文件的访问模式。
  152. #file.name 返回文件的名称。
  153. #file.softspace 如果用print输出后,必须跟一个空格符,则返回false。否则返回true。
  154. fo=open("test.txt","wb",1000);
  155. print("The filename is :",fo.name);
  156. print("The states of files :",fo.closed);
  157. print("The Rquest_Model of files :",fo.mode);
  158. print("Now time I will write something into the files named test.txt!");
  159. fo.write(b'www.runoob.com!\nVery good site!\n');#传递测参数就是要写入fo文件的内容,必须要#使
  160.  
  161. b参数来限定写入的数据类型是byte类型
  162. fo.close();
  163. fo=open("test.txt","rb",1);
  164. #file.read(count)函数传递的参数count是要从已打开文件中读取的字节计数。该方法从文件的开头
  165. #开始读入,如果没有传入count,它会尝试尽可能多地读取更多的内容,很可能是直到文件的末尾。
  166. print("Now time I will read some information from the files named test.txt!");
  167. Str1=fo.read();
  168. print(Str1);
  169. fo.close();
  170. #tell()方法告诉你文件内的当前位置;换句话说,下一次的读写会发生在文件开头这么多字节之后
  171. #seek(offset ,[from])方法改变当前文件的位置。Offset变量表示要移动的字节数。From变量指定#
  172.  
  173. 开始移动字节的参考位置,如果from被设为0,这意味着将文件的开头作为移动字节的参考位置。如果#设
  174.  
  175. 1,则使用当前的位置作为参考位置。如果它被设为2,那么该文件的末尾将作为参考位置
  176. fo=open("test.txt","r+",1);
  177. str=fo.read(10);
  178. print(str);
  179. position=fo.tell();
  180. print("The position of file nowtime is equal to :",position);
  181. position=fo.seek(0,0)
  182. str=fo.read(10);
  183. print(str);
  184. fo.close();
  185.  
  186. import os;
  187. Path=os.getcwd()#获得当前的路径
  188. print(Path)
  189. os.mkdir("Subdirector");#当文件夹已经存在的时候不能再次创建它
  190. os.rmdir("Subdirector");#删除当前目录下的文件夹
  191.  
  192. class Employee:
  193. 'Hello,This the first class named Employee!'
  194. empCount=0;
  195. def __init__(self,name,salary):
  196. self.name = name;
  197. self.salary = salary;
  198. Employee.empCount += 1;
  199. def displayCount(self):
  200. print("Total Employee %d"%Employee.empCount);#看这里的语法,如何输出变量
  201. def displayEmployee(self):
  202. print("Name:",self.name,",Salary:",self.salary);
  203. emp1 = Employee("mamiao",20000);
  204. emp2 = Employee("zhangle",30000);
  205. emp3 = Employee("jujiabao",40000);
  206. emp1.displayCount();
  207. emp1.displayEmployee();
  208. emp2.displayCount();
  209. emp2.displayEmployee();
  210. emp3.displayCount();
  211. emp3.displayEmployee();
  212. print("Total Employee %d"%Employee.empCount);#class申明的成员变量是共用的,public
  213. emp1.age = 7;#添加emp1的变量属性age
  214. emp1.sex = 1;
  215. emp1.age = 8;#修改emp1age变量值
  216. print(emp1.age);
  217. del emp1.age;#删除emp1的变量属性age
  218.  
  219. #getattr(obj,'name',[default])#访问对象的属性。
  220. #hasattr(obj,'name')#检查是否存在一个属性。
  221. #setattr(obj,'name',value)#设置一个属性。如果属性不存在,会创建一个新属性。
  222. #delattr(obj,'name')#删除属性。
  223. #getattr(emp1,'sex');
  224. if hasattr(emp1,'sex'):
  225. print("There is a member of emp1 named age!");
  226. setattr(emp1,'Weight',60);
  227. if hasattr(emp1,'Weight'):
  228. print("There is a member of emp1 named Weight!");
  229. delattr(emp1,'Weight');
  230. if hasattr(emp1,'Weight'):
  231. print("There is a member of emp1 named Weight!");
  232. else:
  233. print("The member has already been delete by User miaoma!");
  234. print("Employee.__doc__:", Employee.__doc__)
  235. print("Employee.__name__:", Employee.__name__)
  236. print("Employee.__module__:", Employee.__module__)
  237. print("Employee.__bases__:", Employee.__bases__)
  238. print("Employee.__dict__:", Employee.__dict__)
  239.  
  240. class Parent:#定义父类
  241. parentAttr = 100
  242. def __init__(self):
  243. print("Callback the Structure-function of parent!");
  244.  
  245. def parentMethod(self):
  246. print('Callback the normal parent mothed!');
  247.  
  248. def setAttr(self, attr):#成员变量更新方法setAttr
  249. Parent.parentAttr = attr;
  250.  
  251. def getAttr(self):
  252. print("Characte-Value of Parent:", Parent.parentAttr);
  253.  
  254. def Function_Overwrite(self):
  255. print("This is Parent's Function!");
  256.  
  257. class Child(Parent): # 定义子类,子类的内部调用了参数Parent,该参数表明Child类继承了Parent类
  258.  
  259. 的基本方法
  260. def __init__(self):
  261. print("Callback Structure-function of Child!");
  262.  
  263. def childMethod(self):
  264. print('Callback child method');
  265.  
  266. def Function_Overwrite(self):
  267. print("This is Child's Function!");
  268.  
  269. c = Child() # 实例化子类
  270. c.childMethod() # 调用子类的方法
  271. c.parentMethod() # 调用父类方法
  272. c.setAttr(200) # 再次调用父类的方法
  273. c.getAttr() # 再次调用父类的方法
  274. c.Function_Overwrite() #方法重写
  275.  
  276. #__private_attrs:两个下划线开头,声明该属性为私有,不能在类地外部被使用或直接访问。在类内
  277.  
  278. 部的方法中使用时 self.__private_attrs
  279. class JustCounter:
  280. __secretCount = 0 # 私有变量
  281. publicCount = 0 # 公开变量
  282.  
  283. def count(self):
  284. self.__secretCount += 1
  285. self.publicCount += 1
  286. print(self.__secretCount)
  287.  
  288. counter = JustCounter()
  289. counter.count()
  290. counter.count()
  291. print(counter.publicCount)
  292. #print(counter.__secretCount)#报错,实例不能访问私有变量
  293.  
  294. #Python正则表达式(提前学习正则表达式),需要引入头文件:import re
  295. #re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回
  296.  
  297. none
  298. #函数语法:re.match(pattern, string, flags=0)
  299. #pattern 匹配的正则表达式
  300. #string 要匹配的字符串
  301. #flags 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等
  302. import re
  303. print(re.match('www','www.runoob.com').span()) # 在起始位置匹配
  304. print(re.match('com','www.runoob.com')) # 不在起始位置匹配
  305.  
  306. line = "Cats are smarter than dogs"
  307. matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
  308. if matchObj:
  309. print("matchObj.group() : ", matchObj.group())
  310. print("matchObj.group(1) : ", matchObj.group(1))
  311. print("matchObj.group(2) : ", matchObj.group(2))
  312. else:
  313. print("No match!!")
  314. #re.search 扫描整个字符串并返回第一个成功的匹配
  315. #re.search(pattern, string, flags=0)
  316. #pattern 匹配的正则表达式
  317. #string 要匹配的字符串。
  318. #flags 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等
  319. #匹配成功re.search方法返回一个匹配的对象,否则返回None
  320. print(re.search('www', 'www.runoob.com').span()) # 在起始位置匹配
  321. print(re.search('com', 'www.runoob.com').span()) # 不在起始位置匹配
  322.  
  323. searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)
  324. if searchObj:
  325. print("searchObj.group() : ", searchObj.group())
  326. print("searchObj.group(1) : ", searchObj.group(1))
  327. print("searchObj.group(2) : ", searchObj.group(2))
  328. else:
  329. print("Nothing found!!")
  330.  
  331. #比较match函数和search函数的区别,re.match只匹配字符串的开始,如果字符串开始不符合正则表达
  332.  
  333. 式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配
  334. matchObj = re.match( r'dogs', line, re.M|re.I)
  335. if matchObj:
  336. print("match --> matchObj.group() : ", matchObj.group())
  337. else:
  338. print("No match!!")
  339.  
  340. matchObj = re.search( r'dogs', line, re.M|re.I)
  341. if matchObj:
  342. print("search --> matchObj.group() : ", matchObj.group())
  343. else:
  344. print("No match!!")
  345.  
  346. #Python 的re模块提供了re.sub用于替换字符串中的匹配项:re.sub(pattern, repl, string, max=0)
  347. #返回的字符串是在字符串中用 RE 最左边不重复的匹配来替换。如果模式没有发现,字符将被没有改变
  348.  
  349. 地返回。可选参数 count 是模式匹配后替换的最大次数;count 必须是非负整数。缺省值是 0 表示替
  350.  
  351. 换所有的匹配
  352. phone = "2004-959-559 # This is Phone Number"
  353.  
  354. # Delete Python-style comments
  355. num = re.sub(r'#.*$', "", phone)
  356. print("Phone Num : ", num)
  357.  
  358. # Remove anything other than digits
  359. num = re.sub(r'\D', "", phone)#\D匹配一个非数字字符,等价于等价于[^0-9]
  360. print("Phone Num : ", num)
  361.  
  362. #Python连接到数据库必须学习,方便进行大数据的数据库处理
  363.  
  364. #Python2.6和Python3.0的版本的改变:
  365. b = b'china';
  366. print("b is :",b);
  367. print("The type of b is:",type(b))
  368. s = b.decode()
  369. print(s)
  370. b1 = s.encode();
  371. print("The type of b1 is:",type(b1))
  372. print(b1)

Python基本语法初试的更多相关文章

  1. python之最强王者(2)——python基础语法

    背景介绍:由于本人一直做java开发,也是从txt开始写hello,world,使用javac命令编译,一直到使用myeclipse,其中的道理和辛酸都懂(请容许我擦干眼角的泪水),所以对于pytho ...

  2. Python基本语法[二],python入门到精通[四]

    在上一篇博客Python基本语法,python入门到精通[二]已经为大家简单介绍了一下python的基本语法,上一篇博客的基本语法只是一个预览版的,目的是让大家对python的基本语法有个大概的了解. ...

  3. Python基本语法,python入门到精通[二]

    在上一篇博客Windows搭建python开发环境,python入门到精通[一]我们已经在自己的windows电脑上搭建好了python的开发环境,这篇博客呢我就开始学习一下Python的基本语法.现 ...

  4. python 缩进语法,优缺点

    Python的语法比较简单——采用缩进方式 缩进有利有弊: 好处之一是强迫你写出格式化的代码,但没有规定缩进是几个空格还是Tab.按照约定俗成的管理,应该始终坚持使用4个空格的缩进. 其二是强迫你写出 ...

  5. Python特殊语法:filter、map、reduce、lambda [转]

    Python特殊语法:filter.map.reduce.lambda [转] python内置了一些非常有趣但非常有用的函数,充分体现了Python的语言魅力! filter(function, s ...

  6. Python 基础语法(三)

    Python 基础语法(三) --------------------------------------------接 Python 基础语法(二)------------------------- ...

  7. Python 基础语法(四)

    Python 基础语法(四) --------------------------------------------接 Python 基础语法(三)------------------------- ...

  8. Python 基础语法(二)

    Python 基础语法(二) --------------------------------------------接 Python 基础语法(一) ------------------------ ...

  9. Python 基本语法1

    Python 基础语法(一) Python的特点 1. 简单 Python是一种代表简单思想的语言. 2. 易学 Python有极其简单的语法. 3. 免费.开源 Python是FLOSS(自由/开放 ...

随机推荐

  1. 【原创】有关Silverlight控件DataGrid的绑定数据后单元格单独复制的功能实现分析

    前些日子,公司新需求需要对silverlight的datagrid进行局部任意单元格数据可复制,查阅了半天网络资料愣是没找到相关资料,开始还以为是silverlight的bug根部无法实现, 最后还是 ...

  2. 新的Visual C++代码优化器

    微软在 5 月 4 日发布了新的高级代码优化器,服务于 Visual C++ 的后端编译器.提高了代码性能,可以压缩代码体积,将编译器带入了一个新的境界. Visual C++ 的团队在博客上称,这将 ...

  3. SqlServer 2008 R2定时备份数据库,并且发送邮件通知

    先配置数据库的邮件设置,这样才可以发送邮件. 2. 3. 4. 5. 6. 7. 8. 9. 10. 总的预览图,如图 执行这一段(先发送备份邮件,然后进行数据备份,将昨天的发送数据插入到另一张表中, ...

  4. 泛函编程(14)-try to map them all

    虽然明白泛函编程风格中最重要的就是对一个管子里的元素进行操作.这个管子就是这么一个东西:F[A],我们说F是一个针对元素A的高阶类型,其实F就是一个装载A类型元素的管子,A类型是相对低阶,或者说是基础 ...

  5. jquery checkbox checked

    1.question: when first operate the checkbox with sentence like : $("input[type=checkbox]") ...

  6. python peewee.ImproperlyConfigured: MySQLdb or PyMySQL must be installed.

    最近在学习Python,打算先看两个在线教程,再在github上找几个开源的项目练习一下,在学到“被解放的姜戈”时遇到django同步数据库时无法执行的错误,记录一下. 错误现象: 执行python ...

  7. 六个创建模式之简单工厂模式(Simple Factory Pattern)

    定义: 定义一个工厂类,它可以根据参数的不同生成对应的类的实例:被创建的类的实例通常有相同的父类.因为该工厂方法尝尝是静态的,所以又被称为静态工厂方法(Static Factory Method) 结 ...

  8. 怎么通过activity里面的一个按钮跳转到另一个fragment(android FragmentTransaction.replace的用法介绍)

    即:android FragmentTransaction.replace的用法介绍 Fragment的生命周期和它的宿主Activity密切相关,几乎和宿主Activity的生命周期一致,他们之间最 ...

  9. linux 查看占用内存/CPU最多的进程

    可以使用一下命令查使用内存最多的5个进程 ps -aux | sort -k4nr | head -n 5 或者 top (然后按下M,注意大写) 可以使用一下命令查使用CPU最多的5个进程 ps - ...

  10. 从网络中获取图片显示到Image控件并保存到磁盘

    一.从网络中获取图片信息: /// <summary> /// 获取图片 /// </summary> /// <param name="url"&g ...