Python笔记之入门(基础篇)

来源:互联网 发布:我知这世界 编辑:程序博客网 时间:2024/05/20 01:37

Python 3笔记之入门

Python简单介绍

  Python 是一个高层次的结合了解释性、编译性、互动性和面向对象的脚本语言。Python 的设计具有很强的可读性,相比其他语言经常使用英文关键字,其他语言的一些标点符号,它具有比其他语言更有特色语法结构。
  

  • Python 是一种解释型语言: 这意味着开发过程中没有了编译这个环节。类似于PHP和Perl语言。
  • Python 是交互式语言: 这意味着,您可以在一个Python提示符,直接互动执行写你的程序。
  • Python 是面向对象语言: 这意味着Python支持面向对象的风格或代码封装在对象的编程技术。
  • Python 是初学者的语言:Python 对初级程序员而言,是一种伟大的语言,它支持广泛的应用程序开发,从简单的文字处理到 WWW 浏览器再到游戏。

Python 环境搭建

  1. 操作系统: win8 64bit
  2. 下载响应的win平台的Python安装包 下载链接,将下载的安装包按照提示安装。
  3. 环境变量配置
    程序和可执行文件可以在许多目录,而这些路径很可能不在操作系统提供可执行文件的搜索路径中。

Python 中文编码

关于在sublime text中中文编码的支持的问题
使用Sublime在build python程序时,有时候会遇到Decode error -output not utf-8或者是cp936。
原因是python编译运行后的流的编码方式和Sublime的解码方式不同,Sublime Ctrl+B build一个python程序时,
输出output not cp936,说明Sublime中的Python build默认接收的编码是cp936,
如果你的python 程序是utf-8编码,有汉字输出时,Sublime就会报not cp936的错误。
如果报的是output not utf-8,说明python在编译运行源码后默认将输出结果以cp936编码发送给Sublime。
而Sublime中的默认接收编码是utf-8。Sublime Text在接收到python输出后,试图以utf-8编码cp936编码的流。
当cp936编码的流中没有中文字符时,用utf-8解码不会出错,当cp936编码的流中有中文字符时,因为汉子集在cp936与utf-8的编码不兼容,所以用utf-8解码就会报错。
解决问题的关键就是弄明白你的python程序的编码和Sublime的python build中指定的编码。
python sublime decode errorcp936 utf-8 output not utf-8utf-8 cp936 output not cp936比如,你的python代码中制定了编码格式是utf-8,现在sublime报错了output not cp936的错误,则设置Sublime中python build编码格式为utf-8,反之亦然。Python.sublime-build
位置:
Sublime Text 2 : SublimeText2/Data/Packages/Python/ Python.sublime-build
Sublime Text 3 :SublimeText3/Packages/Python.sublime-package
Python.sublime-build文件:

{"cmd": ["python", "-u", "$file"],"file_regex": "^[ ]*File /"(...*?)/", line ([0-9]*)","selector": "source.python","encoding":"utf-8"}

input函数问题解决

关于用户输入的交互问题在sublime text中解决。
Sublime3编译Python程序EOFError:EOF when reading a line。
具体的解决办法已经在网上找到,链接在这里,希望对你能够有帮助。总的来讲就是:

  1. 下载一个SublimeRepl插件;
  2. 将插件放在如下图所示的位置location
  3. 运行的时候按照下图选择:
    这里写图片描述
    解决方案
#!/usr/bin/pythonprint ("dddd中国")if True:    print ("true");    print ('true你好')else:    print ("false");    print ("dddd中国")word = 'word'sentence = "这是一个句子。"paragraph = """这是一个段落。包含了多个语句"""print (paragraph)'''注释多行注释'''item_one=1;item_two=2;item_three=4total = item_one + \        item_two + \        item_three;print (total);import sys; x = 'runoob'; sys.stdout.write(x + '\n')import sysprint (sys.stdin.encoding);print (sys.stdout.encoding);x = 'runoob'; sys.stdout.write(x + '\n')#input("\n\nPress the enter key to exit.")#测试输入效果xx=input("\n\nPress the enter key to exit:");print (“当前的字符”+xx);

基础语法的参考教程

这里写链接内容
其中这个教程主要是面向python2的,因此一些python3中有区别的地方,我在下面给出一下代码案例:

数据类型

import sysprint (sys.stdin.encoding);print (sys.stdout.encoding);#自动类型包装counter = 100 # 赋值整型变量miles = 1000.0 # 浮点型name = "John" # 字符串print (counter)print (miles)print (name)a, b, c = 1, 2, "john"print (a)print (b)print (c)##Number  数字数据类型用于存储数值。var1 = 1print (var1)var2 = 10##String 字符串或串(String)是由数字、字母、下划线组成的一串字符。str = 'Hello World!'print (str) # 输出完整字符串print (str[0]) # 输出字符串中的第一个字符print (str[2:5]) # 输出字符串中第三个至第五个之间的字符串print (str[2:]) # 输出从第三个字符开始的字符串print (str * 2) # 输出字符串两次print (str + "TEST") # 输出连接的字符串##list list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]tinylist = [123, 'john']print list # 输出完整列表print list[0] # 输出列表的第一个元素print list[1:3] # 输出第二个至第三个的元素 print list[2:] # 输出从第三个开始至列表末尾的所有元素print tinylist * 2 # 输出列表两次##元组tou1 = ('11','33','23','1234124');print (tou1);tup1 = ('physics', 'chemistry', 1997, 2000);tup2 = (1, 2, 3, 4, 5, 6, 7 );print ("tup1[0]: ", tup1[0])print ("tup2[1:5]: ", tup2[1:5])tup3=tup1+tup2;print (tup3);#任意无符号的对象,用逗号隔开 默认为元组print ('abc', -4.24e93, 18+6.6j, 'xyz');x, y = 1, 2;print ("Value of x , y : ", x,y);dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};del dict['Name']; # 删除键是'Name'的条目#dict.clear();     # 清空词典所有条目#del dict ;        # 删除词典print ("dict['Age']: ", dict['Age']);#print ("dict['School']: ", dict['School']);

运算符

  • 算术运算符
  • 比较(关系)运算符
  • 赋值运算符
  • 逻辑运算符
  • 位运算符
  • 成员运算符
  • 身份运算符
  • 运算符优先级
##算术运算符a = 21b = 10c = 0c = a + bprint ("1 - c 的值为:", c)c = a - bprint ("2 - c 的值为:", c)c = a * bprint ("3 - c 的值为:", c) c = a / bprint ("4 - c 的值为:", c)c = a % bprint ("5 - c 的值为:", c)# 修改变量 a 、b 、ca = 2b = 3c = a**b print ("6 - c 的值为:", c)a = 10b = 5c = a//b print ("7 - c 的值为:", c)##比较运算符a = 21b = 10c = 0if ( a == b ):   print ("1 - a 等于 b")else:   print ("1 - a 不等于 b")if ( a != b ):   print ("2 - a 不等于 b")else:   print ("2 - a 等于 b")if ( a < b ):   print ("4 - a 小于 b") else:   print ("4 - a 大于等于 b")if ( a > b ):   print ("5 - a 大于 b")else:   print ("5 - a 小于等于 b")# 修改变量 a 和 b 的值a = 5;b = 20;if ( a <= b ):   print ("6 - a 小于等于 b")else:   print ("6 - a 大于  b")if ( b >= a ):   print ("7 - b 大于等于 b")else:   print ("7 - b 小于 b")##Python赋值运算符#a=6;c=2;c **= aprint ("6 - c 的值为:", c)c //= aprint ("7 - c 的值为:", c)##Python位运算符c = a ^ b;        # 49 = 0011 0001print ("3 - c 的值为:", c)c = ~a;           # -61 = 1100 0011print ("4 - c 的值为:", c)c = a << 2;       # 240 = 1111 0000print ("5 - c 的值为:", c)c = a >> 2;       # 15 = 0000 1111print ("6 - c 的值为:", c)##Python逻辑运算符#a = 10b = 20if ( a and b ):   print ("1 - 变量 a 和 b 都为 true")else:   print ("1 - 变量 a 和 b 有一个不为 true")if ( a or b ):   print ("2 - 变量 a 和 b 都为 true,或其中一个变量为 true")else:   print ("2 - 变量 a 和 b 都不为 true")# 修改变量 a 的值a = 0if ( a and b ):   print ("3 - 变量 a 和 b 都为 true")else:   print ("3 - 变量 a 和 b 有一个不为 true")if ( a or b ):   print ("4 - 变量 a 和 b 都为 true,或其中一个变量为 true")else:   print ("4 - 变量 a 和 b 都不为 true")if not( a and b ):   print ("5 - 变量 a 和 b 都为 false,或其中一个变量为 false")else:   print ("5 - 变量 a 和 b 都为 true")##Python成员运算符a = 10b = 20list = [1, 2, 3, 4, 5 ];if ( a in list ):   print ("1 - 变量 a 在给定的列表中 list 中")else:   print ("1 - 变量 a 不在给定的列表中 list 中")if ( b not in list ):   print ("2 - 变量 b 不在给定的列表中 list 中")else:   print ("2 - 变量 b 在给定的列表中 list 中")# 修改变量 a 的值a = 2if ( a in list ):   print ("3 - 变量 a 在给定的列表中 list 中")else:   print ("3 - 变量 a 不在给定的列表中 list 中")##Python身份运算符a = 20b = 20if ( a is b ):   print ("1 - a 和 b 有相同的标识")else:   print ("1 - a 和 b 没有相同的标识")if ( id(a) == id(b) ):   print ("2 - a 和 b 有相同的标识")else:   print ("2 - a 和 b 没有相同的标识")# 修改变量 b 的值b = 30if ( a is b ):   print ("3 - a 和 b 有相同的标识")else:   print ("3 - a 和 b 没有相同的标识")if ( id(a) is not id(b) ):   print ("4 - a 和 b 没有相同的标识")else:   print ("4 - a 和 b 有相同的标识")##Python运算符优先级a = 20b = 10c = 15d = 5e = 0e = (a + b) * c / d       #( 30 * 15 ) / 5print ("(a + b) * c / d 运算结果为:",  e)

运算符优先级

基本语句

##Whilei = 1while i < 10:       i += 1    if i%2 > 0:     # 非双数时跳过输出        continue    print (i)         # 输出双数2、4、6、8、10i = 1while 1:            # 循环条件为1必定成立    print (i)         # 输出1~10    i += 1    if i > 10:     # 当i大于10时跳出循环        break##for 循环语句for letter in 'Python':     # 第一个实例   print ('当前字母 :', letter)fruits = ['banana', 'apple',  'mango']for f in fruits:    print ("当前字母",f);for index in range(len(fruits)):   print ('当前fruit :', fruits[index])##python 中,for … else 表示这样的意思,#for 中的语句和普通的没有区别,else 中#的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样。for num in range(10,20):  # 迭代 10 到 20 之间的数字   for i in range(2,num): # 根据因子迭代      if num%i == 0:      # 确定第一个因子         j=num/i          # 计算第二个因子         print ('%d 等于 %d * %d' % (num,i,j))         break            # 跳出当前循环   else:                  # 循环的 else 部分      print (num, '是一个质数')###else是在for正常执行结束之后才会执行else'''Python break语句,就像在C语言中,打破了最小封闭for或while循环。break语句用来终止循环语句,即循环条件没有False条件或者序列还没被完全递归完,也会停止执行循环语句。break语句用在while和for循环中。如果您使用嵌套循环,break语句将停止执行最深层的循环,并开始执行下一行代码。''''''Python continue 语句跳出本次循环,而break跳出整个循环。continue 语句用来告诉Python跳过当前循环的剩余语句,然后继续进行下一轮循环。continue语句用在while和for循环中。'''for letter in 'Python':     # 第一个实例   if letter == 'h':      continue   print ('当前字母 :', letter)var = 10                    # 第二个实例while var > 0:                 var = var -1   if var == 5:      break;   print ('当前变量值 :', var)'''Python pass 语句Python pass是空语句,是为了保持程序结构的完整性。pass 不做任何事情,一般用做占位语句。'''for letter in 'Python':   if letter == 'h':      pass      print ('这是 pass 块')   print ('当前字母 :', letter)##字符串格式化输出print ("My name is %s and weight is %d kg!" % ('Zara', 21) )hi = '''hi there'''repr(hi)print (repr(hi));print (str(hi))hi #reprlist = ['physics', 'chemistry', 1997, 2000];print ("Value available at index 2 : ")print (list[2]);list[2] = 2001;print ("New value available at index 2 : ")print (list[2]);print (len(list));print (1997 in list);print (list *4);print (list[1:]);print (list[1:3]);print (list[-2]);list.append(122);print (list)print (list.count(122));#print (list.reverse());print (list);print (len(list));mylist = ['aa','cc','bb'];print (mylist);print (min(mylist));print (max(mylist));print (list.reverse());

日期时间函数

##常用的工具函数import time;  # 引入time模块ticks = time.time()print ("当前时间戳为:", ticks)print (time.localtime(time.time()));# 格式化成2016-03-20 11:45:39形式print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 格式化成Sat Mar 28 22:24:24 2016形式print (time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) )# 将格式字符串转换为时间戳t = (2009, 2, 17, 17, 3, 38, 1, 48, 0)secs = time.mktime( t )print ("time.mktime(t) : %f" % secs)print ("asctime(localtime(secs)): %s" % time.asctime(time.localtime(secs)))##calendar# 获得今天的日期,并计算昨天和明天的日期'''You have a file called operator.py in the current directory,so import operator is picking up your module and not the Python standard library module operator.You should rename your file to not conflict with Python's standard library.'''import datetimeimport calendartoday = datetime.date.today()yesterday = today - datetime.timedelta(days = 1)tomorrow = today + datetime.timedelta(days = 1)print(yesterday, today, tomorrow)last_friday = datetime.date.today()oneday = datetime.timedelta(days = 1)while last_friday.weekday() != calendar.FRIDAY:    last_friday -= onedayprint(last_friday.strftime('%A, %d-%b-%Y'))today = datetime.date.today()target_day = calendar.FRIDAY; #目标print ("目标",target_day)this_day = today.weekday(); #今天的星期print ("today",this_day)delta_to_target = (this_day - target_day) % 7print ("求余",delta_to_target)va = (0-4)%7;##负数求模就是做差print (va)last_friday = today - datetime.timedelta(days = delta_to_target)print(last_friday.strftime("%d-%b-%Y"))def total_timer(times):    td = datetime.timedelta(0)    duration = sum([datetime.timedelta(minutes = m, seconds = s) for m, s in times], td)    return durationtimes1 = [(2, 36),          (3, 35),          (3, 45),          ]times2 = [(3, 0),          (5, 13),          (4, 12),          (1, 10),          ]assert total_timer(times1) == datetime.timedelta(0, 596)assert total_timer(times2) == datetime.timedelta(0, 815)print("Tests passed.\n"      "First test total: %s\n"      "Second test total: %s" % (total_timer(times1), total_timer(times2)))
##函数def printme(str):    "打印任何传入的字符串"    print (str)    returnprintme("我要调用用户自定义函数!");printme("再次调用同一函数");##notice list in python is 广义表def changeme(mylist):    "change the list getted"    mylist.append([1,2,3,4])    print ("in the function Value",mylist)    returnmylist=[5,6,7]changeme(mylist)print (mylist)printme(str = "My string");#可写函数说明def printinfo( name, age ):   "打印任何传入的字符串"   print ("Name: ", name);   print ("Age ", age);   return;#调用printinfo函数printinfo( age=50, name="miki" );# 可写函数说明def printinfo1( arg1, *vartuple ):   "打印任何传入的参数"   print ("输出: ")   print (arg1)   for var in vartuple:      print (var)   return;# 调用printinfo 函数printinfo1( 10 );printinfo1( 70, 60, 50 );# 可写函数说明sum = lambda arg1, arg2: arg1 + arg2;# 调用sum函数print ("相加后的值为 : ", sum( 10, 20 ))print ("相加后的值为 : ", sum( 20, 20 ))min = lambda a1,a2,a3: a1+a2+a3;print (min(1,3,4))

文件IO

# 打开一个文件fo = open("data.py", "wb")print ("文件名: ", fo.name)print ("是否已关闭 : ", fo.closed)print ("访问模式 : ", fo.mode)#print ("末尾是否强制加空格 : ", fo.softspace)#fo.close()fo = open("foo.txt", "w")fo.write( "www.runoob.com!\nVery good site!\n");fo = open("foo.txt", "r+")str = fo.read(10);print ("读取的字符串是 : ", str)# 关闭打开的文件fo.close()fo = open("foo.txt", "r+")str = fo.read(10);print ("读取的字符串是 : ", str)# 查找当前位置position = fo.tell();print ("当前文件位置 : ", position)str = fo.read(10);print (str);# 把指针再次重新定位到文件开头position = fo.seek(0, 0);str = fo.read(10);print ("重新读取字符串 : ", str)# 关闭打开的文件fo.close()import os;'''os.mkdir("newdir");os.chdir("newdir");print (os.getcwd());'''fo = open("foo.txt", "r")print ("文件名为: ", fo.name)line = fo.readline()print ("读取第一行 %s" % (line))line = fo.readline(5)print ("读取的字符串为: %s" % (line))# 关闭文件fo.close()# 打开文件fo = open("foo.txt", "r+")print ("文件名为: ", fo.name)# 截取10个字节fo.truncate(5)##截取部分字符str = fo.read()print ("读取数据222: %s" % (str))# 关闭文件fo.close()# 打开文件fo = open("test.txt", "w")print ("文件名为: ", fo.name)str = "菜鸟教程"fo.write( str )fo = open("test.txt", "r")print (fo.readlines());# 关闭文件fo.close()

异常的使用

try:   fh = open("testfile", "w")   fh.write("This is my test file for exception handling!!")except IOError:   print ("Error: can\'t find file or read data")else:   print ("Written content in the file successfully")   fh.close()try:    fo=open("test","r");except IOError:    print ("exception raise!");else:    print ("read ok");    fo.close();##自定义异常class Networkerror(RuntimeError):   def __init__(self, arg):      self.args = argtry:   raise Networkerror("Bad hostname")except Networkerror as e:   print (e.args)
0 0
原创粉丝点击