Python基础语法


基础
字符数组、列表等容器下标从0开始

Python数据类型

  • 数字    
    
    
  1. var1 = 1
  • 字符串    
    
    
  1. str = 'Hello World!'    下标访问字符串类似列表
  • 列表      
    
    
  1. list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]  
  2. print list[0]       # Prints first element of the list
  3. print list[1:3]     # Prints elements starting from 2nd to 4th
  4. print list[2:]      # Prints elements starting from 3rd element
  5. del list[0] # Delete first element of the list
  • 元组      
    
    
  1. tinytuple = (123, 'john')    元组可以被认为是只读的列表。
  • 字典      
    
    
  1. tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
  2. print dict['one']       # Prints value for 'one' key
  3. print dict[2]           # Prints value for 2 key
  4. print tinydict          # Prints complete dictionary
  5. print tinydict.keys()   # Prints all the keys
  6. print tinydict.values() # Prints all the values


三引号让程序员从引号和特殊字符串的泥潭里面解脱出来;
一个典型的用例是,处理HTML或者SQL
cursor.execute('''
CREATE TABLE users (  
login VARCHAR(8), 
uid INTEGER,
prid INTEGER)
''')

内嵌 if...elif...else 结构

    
    
  1. if expression1:
  2.    statement(s)
  3. elif expression2:
  4.    statement(s)
  5. else:
  6.    statement(s)

while 循环

    
    
  1. while expression:
  2.    statement(s)
  3. 单行while子句的例子:
  4. while expression : statement


for 循环

    
    
  1. for iterating_var in sequence:
  2.     statements(s)

例子:

    
    
  1. fruits = ['banana', 'apple',  'mango']
  2. for index in range(len(fruits)):
  3.    print ('Current fruit :', fruits[index])
  4. for fruit in fruits:
  5.    print ('Current fruit :', fruit)


range
    
    
  1. >>> range(1,5) #代表从1到5(不包含5)
  2. [1, 2, 3, 4]
  3. >>> range(1,5,2) #代表从1到5,间隔2(不包含5)
  4. [1, 3]
  5. >>> range(5) #代表从0到5(不包含5)
  6. [0, 1, 2, 3, 4]


break 语句、continue 
pass 语句: 空操作 ; 在执行时什么也不会发生

函数

    
    
  1. def functionname( parameters ):
  2.     function_suite
  3.     return [expression]

例子:
    
    
  1. def functionname( parameters ):
  2. a = parameters+' world'
  3. return a
  4. print (functionname('hello'))
不定长参数
加了星号(*)的变量名会存放所有未命名的变量参数。选择不多传参数也可。如下实例:
    
    
  1. def printinfo( arg1, *vartuple ):
  2. print arg1
  3. for var in vartuple:
  4. print var
  5. return;
  6. printinfo( 10 );
  7. printinfo( 70, 60, 50 );


     
     
  1. class CUser:
  2. __Id = 0 # 私有变量
  3. Version = '1.0' # 公有变量
  4. "这里self参数就会告诉方法是哪个对象来调用的.这称为实例引用"
  5. def __init__(self,id,name):
  6. self.__Id = id
  7. self.Name = name
  8. def get_version(self):
  9. return self.Version
  10. "self代表类的实例,而非类[同this]"
  11. def set_name(this,new_name):
  12. this.Name = new_name
  13. "调用user.print_dict(),实际是CUser.print_dict(user),也就是说把self替换成类的实例"
  14. def print_dict(self):
  15. print (self.__dict__)
  16. "如果不需要使用self参数可以不用self : CUser.print_class2()"
  17. def print_class():
  18. print (__class__)
  19. user = CUser(1,'hz')
  20. user.set_name('new hz')
  21. print (user.Name)
  22. CUser.print_class()
  23. user.print_dict() #内置属性
  24. print (user.get_version()) #自定义属性:__Id\Name\Version

执行结果
     
     
  1. new hz
  2. <class '__main__.CUser'>
  3. {'Name': 'new hz', 'Id': 1}
  4. 1.0

内置类的属性     
     
     
  1. __dict__ : 字典包含类的命名空间。
  2. __doc__ : 类文档字符串,或者如果是None那么表示未定义。
  3. __name__: 类名
  4. __module__: 其中类定义的模块名称。此属性在交互模式为“__main__”。
  5. __bases__ : 一个可能为空的元组包含基类,其基类列表为出现的顺序。

销毁对象(垃圾回收)
Python 的垃圾收集程序执行过程中运行,当一个对象的引用计数为零时被触发 回收的内存块

类继承、重载
类似C++

import
导入模块;
import module1[, module2[,... moduleN]
从模块中导入一个指定的部分到当前命名空间中
from modname import name1[, name2[, ... nameN]]


打开和关闭文件
    
    
  1. file object = open(file_name [, access_mode][, buffering])
  2. ...
  3. fileObject.read([count]);
  4. fileObject.write(string);
  5. fileObject.close();

新建目录、删除目录、重命名文件和删除文件
    
    
  1. os.mkdir("newdir")
  2. os.rmdir('dirname')
  3. os.rename(current_file_name, new_file_name)
  4. os.remove(file_name)

获取路径、切换路径
    
    
  1. os.getcwd()
  2. os.chdir("newdir")

处理异常
 try....except...else
    
    
  1. raise [Exception [, args [, traceback]]]
例子:
    
    
  1. class AiError(RuntimeError):
  2. def __init__(self,arg):
  3. self.arg = arg
  4. try:
  5. raise AiError("except AiError!")
  6. # raise "except"
  7. except AiError as e:
  8. print(e.arg)
  9. except:
  10. print("common except...")
  11. else:
  12. print("no except...")
  13. finally:
  14. print("alway execute!")


匹配VS搜索

 

Python的提供两种不同的原语操作基于正则表达式

match匹配检查匹配仅在字符串的开头,而search检查匹配字符串中的任何地方(这是Perl并默认的情况)

    
    
  1. re.match(pattern, string, flags=0)
  2. re.search





搜索和替换

    
    
  1. sub(pattern, repl, string, max=0)













  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值