Python基础

作者: JunChow520 | 来源:发表于2019-03-24 23:42 被阅读60次

Python语言特点

  • 开源免费
  • 脚本语言 解释执行
  • 跨平台
  • 简介美观
  • 一切皆对象
  • 可扩展的胶水语言

Python解析执行原理

python解释执行原理

Python是Linux、Unix、Mac OS X等的重要系统组件

# 检查python是否已经安装
$ python --version
Python 2.7.15rc1

$ vim hello.py
print "hello"

$ python hello.py
hello

Python交互执行环境

$ python
Python 2.7.15rc1 (default, Nov 12 2018, 14:31:15) 
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print("hello")
hello

模块加载

模块是包含函数、类、变量等独立的python文件

导入模块并使用模块中的函数

// 导入模块
import module_name 
// 使用模块中的函数
module_name.function_name()
$ vim module.py
def plus(x, y):
  return x + y

$ vim test.py
import module
print module.plus(1, 2)
from module_name import function_name

function_name()

导入系统模块

import sys.path
from os import *

import string, re
import time, random
import socket, threading

time.sleep(1)

print uname()[-1]
// ImportError: No module named path

变量

变量
var = 1
var = var + 1

作用域

def fn(x):
  z = x + y //本地变量 y、z
  return z

x = 1 // 全局变量 x
fn(2)

变量也是对象,在python中一切皆对象,变量是对象有自己的属性和方法。

  • 查看对象类型:变量名.class
  • 调用对象方法:变量名.方法()
$ python
>>> var = 1

>>> dir(var)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']

>>> var.__class__
<type 'int'>

>>> var.__hex__()
'0x1'

内建数据类型

  • Boolean
>>> is_passed = True
  • Integer
>>> number = 100
  • Float
>>> weight = 65.23
  • String
>>> msg = "welcome to visit"
  • List
>>> index_list = [1, 2, 3, 4]
  • Tuple
 >>> index_t uple = (0, 1, 2, 3, 4)
  • Dict
>>> user_dict = {"username":"alice", "age":20}
  • Set
>>> index_set = set([0, 1, 2, 3, 4])
  • None
    None、空字符串''、空元素()、空列表[]、空字典{}

字符串和列表的转换

>>> st = "hello world"

>>> list = str.split() // ["hello", "world"]

>>> list.append("!")

>>> str = string.join(list[1:3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'string' is not defined

insert/pop/sort/index/remove/del...

$ python
>>> help(dict)
>>> help(s)

字典的使用

字典名 = {"关键字":值, ...}

字典名.get("关键字", 默认值)

字典名["关键字"] = 值
$ python

>>> user_dict = {"id":10, "name":"alice"}

>>> user_dict.get("id")
10
>>> user_dict.get("gender", 1)
1
>>> user_dict.get("gender")

>>> user_dict["gender"] = 1

>>> user_dict.get("gender")
1

>>> user_dict.keys()
['gender', 'id', 'name']

>>> user_dict.values()
[1, 10, 'alice']


>>> user2_dict = user_dict.copy()

>>> del user2_dict["name"]

>>> user2_dict.popitem()

表达式

表达式比较,返回TrueFalse

  • = 赋值
  • == 比较是否一样
  • >, < 大于,小于
  • >=, <= 大于等于,小于等于

表达式组合

使用andor进行表达式组合,用于执行逻辑运算。

  • and 逻辑与,电路串联
  • or 逻辑或,电路并联
  • not 逻辑非

x and y 左右都为True结果则为True

x or y 左右有一个或两个为True则为True

not x 若表达式x不为True则为True

人生的道路虽然漫长,但紧要处常常只有几步,特别是当人年轻的时候。 -- 路遥

image.png FTP

逻辑分支

  • Python 当判断条件为True时执行特定语句
  • Python中,除了FalseNone之外都被认为是True
  • Python中不存在switch语句
  • Python中不存在三目运算符
if 条件判断语句:
  ...
else:
  ...
...
if 条件判断语句:
  ...
elif 条件判断语句:
  ...
else:
  ...

实例

gender = "male"
age = 19

if gender == "male":
    print "boy"
elif gender == "female":
    if age < 18:
        print "girl"
    else:
        print "lady"
else:
    print "weather is good"

逻辑循环

  • 循环 重复执行特定语句
for 变量 in 列表:
  ...

循环打印列表元素

list = ["alice", "bob", "lucy", "jim"]

for item in list:
    print item

循环打印元祖元素,元祖是一种特殊的列表。

tuple = (
    (100, "alice","female"), 
    (101, "bob", "male")
)

for id,name,gender in tuple:
    print id,name,gender

循环控制语句

  • continue 进入下一个循环
  • break 退出循环
for i in range(1, 20):
    if i<10:
        continue 
    else:
        print i,"no break/exception"

while循环

  • 但判断条件为True时循环执行
  • while循环支持continuebreakelse对循环进行控制
while 判断条件:
  ...
i = 0

while i < 10:
    print i
    i+=1

迭代器

obj = range(5)
iterator = iter(obj)

try:
    while True:
        print iterator.next()
except StopIteration:
    pass
  • iter(obj)等价于obj.__iter__()
  • 迭代器中无元素可取出时抛出异常

函数

函数的定义和调用,函数通过组合特定代码,实现可重复执行的特定功能。

# 函数定义
def 函数名():
  函数体

# 函数调用
函数名()
def welcome():
    print("welcome to visit")

welcome()

函数参数:函数通过参数接收数据

  • 形式参数、实际参数
# 函数定义
def 函数名(参数列表):
  函数体

# 函数调用
函数名(参数列表)
def fn(who, act):
    print(who+" "+act)

fn("jim", "sleep")

变长参数

变长参数会被自动转变为以参数名命名的元祖或字典

def 函数名(*args):
  函数体

函数名(v1, v2, v3)
def 函数名(**args):
  函数体

函数名(k1=v1, k2=v2)

元祖

def fn(*args):
    print(args)

fn("id", "name", "gender")

('id', 'name', 'gender')

字典

def fn(**args):
    print args

fn(id=1, name="alice")

{'id': 1, 'name': 'alice'}

参数默认值

  • 当不指定参数时使用默认参数,指定参数时使用指定值。
  • 必须给无默认值的参数赋值且保证顺序
def fn(id, name="name"):
    print id,name

fn(1, "alice")
fn(2, name="bob")
fn("carl")

函数返回值

  • 每个方法都绝对会有一个返回值(返回对象)
  • 当没有return时,函数默认返回一个None对象。

面向对象 - 类

  • python中一切都是对象,类和对象是面向对象的基础。
  • class 类名称
  • def 方法名(self, 参数列表)
  • 实例化方法的调用为 实例名.方法名(参数列表)
class Klass:
    def __init__(self, name, age):
        self.name = name
        self.age = age

obj = Klass("alice", 18)

print(obj.name)
# alice

print(type(obj))
# <type 'instance'>

print(obj.__class__)
# __main__.Klass
class DB:
    def __init__(self, host, port, user, pwd):
        self.host = host
        self.port = port
        self.user = user
        self.pwd = pwd
    def connect(self):
        print("db connect success", self.host, self.port)

obj = DB("127.0.0.1", 3306, "root", "root")
obj.connect

文件IO

  • print 输出数据到标准输出
  • raw_input 从标准输入读取数据
input= raw_input("prompt@ ")
print(input)

file类 读取文件

filepath = "test.txt"

# 创建file类实例fp,以只读模式打开文本文件。
fp = file(filepath, "r")

# 通过fp实例读取文件内容
content = fp.read()

# 关闭文件实例释放资源
fp.close()

print(content)

文件打开模式

  • r 只读
  • w 只写
  • a 追加
  • b 以二进制方式打开文件
  • r+a+ 更新

open() 使用open函数打开文件返回一个file类实例

# 使用open函数打开文件返回一个file类实例
fp = open("test.txt", "r")

print(type(fp))
# <type 'file'>

print(type(open))
# <type 'builtin_function_or_method'>

读取方式

#-*-coding:utf-8-*-

# 使用open函数打开文件返回一个file类实例
fp = open("test.txt", "r")

# 读取全部返回字符串
# str= fp.read()
# print(str)

# 一次读取一行并返回字符串
# line= fp.readline()
# print(line)

# 读取全部返回列表
list = fp.readlines()
print(list )

若出现错误:SyntaxError: Non-ASCII character '\xe4' in file...,则需要在文件开头添加 #-*-coding:utf-8-*- 以确保文件的编码方式。

file类写文件

# 以追加模式打开文件并返回一个file类实例
fp = file("test.txt", "a")

# 向文件中写入字符串(追加)
fp.write("write content to file")

# 刷新缓冲
fp.flush()

# 关闭文件释放资源
fp.close()

根据命令行输入,将其保存到文件中。

fp = file("test.txt", "a")

while True:
    input = raw_input()
    if input == "exit":
        fp.close()
        break
    fp.write(input + "\n")

从文件中逐行读取内容并输出到屏幕

fp = file("test.txt", "r")
for item in fp.readlines():
    print(item)
fp.close()

相关文章

网友评论

    本文标题:Python基础

    本文链接:https://www.haomeiwen.com/subject/wwnhvqtx.html