1 条件循环和其它语句

1.1 print import

使用逗号输出

print('age',42)
Out[1]:age 42

1.2 赋值魔法

多个变量同时赋值

x,y,z = 1,2,3
print(x,y,z)

values = 1,2,3
values
Out[1]: (1, 2, 3)

x,y,z = values
x
Out[3]: 1

链式赋值

x = y = somefunction()

增量赋值

x = 2
x +=1
x *=1
x
Out[4]: 3
#其它类型
t = 'a'
t += 'b'
t *= 2
t
Out[5]: 'abab'

1.3 条件和条件语句

除了
False None 0 ‘’ () [] {}
其它都是True。所有的值都可以被看作布尔值

比较运算符

x == y
x != y
x <= y
x is y      同一个对象
x is not y
x in y
x not in y

布尔运算符 多个条件
两个条件时,用and,or,not

num = 1
if num <=10 and num>=1:
    print('great')
else:
    print('wrong')

#更简单的方法
1<=num <=10

while循环

x = 1
while x<=100:
    print(x)
    x +=1

循环遍历字典

d = { 'x':1,'y':2}
for k in d:
    print(k,'to ',d[k])
Out[26]:
x to  1
y to  2

迭代工具
1.并行迭代

names = ['any','bel','baby']
age = [21,33,11]

for i,j in zip(names,age):
    print(i,j)
    
any 21
bel 33
baby 11

索引迭代

names = ['any','bel','baby']
for index,string in enumerate(names):
   # print(index,string)
    if 'a' in string:
        names[index] = 'A'
names
Out[37]: ['A', 'bel', 'A']

跳出循环
break
continue

列表推倒式 轻量级循环 非常方便
小型循环,结果生成列表,速度较快

[x*x for xbngm in range(10) if x%3==0]
[(x,y) for x in range(3) for y in range(3)]

2 抽象

2.1 函数参数

关键词参数、位置参数、默认参数

def hello(name,male,greeting='hello'):
    print('%s,%s%s')%(greeting,name,male)

收集参数一个星*
收集其余位置的参数,如果不提供任何供收集的元素,就是个空元组

def print_params(title,*params):
    print(title)
    print(params)

print_params('title',1,2,3)
Out[6]:
title
(1, 2, 3)

收集参数 对于关键词参数两个星**

def print_params(x,y,z=3,*params,**params2):
    print(x,y,z)
    print(params)
    print(params2)
print_params(1,2,3,4,5,6,fool = 'a',hasha = 'love')
Out[6]:
1 2 3
(4, 5, 6)
{ 'fool': 'a', 'hasha': 'love'}

参数练习

#定义三个函数
def story(**kwds):
    return 'once upon a time,there was s ','%(job)s called%(name)s'%kwds

def power(x,y,*others):
    if others:
        print('Received redundant parameters',others)
    return pow(x,y)

def interval(start,stop = None,step = 1):
    'imitages range() for step>0'
    if stop is None:
        start ,stop = 0,start
    result = []
    i = start
    while i<stop:
        result.append(i)
        i +=step
    return result
 #看一下结果
print(story(job='king',name = 'amy'))
('once upon a time,there was s ', 'king calledamy')

print(story(name = 'amy',job='king'))
('once upon a time,there was s ', 'king calledamy')

params = { 'job':'doctor','name':'amy'}
print(story(**params))
('once upon a time,there was s ', 'doctor calledamy')

del params['job']
print(story(job='language',**params))
('once upon a time,there was s ', 'language calledamy')

power(2,3)
Out[30]: 8

power(3,2)
Out[31]: 9

params = (5,)*2
power(*params)
Out[33]: 3125

power(3,3,'hello world')
Received redundant parameters ('hello world',)
Out[34]: 27

interval(10)
Out[35]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

interval(1,5)
Out[36]: [1, 2, 3, 4]

interval(3,12,4)
Out[37]: [3, 7, 11]

power(*interval(3,7))#interval(3,7)的结果是(3,4,5,6),前两个(3,4)是位置参数x,y,后面(5,6)是可变参数
Received redundant parameters (5, 6)
Out[38]: 81                           

2.2作用域

一个函数位于另一个函数里面,外层函数返回里层函数。也就是函数本身被返回了,但没有被调用。

def multiplier(factor):
    def multiplyByFactor(number):
        return number*factor
    return multiplyByFactor

double = multiplier(2)
double(5)
Out[6]: 10

multiplier(2)(6)
Out[7]: 12

2.3递归

函数可以调用自身,也就是引用自身的意思。一般应包含:

  • 当函数直接返回值时,有基本实例(最小可能性问题)
  • 递归实例,包括一个或者多个问题较小部分的递归调用

阶乘,计算阶乘,n(n-1)*…1

''原始函数'''
def factorial(n):
    result = n
    for i in range(1,n):
        result *=i
    return result

factorial(8)
Out[8]: 40320

改编:

  • 1的阶乘是1
  • 大于的数n的阶乘 = n乘以n-1的阶乘
def factorial(n):
    if n==1:
        return 1
    else:
        return n*factorial(n-1)

factorial(5)
Out[11]: 120

:**幂,计算n个x相乘

''原始函数'''
def factorial(x,n):
    result = 1
    for i in range(n):
        result *=x
    return result

factorial(8,2)
Out[12]: 64

改编:

  • 对于任意x,n为0时幂为1
  • 对于大于1的n的幂= x乘以factorial(x,n-1)
def factorial(x,n):
    if n==0:
        return 1
    else:
        return x*factorial(x,n-1)

factorial(5,2)
Out[13]: 25

3更加抽象

3.1对象的魔力

多态:多态意味着就算不知道变量所引用的对象类型是什么,还是能对它进行操作,而它也会根据对象类型的不同而表现出不同的行为。

def lent(x):
    print('the length of ',repr(x),'is',len(x))

lent('love')
the length of  'love' is 4

lent([1,2])
the length of  [1, 2] is 2

3.2类

类就是一种对象,所有的对象都属于某一个类,对象称为类的实例。
self的用法:

class person():
    
    def setname(self,name):
        self.name = name
    
    def getname(self):
        return self.name
    
    def greet(self):
        print("hello ,I am %s"%self.name)

foo = person()
bar = person()
foo.setname('luke')
bar.setname('ana')

foo.greet()
Out[11]:hello ,I am luke

bar.greet()
Out[11]:hello ,I am ana

指定超类
将其它类名class语句后面的圆括号内可以指定超类
首先定义 class filter()
在定义SPAMfilter的时候:class SPAMfilter(filter),则定义了SPAMfilter是filter的子类

检查继承
issubclass(子类,基类) 检查是否是子类

多个超类
如果有多个超类的话,就可以集合其重多超类的特点(子类继承超类),有时候会非常方便。

class Calculator():
    def calculator(self,expression):
        self.value = eval(expression)
        
class Talker():
    def talker():
        print('hi,my value is',self.value)

class Talker_Calculator(Calculator,Talker):
    pass

tc = Talker_Calculator()
tc.calculator('1+2*3')
tc.talker()

本文地址:https://blog.csdn.net/qq_42871249/article/details/110498585