一点python基础知识

python入门推荐:A byte of python

链接:http://pan.baidu.com/s/1boZ8auF

如何退出解释器?
(1)windows下 :按下ctrl+z 并敲击enter
(2)GNU/Linux 或 OS X 上的 Shell 程序,可以通过按下 [ctrl + d] 组
合键或是输入 exit()

==学习使用Vim或者Emacs==

通过‘#’即可实现注释

写程序注释很重要。

字面常量。

数字:整数,浮点数。
字符串:就是很多字符,嗯,没错,就是这样。可以通过单引号,双引号,三引号来指定字符串。当然,三引号更多的用来表示多行字符串。

字符串是不可变得,一经创建,则不可修改。

>>>name='liudongqing'
>>>name[0]='a‘

#这种操作是错误的。对,没错,没有这样的操作,而不是“字符串居然有这样的操作”

当需要从其他信息中构建字符串时,可使用format()

age = 20
name = 'Swaroop'
print('{0} was {1} years old when he wrote this book'.format(name, age))
print('Why is {0} playing with that python?'.format(name))

print(x,end=’…’) #可以规定所打印的内容以什么结尾

转义符 \

原始字符串,在字符串之前添加’r’

Python将程序中的一切均看为对象。是强面向对象的语言,数字,字符串,函数均被看作字符串。

物理行:就是你所能看到的一行行代码
逻辑行:Python所看到的单个语句,Python会假定一个物理行对应一个逻辑行。

缩进在Python中很重要。它确定了程序的不同块。Python官方推荐使用 四个空格作为缩进。

运算符与表达式。
** 乘方 //整除

程序控制语句

if语句

if condition:
    execute this

input()返回的为字符串类型的数据

while语句
for语句

for x in range(10):
    print(x)

range(1,5) 包括起始但不包括结束。
[1,2,3,4]
还可以设置第三个参数,选择以多少递增。

range() 每次只会生成一个数字,如果你希望获得完整的数字列表,要
在使用 range() 时调用 list() 。

break 语句用以中断(Break)循环语句,也就是中止循环语句的执行。

continue 语句用以告诉 Python 跳过当前循环块中的剩余语句,并继续该循环的下一次迭代。

函数

函数就是一段可以重复使用的代码。通过def关键字定义,后面跟函数名,(形参),再以冒号结尾。

def functionName():
    print("Python is the best programminglanguage")

functionName()
函数参数
def loveConnect(name1,name2):
    print(name1 + 'love' + name2)

loveConnect('ldq','SQ')
局部变量
x1=0
def change():
    x2=1
change()
print(x1)   #用来观察x1是否会受到局部变量x2的影响
#此处x2就是局部变量

需要定义一个全局的变量时,需要使用global语句。

默认参数值,当你不传入参数时,即为默认值。
def Infor(name,city='beijing'):
    print(name + 'live in' + city)

Infor('zhangsan')
Infor('liudongqing','lanzhou')

==只有那些位于参数列表末尾的参数才能被赋予默认参数值,意即在函数的参数列表中拥
有默认参数值的参数不能位于没有默认参数值的参数之前==

关键字参数
def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7)
func(25, c=24)
func(c=50, a=100)
可变参数

参数数量是可变的,可以通过*实现

文档字符串(DocStrings)
def print_max(x, y):
    '''Prints the maximum of two numbers.打印两个数值中的最大数。
The two values must be integers.这两个数都应该是整数'''
    # 如果可能,将其转换至整数类型
    x = int(x)
    y = int(y)
    if x > y:
        print(x, 'is maximum')
    else:
     print(y, 'is maximum')
print_max(3, 5)
print(print_max.__doc__)

该文档字符串所约定的是一串多行字符串,其中第一行以某一大写字母开始,以句号结束。
第二行为空行,后跟的第三行开始是任何详细的解释说明

模块(module)
import sys
print('The command line arguments are:')
for i in sys.argv:
    print(i)    
    //sys.argv  变量是一系列字符串的列表(List)
print('\n\nThe PYTHONPATH is', sys.path, '\n')
from … import …语句

如果希望导入sys模块中的argv变量,可以采用from sys import args。当然,应该尽可能避免这种方式,因为这样有可能在你的程序中造成同名冲突。

from math import sqrt
print("Square root of 16 is", sqrt(16))
模块的name

每个模块都有一个名称,而模块中的语句可以找到它们所处的模块的名称。这对于确定模块
是独立运行的还是被导入进来运行的这一特定目的来说大为有用。正如先前所提到的,当模
块第一次被导入时,它所包含的代码将被执行。

//保存为module.py
if __name__=='__main__':
    print('I am running by myself')
else:
    print('I am imported')

//在相同目录下创建一个py文件,导入moudle
import module

每一个 Python 模块都定义了它的 name 属性。如果它与 main 属性相同则代表这一
模块是由用户独立运行的

编写自己的模块
//保存为my_module.py
def say():
    print("I am happy to learn python")
__version__=‘1.0

在另一程序中导入my_module,注意,这两个文件需要在同一个目录之下。

import my_module

my_module.say()
print('version: ',my_module.__version__)
dir函数

该函数会返回由对象所定义的名称列表。如果该列表为一模块,则会返回模块所定义的函数,类,变量。

该函数接受参数。 如果参数是模块名称,函数将返回这一指定模块的名称列表。 如果没有提

供参数,函数将返回当前模块的名称列表

当需要组织很多模块的时候,就需要包(package)。

包是指一个包含模块与一个特殊的 init.py 文件的文件夹,后者向 Python 表明这一文
件夹是特别的,因为其包含了 Python 模块。

数据结构

Python 中有四种内置的数据结构——列表(List)、元组(Tuple)、字典(Dictionary)和集
合(Set)

nameList=['ldq','zhangsan','lisi']

nameList.append('this is added at end')//将元素添加至末尾

//列表是可变的(mutable)
nameTuple=(1,2,3,4)

元组如同字符串一样是不可变的。

一个demo

zoo = ('python', 'elephant', 'penguin')
print('Number of animals in the zoo is', len(zoo))
new_zoo = 'monkey', 'camel', zoo
print('Number of cages in the new zoo is', len(new_zoo))
print('All animals in new zoo are', new_zoo)
print('Animals brought from old zoo are', new_zoo[2])
print('Last animal brought from old zoo is', new_zoo[2][2])
print('Number of animals in the new zoo is',
len(new_zoo)-1+len(new_zoo[2]))

//一个空的元组
zoo=()

//一个元素的元祖
zoo(1,)
字典
d = {key : value1 , key2 : value2}

//key必须是不可变对象

dict={
    'name':'DoctorLDQ','age':'19','sex':'male'
} 
//字典中的成对的键值—值配对不会以任何方式进行排序

ab = {
'Swaroop': '[email protected]',
'Larry': '[email protected]',
'Matsumoto': '[email protected]',
'Spammer': '[email protected]'
}
print("Swaroop's address is", ab['Swaroop'])
# 删除一对键值—值配对
del ab['Spammer']
print('\nThere are {} contacts in the address-book\n'.format(len(ab)))
for name, address in ab.items():
qprint('Contact {} at {}'.format(name, address))
# 添加一对键值—值配对
ab['Guido'] = '[email protected]'
if 'Guido' in ab:
    print("\nGuido's address is",ab['Guido'])

字典的item()方法获取字典中每一对键值对的信息。

集合(set)简单对象的无序集合。

fruit1=set(['apple','strawberry','lemon'])
fruit.add('banana')
fruit
fruit.remove('apple')
fruit1 & fruit2 //可用来求公共集合
fruit1.issuperset(fruit2)   //判断是否为set

==如果你希望创建一份诸如序列等复杂对象的副本(而非整数这种简单的对象
(Object)),你必须使用切片操作来制作副本==

字符串

name='liudongqing'

if name.startswith('l'):
    print('Start with l')
if 'a' in name:
    print('a is in name')
if name.find('ing')!=-1:    //如果找不到则返回-1
    print('contain ing')


delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print(delimiter.join(mylist))
软件开发流程
  1. What/做什么(分析)
  2. How/怎么做(设计)
  3. Do It/开始做(执行)
  4. Test/测试(测试与修复错误)
  5. Use/使用(操作或开发)
  6. Maintain/维护(改进
  7. 7.

类与对象

class my:
    def say_hello(self):
        print('Learing python')
p=my()
p.say_hello()

init方法是类中一个特殊的方法,在对象被实例化时会立即调用。不会显示调用它。

class my:
    def __init__(self,name):
        self.name = name
    def say_hello(self):
        print(' Learing python',self.name)
p=my('liudongqing')
p.say_hello()
类变量与对象变量


据部分——也就是字段——只不过是绑定(Bound)到类与对象的命名空间(Namespace)
的普通变量

字段(Filed)有两种类型——类变量与对象变量。

类变量是共享的,可以被类的所有实例访问。该变量只有一个副本,当一个发生变化时,其它实例中也会有所体现。

对象变量(Object variable)由类的每一个独立的对象或实例所拥有。

==每个对象可以都通过

self.class 属性来引用它的类

定义一个classmethod

@classmethod
def how_many(cls):
"""打印出当前的人口数量"""
print("We have {:d} robots.".format(cls.population))

私有变量:__name

任何在类或对象之中使用的变量其命名应以2个下划线开头,其
它所有非此格式的名称都将是公开的,并可以为其它任何类或对象所使用

class schoolWorker:
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def tell(self):
        print("My name is {0}.I am {1} years old".format(self.name,self.age),end='.')
class Teacher(schoolWorker):
    def __init__(self,name,age,job):
        schoolWorker.__init__(self,name,age)
        self.job=job
    def tell(self):
        schoolWorker.tell(self)
        print('My job is {}'.format(self.job),end='\n')

class student(schoolWorker):
    def __init__(self,name,age,job):
        schoolWorker.__init__(self,name,age)
        self.job=job
    def tell(self):
        schoolWorker.tell(self)
        print("My job is {}".format(self.job))


ST=Teacher('liudongqing',19,'teacher')
ST.tell()

SS=student('liudongqing','20','student')
SS.tell()

mem=[ST,SS]
for x in mem:
   x.tell()

==如果在子类中定义了init(),则Python不会自动调用基类的init(),你需要在子类的init()中显示调用。如果我们没有在一个子类中定义一个 init 方法,Python 将会自动调用基类的构
造函数==
记到这里的感觉就是python真的是一种包容性很强的语言。

如果继承元组(Inheritance Tuple)中有超过一个类,这种情
况就会被称作多重继承(Multiple Inheritance)

输入与输出
get=input("Input a word:")  //让用户输入,所获取的值是一个字符串
rget=get[::-1]  //可以将一个字符串进行反转
if(get==rget):
    print("It is a palindrom!")
else:
    print("It is not a palindrom!")
print(rget)

Pickle模块,可以将任何纯Python对象存储到一个文件中,并在之后将其取回。

try…except处理异常。

可以有一个else语句与try..except语句块相关联。

我们自己可以通过raise引发一次异常,需要提供异常名或错误名,以及要抛出异常的对象。

class MathException(Exception):     //注意此处,自己通过raise所引发的异常必须是Exception的子类
    def __init__(self,number):
        Exception.__init__(self)    //因为写了__init__方法,所以此处需要显示调用基类__init__方法
        self.number=number

try:
    number=int(input("Input a number :"))   //通过input()得到的是一个字符串,此处需要转换为一个数字,当然还可以采用float()
    if (number == 0):
        raise MathException(0)
    else:
        print("The number is {}".format(number))
except MathException:   //捕获自己所引发的异常。
    print("0 操作数不能进行操作")

当程序在运行时,可以通过ctrl+c停止程序运行

with语句

with  open('except.txt') as f
for line in f:
    print(line,end=' ')
标准库

//之后进行补充。

从一个函数返回两个数值如何实现?
哈哈,当然是返回一个元组

def get():
    return ('liudongqing',19)

v=get()
print(v)
//当然,我在书中看到python所实现的一种极为简单的交换我数的方法。但是,现在不太清楚原理是什么。。。。。
a,b=b,a
列表推导式
>>> li=[1,2,3,4,5,6,7,8,9,10]
>>> litwo=[x * x for x in li if x%2==0]
>>> litwo
[4, 16, 36, 64, 100]
在函数中接收元组与字典

分别使用* 或 **作为元组和字典的前缀,来使它们作参数为函数所接收。

//此段代码没有自己完成
>>> def powersum(power, *args):
... '''Return the sum of each argument raised to the specified power.'''
...     total = 0
...     for i in args:
...         total += pow(i, power)
...         return total
...
>>> powersum(2, 3, 4)
25
>>> powersum(2, 10)
100

assert语句。
可以用来断言某种情况为真或假

>>> assert len(list)
>>> list.pop()
'item'
>>> list
[]
>>> assert len(list)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

猜你喜欢

转载自blog.csdn.net/DoctorLDQ/article/details/74857230