Python快速入门

Python快速入门

 一、基础概要

命名:h.py

Linux命令行运行:python h.py

注释、数字、字符串:

基本类型只有数字与字符串

#python注释是这样写的
'''  
当然也可以这样
'''
"""
或者这样"""

#数字分为整数和浮点数
#浮点数可以这样:
a = 3.14E-4

#而字符串和Java中的一样,是不可变的,在Python中一切都是对象
#字符串,数字常量也一样,意思是可以直接对它使用方法

格式化方法:

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('{} was {} years old when he wrote this book'.format(name, age))
#对于浮点数'0.333'保留小数点后三位
# 使用下划线填充文本,并保持文字处于中间位置
# 使用 (^) 定义 '___hello___'字符串长度为 11
print('{0:_^11}'.format('hello'))
# 基于关键词输出 'Swaroop wrote A Byte of Python'
print('{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python'))

#禁用自动换行,end 指定用什么结尾,默认为换行符
print('a', end='')

转义序列'\':

在Python中'\'除了用作转移序列外,可以表示下一行继续,而不添加新一行。

"This is the first sentence. \
This is the second sentence."
#相当于
"This is the first sentence. This is the second sentence."

i = \
5
#相当于
i = 5

原始字符串:

在字符串前用R或者r表示原始字符串,所谓原始字符串,跟bash shell中单引号效果相同

R'Hello, how are you.\n'  #这里的'\n'不会导致换行

逻辑行、物理行、缩进

二、运算符与表达式

大体同其他语言相同,只对不同的地方做说明。

1. '//'表示整除,对结果进行向下取整

如:13//3  输出4        -13//3输出-5

2.not 布尔非    or布尔或     and布尔与

3.求值顺序:   lambda表达式------>if  else表达式-------->布尔或-->与--->非...........

length = 5
breadth = 2
area = length * breadth
print('Area is', area)
print('Perimeter is', 2 * (length + breadth))
#输出:
'''
Area is 10
Perimeter is 14'''
#注意自动加空格

三、控制流

if

#! /usr/bin/python3                         
num = 35                                    
guess = int(input('Input a number please:'))
if guess == num:                            
    print('equal')                          
elif guess > num:        #特别注意 else if 的python写法                   
    print('>')                              
else:                                       
    print('<')                              
print('Game Over!')                         

另外Python中不存在switch

while:

while bol:
    #do sth
else:
    #do others
#特别注意可以使用else从句

for:

注意python中没有C形式的for(int i=0; i < 10;i++)的for,取而代之的是

for i in range(1,5):
    print(i)
else:
    #do others
#注意同样也有else从句

break和continue:

注意:如果用break中断了for或者while语句,else从句一样也不会执行

四、函数

1.用def关键字定义一个函数

2.局部变量:在函数内部中定义的变量,同Java方法中的变量类似,只存在于函数这一局部

如果想在函数或者类的内部给一个顶层变量赋值,可使用global语句(当然能不使用global就不要使用它)。

#! /usr/bin/python3
x = 8
def fun():
    global x
    print('the x that not changed is',x) #8
    x = 9
    print('change x to',x) #9
fun()
print('Now the x is',x) #9

默认参数值:

#! /usr/bin/python3
def say(msg,times=1,c=5):    #参数列表中拥有默认参数值的参数不能位于无默认参数值的参数前面
    print(msg * times)
    print(c)
say('hi')
say('hi',3)
say(c=8,times=5,'sss') #我们使用标识符而非参数位置来指定函数中的参数

可变参数:

#! /usr/bin/python3
def fun(a=88,*itmes,**maps):
    print('a={}'.format(a))
    for itme in itmes:
        print('item is',itme)
    for m, n in maps.items():
        print('map is',m,n)
fun(99,1,2,3,4,5,6,tang=555,jia=666,pi=888)
'''
a=99
item is 1
item is 2
item is 3
item is 4
item is 5
item is 6
map is pi 888
map is jia 666
map is tang 555
'''

注意:形参前一个'*'代表元组,两个代表字典

文档字符串(DocStrings):

函数、模块与类的第一逻辑行的字符串为逻辑字符串

#! /usr/bin/python3
def print_max(x, y):
    '''Print the max of two numbers
    The two values must be integers.'''
    x = int(x)
    y = int(y)
    if x > y:
        print(x, 'is max number.')
    elif y > x:
        print(y, 'is max number')
    else:
        print(x+' is equal to '+y)
print_max(5,8)
print(print_max.__doc__)  #通过print_max.__doc__获取文档字符串,记住python中的一切都是对象

五、模块

编写模块方式:

1.写一个.py

2.用Python解释器本身的本地语言来编写模块。

导入模块语法:

首先要注意导入模块时,Python解释器首先从sys.path目录(当前目录即程序的启动目录也是其一部分)进行搜索

1.import modulName

2.from modulName import sth(尽量避免使用)

如果想更快地导入模块,可以先把模块编译成对应的.pyc

每个模块都定义的它的__name__属性,如果该属性为'__main__'则代表这一模块是由用户独立运行。

dir()函数能够返回由对象所定义的名称列表,如果该对象为模块文件,则该列表会包括模块所定义的函数、类与变量。

包是指一个包含模块与特殊__init.py__文件的文件夹,后者向Python表明该文件夹是一个包。

六、数据结构

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

List

列表是一种用于保存有序项目的可变集合,此外可以向列表添加任何对象

#! /usr/bin/python3
a = ['apple','banana','orange']
#
a.append('rice')
#
del a[1]
#
a[0] = 'noodle'
for item in a:
    print(item,end = '|')

Tuple

元组,可以理解为不可变的列表

#! /usr/bin/python3
zoo = ('Java','Kotlin','Bash Shell','Python','JavaScript')
new_zoo = ('C','C++','C#',zoo)
print(new_zoo[3][3])

Dictionary

类似Java中的map集合,键值对集合,注意只可使用不可变的对象作为键。

war = {                      
       'tang':'God like man',
       'Tom':'Cat',          
       'Jerry':'mouse'       
}                            

使用in运算符检验键值对是否存在

序列

List、Tuple和字符串都可以看作序列(Sequence)的某种表现形式。

序列的主要功能是资格测试(Membership Test) (也就是 in not in 表达式) 和索引
操作(Indexing Operations) ,它们能够允许我们直接获取序列中的特定项目。

上面所提到的序列的三种形态——列表、元组与字符串,同样拥有一种切片(Slicing) 运算
符,它能够允许我们序列中的某段切片——也就是序列之中的一部分。

shoplist = ['apple', 'mango', 'carrot', 'banana']
name = 'swaroop'
# Indexing or 'Subscription' operation #
# 索引或“下标(Subscription) ”操作符 #
print('Item 0 is', shoplist[0])
print('Item 1 is', shoplist[1])
print('Item 2 is', shoplist[2])
print('Item 3 is', shoplist[3])
print('Item -1 is', shoplist[-1])
print('Item -2 is', shoplist[-2])
print('Character 0 is', name[0])
# Slicing on a list #
print('Item 1 to 3 is', shoplist[1:3])
print('Item 2 to end is', shoplist[2:])
print('Item 1 to -1 is', shoplist[1:-1])
print('Item start to end is', shoplist[:])
# 从某一字符串中切片 #
print('characters 1 to 3 is', name[1:3])
print('characters 2 to end is', name[2:])
print('characters 1 to -1 is', name[1:-1])
print('characters start to end is', name[:])

Set

即简单对象的无序集合。 集 合 是 一 个 无 序 不 重 复 元素 的 集 。 基 本 功 能 包 括 关 系 测 试 和 消 除 重 复 元 素 。 集 合 对 象 还 支 持 union( 联
合),intersection(交),difference(差)和 sysmmetric difference(对称差集)等数学运算.

大括号或 set() 函数可以用来创建集合。 注意:想要创建空集合,你必须使用set() 而不是 {} 。{}用于创建空字典

 a={"peace","peace","rong","rong","nick"}                                         
   print(a)                                                                         
   "peace" in  a                                                                    
   b=set(["peace","peace","rong","rong"])                                               
   print(b)                                                                         
   #演示联合                                                                        
   print(a|b)                                                                       
   #演示交                                                                          
   print(a&b)                                                                       
   #演示差                                                                          
   print(a-b)                                                                       
  #对称差集                                                                        
  print(a^b)    
#输出:    
{'peace', 'rong', 'nick'}
{'peace', 'rong'}
{'peace', 'rong', 'nick'}
{'peace', 'rong'}
{'nick'}
{'nick'}

引用

print('Simple Assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
# mylist 只是指向同一对象的另一种名称
mylist = shoplist
# 我购买了第一项项目,所以我将其从列表中删除
del shoplist[0]
print('shoplist is', shoplist)
print('mylist is', mylist)
# 注意到 shoplist 和 mylist 二者都
# 打印出了其中都没有 apple 的同样的列表,以此我们确认
# 它们指向的是同一个对象
print('Copy by making a full slice')
# 通过生成一份完整的切片制作一份列表的副本
mylist = shoplist[:]
# 删除第一个项目
del mylist[0]
print('shoplist is', shoplist)
print('mylist is', mylist)
# 注意到现在两份列表已出现不同

七、面向对象编程

对象可以使用属于它的普通变量来存储数据。这种从属于对象或类的变量叫作字段
Field) 。对象还可以使用属于类的函数来实现某些功能,这种函数叫作类的方法
Method) 。这两个术语很重要,它有助于我们区分函数与变量,哪些是独立的,哪些又是
属于类或对象的。总之,字段与方法通称类的属性(Attribute)

#! /usr/bin/python3
class Person:
#所谓构造函数,类中的方法都必须有self参数
    def __init__(self, name):
        self.name = name
    def say_hi(self):
        print('Hello, my name is',self.name)
Person('Tom').say_hi()

类变量与对象变量

不解释,上代码:

class Roboot:
    #定义一个类变量
    count = 0
    def __init__(self,name):
        #这里self.name就是一个对象变量
        self.name = name
        print('Creating {}'.format(self.name))
        #改变一个类变量,也可用:self.__class__.count引用
        Roboot.count += 1
    def destroy(self):
        print("Destroying {}".format(self.name))
        Roboot.count -= 1
    #定义一个类方法
    @classmethod
    def how_many(cls):
        print("We have {:d} roboots.".format(cls.count))

tom = Roboot('Tom')
jerry = Roboot('Jerry')
#调用类方法:
Roboot.how_many()
tom.destroy()
dog = Roboot('Dog')
wore = Roboot('Wore')
Roboot.how_many()

注意:Python中所有的类变量默认都是公有的,要使类变量成为私有必须'__varName',即变量名前加两下划线。

继承

class Schooler:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print('Creating Schooler: {}'.format(self.name))
    def tell(self):
        print('Name: {} Age:'.format(self.name, self.age), end=' ')

class Teacher(Schooler):
    #如果子类不定义一个__init__函数,将会继承父类的
    def __init__(self, name, age, salary):
        #子类必须显式地调用父类构造函数,父类构造函数才会被调用
        Schooler.__init__(self, name, age)
        self.salary = salary
        print('Creating Teacher: {}'.format(self.name))
    def tell(self):
        #当调用同名方法时,python总会先从子类中寻找方法
        Schooler.tell(self)
        print('Salary: {:d}'.format(self.salary))
Schooler('Tom',22).tell()
Teacher('Jack',33,8000).tell()

类中的特殊方法:

__init__(self, ...)
这一方法在新创建的对象被返回准备使用时被调用。
__del__(self)
这一方法在对象被删除之前调用(它的使用时机不可预测,所以避免使用它)
__str__(self)
当我们使用 print 函数时,或 str() 被使用时就会被调用。
__lt__(self, other)
当小于运算符(<) 被使用时被调用。类似地,使用其它所有运算符(+> 等等)
时都会有特殊方法被调用。
__getitem__(self, key)
使用 x[key] 索引操作时会被调用。
__len__(self)
当针对序列对象使用内置 len() 函数时会被调用

八、输入与输出

用户输入

处理用户输入可用input()函数,该函数返回用户的输入

文件

通过创建文件类,并调用read(),write()及其readLine()函数

#! /usr/bin/python3
poem = '''\
       Come as you are.
       As you were
       Hurry up......
Nirvana
''' #打开文件编辑(w),还有r,a(追加) f = open('poem.txt','w') f.write(poem) f.close() #默认以读的方式打开,文件不存在会新建一个 f = open('poem.txt') while True: line = f.readline() #长度为0到达文件末尾 if len(line) == 0: break #注意,每行末尾都有换行符 print(line, end = '') f.close()

使用Pickle模块,可以向文件写入python对象

#! /usr/bin/python3
import pickle

listf = 'list.data'
shoplist = ['apple','mango','banana']
#写入二进制'wb'
f = open(listf, 'wb')
#存储对象到文件
pickle.dump(shoplist, f)
f.close()

del shoplist
f = open(listf, 'rb')
#从文件中载入对象
slist = pickle.load(f)
print(slist)

九、异常

使用try...except处理异常

try:
    text = input('Enter something --> ')
except EOFError:
    print('Why did you do an EOF on me?')
except KeyboardInterrupt:
    print('You cancelled the operation.')
else:
    print('You entered {}'.format(text))

使用raise语句来抛出异常,能够抛出的异常必须是Exception的派生类

class ShortInputException(Exception):
    '''一个由用户定义的异常类'''
    def __init__(self, length, atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast
try:
    text = input('Enter something --> ')
    if len(text) < 3:
        raise ShortInputException(len(text), 3)
    # 其他工作能在此处继续正常运行
except EOFError:
    print('Why did you do an EOF on me?')
except ShortInputException as ex:
    print(('ShortInputException: The input was ' +
           '{0} long, expected at least {1}')
           .format(ex.length, ex.atleast))
else:
    print('No exception was raised.')

try...finally

#! /usr/bin/python3                                  
import sys                                           
import time                                          
                                                     
f = None                                             
try:                                                 
    f = open('poem.txt')                             
    while True:                                      
        line = f.readline()                          
        if len(line) == 0:                           
            break                                    
        print(line,end='')                           
        sys.stdout.flush()                           
        print('Press ctrl+c now')                    
        time.sleep(2)                                
except IOError:                                      
    print('Could not find file poem.txt')            
except KeyboardInterrupt:                            
    print('You cancelled the reading from the file.')
finally:                                             
    if f:                                            
        f.close()                                    
    print('Closed the file.')                        

关闭文件操作交给with...open来完成

with open("poem.txt") as f:
    for line in f:
        print(line, end='')

十、其他

列表推导

从一份现有的列表得到新的列表

listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print(listtwo)

断言

当断言失败就会抛出AssertionError

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

转载于:https://www.cnblogs.com/Shadowplay/p/8416440.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值