Python 基础

2019-11-30  本文已影响0人  李霖弢

简介

Python是强类型(不允许隐式转换)、动态类型语言(在执行时才检查变量类型,允许变量重新赋值为其他类型、为对象自定义添加属性)。

基础语法

# print absolute value of an integer:
a = 100
if a >= 0:
    print(a)
else:
    print(-a)
total = item_one + \
        item_two + \
        item_three

在 [], {}, 或 () 中的多行语句,不需要使用\,例如:

total = ['item_one', 'item_two', 'item_three',
        'item_four', 'item_five']
a=10
a,b,c=20,a+5,100
print(a,b,c)#20 15 100
d,e,f=(1,2,3)
print(d,e,f)#1 2 3

数据类型

>>> print('''Line1
Line2
Line3''')

等价于

'Line 1\nLine 2\nLine 3'
判别数据类型
isinstance(100, (int, float))#true
type(10)#<class 'int'>

输出 print

每次 print 输出默认是换行的,如果要实现不换行需要在变量末尾加上 end="":

print( 'a', end=" " )
print( 'b', end=" " )

输入 input

print ("请输入你的名字")
name=input()
print (name)

四种数据结构(容器)

1. 列表list

插入元素
删除元素

2. 元组 tuple

t = (1,)

3. dict 字典

类似js中直接创建的对象,但各种类型都可以作为key,例如

myDict = {threading.current_thread(): 100}
print(myDict[threading.current_thread()])#100

和list相比,dict查找/插入速度快,不会随着key的增加而变慢;但需要占用大量内存。

myDict = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
myDict1 = dict('Michael'=95, 'Bob'=75, 'Tracy'=85)
print(myDict == myDict1 )#True

无法获取key不存在的字典值,可通过in.get()方法进行判断

'tk' in myDict
myDict['Thomas']
myDict.get('Thomas')
myDict.get('Thomas', -1)#设置默认值

4. set 集合

无序且不会有重复元素,只能以intstr等不可变对象作为键

s = set([1, 2, 3])
s = {1,2,3}

比较

==类似js的==
is类似js的===

条件判断

if <条件判断1>:
    <执行1>
elif <条件判断2>:
    <执行2>
else:
    <执行3>
if not 50>100:
    pass

循环

for循环

for item in list:
    pass
for index,item in enumerate(list):
    pass
>>>list(enumerate(['a','b']))
[(0,'a'),(1,'b')]

推导式(列表解析式、字典解析式、集合解析式)

书写方便,且执行效率远远高于通过循环生成列表/字典/集合
注意元组没有解析式,当使用()时会生成generator

l = [i+1 for i in range(1,11) if i<5]
#[2, 3, 4, 5]

d = {i: j.upper() for i, j in zip(range(1, 3), 'abc')}
#{1: 'A', 2: 'B', 3: 'C'}

s = {x * x for x in range(10)}
#{0, 1, 64, 4, 36, 9, 16, 49, 81, 25}
>>>list(zip(range(1, 3), 'abc'))
[(1,''a'),(2,'b'),(3,'c')]

while循环

while <条件语句>:
    pass

break

退出循环

continue

提前结束本轮循环,直接开始下一轮循环

函数

def 函数名(参数):
  <函数体>
参数

对于任意函数,都可以通过类似func(*args, **kw)的形式调用它,无论它的参数是如何定义的。

def calc(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum
calc(1, 2)#5
calc(*[1,2])#5
calc(*(1,2))#5
calc()#0
def person(name, age, **kw):
    return name, age, kw
print(person('Adam', 45, gender='M', job='Engineer'))
print(person('Adam', 45, **{'gender':'M', 'job':'Engineer'}))
#(Adam , 45 , {'gender': 'M', 'job': 'Engineer'})
def person(name, age, *, city, job):
    print(name, age, city, job)
person('Jack', 24, city='Beijing', job='Engineer')
#Jack 24 Beijing Engineer
def f1(a, b, c=0, *args, **kw):
    print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
f1('aa','bb','cc','dd',args1=1,args2=2)
#a = aa b = bb c = cc args = ('dd',) kw = {'args1': 1, 'args2': 2}
上一篇 下一篇

猜你喜欢

热点阅读