想飞的鱼 Java Dev Engineer

简单python笔记

2017-08-23

python基础

简单整理python语法


http://www.runoob.com/python3/python3-data-type.html

标准数据类型

Python3 中有六个标准的数据类型:

数据结构

  • Number(数字) int、float、bool、complex 操作
  • String(字符串)操作
  • List(列表) list = [ ‘abcd’, 786 , 2.23, ‘runoob’, 70.2 ] ,操作
  • Tuple(元组) tuple = ( ‘abcd’, 786 , 2.23, ‘runoob’, 70.2 ) 操作
  • Sets(集合)student = {‘Tom’, ‘Jim’, ‘Mary’, ‘Tom’, ‘Jack’, ‘Rose’} 操作
  • Dictionary(字典)dict = {‘name’: ‘abcd’,’code’:1, ‘site’: ‘abcd.com’} 操作

Python3 的六个标准数据类型中:

  • 不可变数据(四个):Number(数字)、String(字符串)、Tuple(元组)、Sets(集合);
  • 可变数据(两个):List(列表)、Dictionary(字典)。

运算符

都可以写到if里面参与逻辑判断

条件控制

  • if
number = 7
guess = -1
guess = int(input("请输入你猜的数字:"))
if guess == number:
        print("恭喜,你猜对了!")
    elif guess < number:
        print("猜的数字小了...")
    else:
        print("猜的数字大了...")
  • where

  • while

    n = 100
       
    sum = 0
    counter = 1
    while counter <= n:
    	if counter == 20:
    		break
        sum = sum + counter
        counter += 1
       
    print("1 到 %d 之和为: %d" % (n,sum))
    
  • for

    for i in range(5):
    	if i == 4:
    		continue
    	print(i)
    
  • exception

    # 定义异常
    class MyError(Exception):
            def __init__(self, value):
                self.value = value
            def __str__(self):
                return repr(self.value)
         
     try:
     	raise MyError(2*2)
     except MyError as e:
     	print('My exception occurred, value:', e.value)
              
    
  • pass Python pass是空语句,是为了保持程序结构的完整性。不做任何事情,一般用做占位语句

函数

# 定义函数
def printvalue( str ):
   "打印任何传入的字符串"
   print (str)
   return
 
# 调用函数
printvalue("hello !")

# 方式2 lambda的匿名函数
# 可写函数说明
sum = lambda arg1, arg2: arg1 + arg2
# 调用sum函数
print ("的值为 : ", sum( 10, 20 ))

pip


# 记录虚拟环境副本 精确版本号以便下个环境部署
pip freeze >requirements.txt

# 安装虚拟环境副本
pip install -r requirements.txt

虚拟环境

# 安装虚拟环境
pip install virtualenv

# 在指定目录创建虚拟环境
virtualenv my_test



文件

线程

thread 库已被遗弃, python3不支持thread, 为了兼容将 thread 重命名为 “_thread”

正则

网络

  • BeautifulSoup
  • urllib
  • requests

json数据处理

数据库

  • mysql PyMysql模块

    
    import pymysql
       
    # 打开数据库连接
    db = pymysql.connect("localhost","root","root","test" )
       
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()
       
    # 使用 execute()  方法执行 SQL 查询 
    cursor.execute("SELECT VERSION()")
       
    # 使用 fetchone() 方法获取单条数据.
    data = cursor.fetchone()
       
    print ("Database version : %s " % data)
       
    # 关闭数据库连接
    db.close()
    

常用模块

内置函数

http://www.runoob.com/python3/python3-built-in-functions.html


上一篇 简单django笔记

Comments

Content