[置顶]Python基本语法初试

来源:互联网 发布:数位板绘画软件 编辑:程序博客网 时间:2024/04/30 17:45
编程环境:

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+'2'); 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       pass100       #Python pass是空语句,是为了保持程序结构的完整性。101       #pass 不做任何事情,一般用做占位语句102       if not(i%j): break103       j = j + 1104    if (j > i/j) : print(i," prime num")105    i = i + 1106 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 + arg2123    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文件里面的函数模块model135 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 run144 145 #file object = open("file_name","access","Buffer"]);146 #filename是文件的名称,access是object操作文件的权限,Buffer是文件是否以寄存器操作来运行147 148 #Buffer=1代表使用Buffer,当Buffer是大于1时,限制了Buffer的大小,Buffer=0表示不使用Buffer149 #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的变量属性age214 emp1.sex = 1;215 emp1.age = 8;#修改emp1的age变量值216 print(emp1.age);217 del emp1.age;#删除emp1的变量属性age218 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 = 100242    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):#成员变量更新方法setAttr249       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_attrs279 class JustCounter:280     __secretCount = 0  # 私有变量281     publicCount = 0    # 公开变量282 283     def count(self):284         self.__secretCount += 1285         self.publicCount += 1286         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 re295 #re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回296 297 none298 #函数语法:re.match(pattern, string, flags=0)299 #pattern  匹配的正则表达式300 #string     要匹配的字符串301 #flags    标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等302 import re303 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方法返回一个匹配的对象,否则返回None320 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 comments355 num = re.sub(r'#.*$', "", phone)356 print("Phone Num : ", num)357 358 # Remove anything other than digits359 num = re.sub(r'\D', "", phone)#\D匹配一个非数字字符,等价于等价于[^0-9]    360 print("Phone Num : ", num)361 362 363 #Python连接到数据库必须学习,方便进行大数据的数据库处理364 365 #Python2.6和Python3.0的版本的改变:366 b = b'china';367 print("b is :",b);368 print("The type of b is:",type(b))369 s = b.decode() 370 print(s)371 b1 = s.encode();372 print("The type of b1 is:",type(b1))373 print(b1)