美文网首页
python学习(一)基础学习 易忘点

python学习(一)基础学习 易忘点

作者: attentionYSF | 来源:发表于2019-05-30 10:38 被阅读0次

字符转义

  • 使用r'',字符串内容不转义
>>> print('\\\t\\')
\       \
>>> print(r'\\\t\\')
\\\t\\

输出字符串

  • 输出多行字符r''''''
.py文件代码

print('''line1
line2
line3''')
---------
line1
line2
line3 

  • 字符串格式化
print('%2d-%02d' % (3, 1))
print('%.2f' % 3.1415926)

s1 = 72
s2 = 85
r = (s2-s1)/s1*100;
print('%.2f%%' % r);
print('{0}成绩提升了{1:.1f}%'.format('小明', r));
------
18.06%
小明成绩提升了18.1%

基本数据类型

  • boolean运算
True   False
and or not

-空值

None

有序列表 list和tuple

  • list
list = [];
len(list)  -- 长度为0
list.append(1)
list.append('xiaoming')
list.append([4, 5, 6, 1])
list.insert(1, 3)
list.pop()
  • tuple
tuple 类似list,但本身包含的元素不能修改,且没有任何函数,包含的list值允许修改,只包含一个元素必须加逗号
tuple=()
tuple=(1, )
tuple=(1, 2, [1, 2, 3])
print(tuple[2][0]) -- 1

dict 字典(map) 和 set

  • dict
dict = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
dict['c'],key不存在会报KeyError错误信息
dict.get('c', -1) --如果存在,返回正确值;不存在返回自定义的值 -1
dict.get('c') --如果不存在,返回None
dict.pop('c') --删除元素,key不存在会报KeyError错误信息

判断key是否在dict中: 'c' in dict  --False

-set 和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。

要创建一个set,需要提供一个list作为输入集合:

set = set([1, 2, 3, 4])
set.add(5)
set.remove(1)

set2 = set([3, 4, 6])

set & set2   --([3, 4])交集
set | set2    --([1, 2, 3, 4, 6])并集

条件判断 if elif else

age = input('请输入你的年龄:')
age = int(age)
if age >= 6:
    print('teenager')
elif age >= 18:
    print('adult')
else:
    print('kid')

循环

跳出循环 break;
进入下一轮循环,跳过后续代码 continue

  • 计算0到100相加之和
sum = 0
for x in range(101):
    sum = sum + x
print(sum)
  • 计算0到100内奇数之和
sum = 0
x = 99
while x > 0 :
    sum += x
    x -= 2
print(sum)  

函数

  • 内置函数 调用
abs(-12.34)  --12.34
max([1, 3, 6])   --6
min()
list()
range(5)  --[0, 1, 2, 3, 4]
hex  --十进制整数十六进制
-------类型转换函数
int()
str()
bool()
    bool(None)  bool() bool(0)  --False
    bool(1)  bool(-1) bool('aa') bool('True') bool('False')    --True

x=22
isinstance(x, (int, float))   --True
  • 函数定义

类似javascript函数,可以返回任何数据类型,默认返回None

---- 函数声明格式
def getSum(x, y, z=0):
    return x + y + z
---- 空函数
def getSum(x, y, z):
    pass
---- 空代码体
if x > 0:
    pass
  • 参数检查
def getSum(x, y):
    if not isinstance(x, (int, float)):
        raise TypeError('bad oprand type')
  • 函数返回多值tuple
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math

def move(x, y, step, angle=0):
    nx = x + step*math.cos(angle)
    ny = y + step*math.sin(angle)
    return nx, ny, angle

print(move(2, 3, 4)) -- (6.0, 3.0, 0)
  • 函数默认参数

有默认参数,调用函数时默认参数可以不传

def def_default(x, y, country='shenzhen', address='china'):
    pass

-------调用方式
def_default(1, 2)
def_default(1, 2, address='hanchuan')
def_default(1, 2, 'hanchuan')

-------陷井
def add_end(L=[]):
    L.append('END')
    return L
add_end()  --第一次调用 输出:['end']
add_end()  --第二次调用 输出:['end', 'end']

原因:
python函数在定义的时候,默认参数L的值就被计算出来了,即[],因为默认参数L也是一个变量,它指向对象[],每次调用该函数,如果改变了L的内容,则下次调用时,默认参数的内容就变了,不再是函数定义时的[]了

**定义默认参数要牢记一点:默认参数必须指向不变对象!**

解决办法:
def add_end(L=None):
    if L is None:
        L = []
    L.append('END')
    return L
  • 函数参数
------可变参数
def def_case(*args)  --*args,args接收的是一个tuple

nums = [1, 2, 3]
def_case(nums)  --([1, 2, 3],)

def_case(*nums)  --(1, 2, 3),*nums将list集合变为了可变参数

-------关键字参数
def person(name, age, **kw):   --**kw, kw接收的是一个dict
    print('name:', name, 'age:', age, 'other:', kw)

-------命名关键字参数
必须以*当作分隔符,city,job为键名,必须传入,否则会报错
def person(name, age, *, city, job):
    print(name, age, city, job)

相关文章

网友评论

      本文标题:python学习(一)基础学习 易忘点

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