1 Star 0 Fork 0

dingnate / python.demo

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README

python入门教程

python 第一课

python之禅

import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

计算器

5+100
105
100/10
10.0
# round函数确定保留小数位数
print(round(10/3,3))
# //除取整-python3.x,/除取整python-2.x
print(10//3)
3.333
3
100*10
1000
100-99
1
10%3
1

应用题

小姐姐去买水果。苹果5元一斤,葡萄15元一斤,小姐姐买了2斤苹果,1.5斤葡萄,请问一共要多少钱?
2*5+15*1.5
32.5

使用变量

apple_price = 5
apple_weight =2
apple_cost=apple_price * apple_weight

grape_price=15
grape_weight=1.5
grape_cost= grape_price*grape_weight

total_cost = apple_cost + grape_cost
print(total_cost)
32.5

增强的格式化字符串函数format

# -*- coding: utf-8 -*-
"苹果的花费:{};葡萄的花费:{};总花费:{}".format(apple_cost,grape_cost,total_cost)
'苹果的花费:10;葡萄的花费:22.5;总花费:32.5'

语法糖

# 交换两个变量,不需要中间变量
a=10
b=20
a,b = b,a
print("a is {},b is {}".format(a,b))
a is 20,b is 10

命名规范

  1. 标识符名称的第一个字符必须时大小字母或者一个下划线('_')
  2. 标识符名称的第一个字符必须时大小字母、一个下划线('_')或者数字(0-9)
  3. 标识符名称是大小写敏感的
n=10
N=10
n_1000=1000
# 首字母为数字
# 3thidnf=10
# 有空格
#my name =100
# -是非法字符
#my-name =10

代码规范建议

  1. 不要使用单字符
  2. 变量名能清晰的表达变量的意思
  3. 合理使用字母之间的下划线

变量类型

  1. 字符 str
  2. 数字 int float complex
  3. 列表 list
  4. 元祖 tuple
  5. 字典 dict

数值类型

number = 10
number = number + 10
number += 10
number -= 10
number *= 10
number /= 10
# 乘方,开方
#方法1 推荐使用
print(10**3)
print(10**(1/3))
#方法2
import math
print(math.pow(10,3))
print(math.pow(10,1/3))
1000
2.154434690031884
1000.0
2.154434690031884
# pi值
print(math.pi)
# sin函数
print(math.sin(math.pi/2))
3.141592653589793
1.0
# 向下取整
math.floor(math.pi)
3
# 向上取整
math.ceil(math.pi)
4
# 角的转换
math.radians(180)
3.141592653589793
#最小值函数
min(10,12,234,100,1)
1
#最大值函数
max(10,12,234,100,1)
234
# 求和函数
# 参数类型是列表
print(sum((10,12,234,100,1)))
# 参数类型是元祖
print(sum([10,12,234,100,1]))
# 参数类型必须是可迭代类型
#print(sum(1,2))
357
357
# 除的时候,同时获取商和余数
divmod(10,3)
(3, 1)

bool类型

True,False
(True, False)
True == 1
True
False == 0
True
True + 0
1
False + 0
0
100 > 10
True

bool类型:与、或、非

# 同为真,则真
True and False
False
# 任一为真,则真
True or False
True
# 非运算,取反
not True
False
操作符 解释
< 小于
<= 小于等于
> 大于
>= 大于等于
== 等于
!= 不等于
is 是相同对象

动态类型变量

# 变量的类型由程序运行过程中变量所代表的值的类型确定
var = 10
print(type(var))
var = 'str'
print(type(var))
<class 'int'>
<class 'str'>

字符串(string)

# 字符串可以使用双引号,也可以使用双引号,通过单双引号的恰当使用,可以避免不必要的字符转义(escape)
hello = "hello world"
hello = "hello world\""
hello = 'hello \'world'
hello
"hello 'world"
# 字符串'+'操作
line1 = "nihao, "
line2 = 'xiaojiejie'
line1+line2
'nihao, xiaojiejie'
# 字符串'*'操作
line = 'nihao '
line * 10
'nihao nihao nihao nihao nihao nihao nihao nihao nihao nihao '
# id函数字符串地址
# 所有的字符串函数都为我们生成一个新的字符串,原有字符串不变
line = 'nihao '
line_copy = line
id(line), id(line_copy)
(131578688, 131578688)
len(line)
6

字符串切片(string slice)

line = 'huan ying da jia lai wan men shang ke'
# 取前十个字符
line[:10]
'huan ying '
# 每两个字符取一个
line[::2]
'ha igd i a a e hn e'
# 取后上个字符
line[-10:]
'n shang ke'
# 反转字符
line[::-1]
'ek gnahs nem naw ial aij ad gniy nauh'
# 单个字符
line[-1]
'e'
# 字符串不可修改
#line[-1]='g'
# capitalize 首字母大写,其它字面小写
print(line.capitalize())
line = "ABCDEF" 
print(line.capitalize())
Huan ying da jia lai wan men shang ke
Abcdef
# center 居中函数,默认填充字符是空格
print(line.center(20))
print(line.center(20,'*'))
       ABCDEF       
*******ABCDEF*******
# count 计数函数
line.count('A')
1
# endswith 结尾判断
line.endswith('EF')
True
# startswith 头部判断
line.startswith("ABE")
False
# find 字符查找
print(line.find('Z'))
print(line.find('BC'))
-1
1
# index 查找,与find函数区别:不存在报错
#line.index('Z')
# 字符串大小写转换
line = 'ABCdefGHIGK'
print(line.upper())
print(line.isupper(),line.upper().isupper())
print(line.lower())
print(line.islower(),line.lower().islower())
print(line.swapcase())# 大小写反转
ABCDEFGHIGK
False True
abcdefghigk
False True
abcDEFghigk
# istitle 与capitalize对应,判断是否是capitalize处理之后的字符
line = 'Abcde'
print(line.istitle())
line = 'AbcdeF'
print(line.istitle())
True
False
# strip 去除两端空白字符
line = '    intresting  \n\r  '
print(line.strip())
print(line.rstrip())#去除右端空白字符
print(line.lstrip())#去除左端空白字符
intresting
    intresting
intresting  

列表

# 空列表
variables = []
variables = list()
# 列表是可以容纳任意类型,任意数量对象的可变类型
variables = [1,2,3,'nihao','hello, python',[],[100,100]]
# append函数
variables = []
variables.append(1)
variables.append(2)
variables.append('nihao')
variables
[1, 2, 'nihao']
# 修改列表
variables[0] = 10
variables[-1] = 'wohao'
variables
[10, 2, 'wohao']

列表切片

variables[-2:]
[2, 'wohao']
variables+[1,23]
[10, 2, 'wohao', 1, 23]
variables*4
[10, 2, 'wohao', 10, 2, 'wohao', 10, 2, 'wohao', 10, 2, 'wohao']

序列

1. 列表是容器型序列
2. 字符串是扁平行序列
# 长度
len(variables)
3
# 没有返回值,修改了列表对象本身
variables.append(1)
variables
[10, 2, 'wohao', 1]
# 清空
variables.clear()
variables
[]
variables = [1,12,23,4234]
variables_1 = variables # 浅复制(复制地址)  variables_1 修改时variables会一起变化
variables_1[-1]=8888
new_variables = variables.copy() #深复制(复制对象)new_variables 修改时variables不会一起变化
print(variables ,variables_1,new_variables)
# 修改新的列表时旧的列表是不变的
new_variables[0]=9999
print(variables ,variables_1,new_variables)
print('variables id is {}'.format(id(variables)))
print('variables_1 id is {}, new_variables id is {}'.format(id(variables_1),id(new_variables)))
print('variables[-1] id is {}'.format(id(variables[-1])))
print('variables_1[-1] id is {}, new_variables[-1] id is {}'.format(id(variables_1[-1]),id(new_variables[-1])))
[1, 12, 23, 8888] [1, 12, 23, 8888] [1, 12, 23, 8888]
[1, 12, 23, 8888] [1, 12, 23, 8888] [9999, 12, 23, 8888]
variables id is 128521640
variables_1 id is 128521640, new_variables id is 129033680
variables[-1] id is 129194192
variables_1[-1] id is 129194192, new_variables[-1] id is 129194192
a = [1, 2]
b = [3, 4]
print(a + b)
# 扩展
a.extend(b)
a
[1, 2, 3, 4]





[1, 2, 3, 4]
# 插入函数
a.insert(0,100)
a
[100, 1, 2, 3, 4]
# 弹出尾部元素
print(a.pop())
a
4





[100, 1, 2, 3]
a=[1,2,3,4,3]
a.remove(3)# 移除第一个匹配的元素
print(a)
#a.remove('Z')#移除不存在的元素会报错
[1, 2, 4, 3]
#反转列表顺序
a.sort(reverse=True)
a
[4, 3, 2, 1]
# 列表是否包含元素的判断
4 in a,5 in a
(True, False)

元组(tuple)

# 空元组 是一种不可变类型的列表
var = tuple()
var = ()
type(var)
tuple
var = (1,2,1,3,4,5,(23,34,43))
var.count(1)
2
var.index(5)
5
a =10,20
type(a)
tuple
a =10,20
print(type(a))
a
<class 'tuple'>





(10, 20)

字典类型(dict)

# 空字典
var = dict()
var = {}
type(var)
dict
var = {
    '中': 100,
    '左': 200
}
var['中']
100
words = ['中','左']
locations=[100, 200]
locations[words.index('中')]
100

拉锁函数(zip)

var_new = list(zip(words,locations))
print(var_new)
print(dict(var_new))
[('中', 100), ('左', 200)]
{'中': 100, '左': 200}
list(zip([1,2],[3,4],[5,6]))
[(1, 3, 5), (2, 4, 6)]
students = ['wang','li','sun','zhao','qian']
money = dict.fromkeys(students,10)#通过keys生成字典,每个元素给一个初始化的值
money
{'wang': 10, 'li': 10, 'sun': 10, 'zhao': 10, 'qian': 10}
money['wang'],money.get('li')
(10, 10)
# get 获取不到可以给默认值
money.get('wan'),money.get('wan',10)
(None, 10)
money.keys()
dict_keys(['wang', 'li', 'sun', 'zhao', 'qian'])
money.values()
dict_values([10, 10, 10, 10, 10])
money.items()
dict_items([('wang', 10), ('li', 10), ('sun', 10), ('zhao', 10), ('qian', 10)])
print(money.pop('wang'))#弹出元素
print(money)
10
{'li': 10, 'sun': 10, 'zhao': 10, 'qian': 10}
money.setdefault('haha',1000)#设置元素默认值
money
{'li': 10, 'sun': 10, 'zhao': 10, 'qian': 10, 'haha': 1000}

python第二课

课程内容

  1. 条件判断
  2. 循环
  3. 函数

条件判断

if condition:
    do something
elif condition:
    do something
else:
    do something

注:

  1. if块只能为1个,elif块可有0或*个,else块可有0或1个
  2. condition为bool值,python中任意值都可以用作bool值,此时的bool值代表的是有和没有的概念

应用题

小姐姐买水果,合计金额32.5元,水果店搞活动,满30打九折,满50打8折,告诉小姐姐的实际花费
total_cost = 32.5
if total_cost >=50:
    discount = 0.8
elif total_cost>=30:
    discount = 0.9
else:
    discount = 1

total_cost *= discount
'小姐姐的实际花费为{}元'.format(total_cost)      
'小姐姐的实际花费为29.25元'
bool(''),bool(()),bool([])
(False, False, False)
condition = ''
if condition:
    print('True')
else:
    print('False')    
False

bool类型变量的逻辑运算

a = True
b = False
print('a and b is',(a and b))
print('a or b is',(a or b))
a and b is False
a or b is True

非bool类型变量的逻辑运算

# 判断非bool类型变量是,非空为True,空为False
a = 'hello world'
b = [1,2,3]
print('a and b is',(a and b))
print('a or b is',(a or b))
print(not b)
a and b is [1, 2, 3]
a or b is hello world
False

assert:断言--条件判断的近亲

# 用法:assert condtion,prompt,一般在调试程序的时候使用

# 我断言肯定是这样的,如果不是,我就崩溃
if not condition:
    crash program
age = 18
# age = 19

assert age == 18,'他竟然不是18岁'

循环

for循环   -- 遍历循环--能用for循环,尽量不用while循环
while循环 -- 条件循环--当循环跟数字没有关系的时候用while循环
costs = [3,4,12,23,43,100]
for cost in costs:
    cost = str(cost)#转换为字符串类型
    cost = cost.center(10)#居中填充10个字符
    print('消费{}元'.format(cost))#格式化输出
    #print('消费{}元'.format(str(cost).center(10)))
消费    3     元
消费    4     元
消费    12    元
消费    23    元
消费    43    元
消费   100    元

题目:生成一个长度为20的随机列表

import random
random_numbers=[]
# while循环
while(len(random_numbers)<20):
    random_numbers.append(random.randint(1,10))
random_numbers
[1, 6, 9, 3, 9, 9, 9, 9, 3, 10, 6, 9, 2, 5, 3, 1, 8, 10, 7, 5]
random_numbers=[]
# for循环
for i in range(20):
    random_numbers.append(random.randint(1,10))
random_numbers
[9, 7, 6, 5, 5, 1, 1, 9, 9, 5, 9, 10, 10, 2, 5, 3, 6, 8, 7, 4]

题目:添加随机数直到随机数为9

random_numbers=[]
# while循环
random_numbers.append(random.randint(1,10))
while(random_numbers[-1]!=9):
    random_numbers.append(random.randint(1,10))
random_numbers
[4, 9]
random_numbers=[]
# while循环
while(9 not in random_numbers):
    random_numbers.append(random.randint(1,10))
random_numbers
[4, 4, 4, 2, 8, 10, 9]
# (b in a)的返回类型是bool
a,b,c = [1,2,3],1,(b in a)
c,type(c)
(True, bool)
#a, b= [],()
a = [1]
b = (1)
c = (1,)# 只有一个元素的元祖的声明方法是元素后面跟','
type(a),type(b),b,type(c),c
(list, int, 1, tuple, (1,))
random_numbers = [2,3,5,6,8]
random_numbers
[2, 3, 5, 6, 8]

跳过(continue)

for number in random_numbers:
    if number % 2==0:
        print('{} is 偶数'.format(number))
    else:
        continue
    print('没有结束')
2 is 偶数
没有结束
6 is 偶数
没有结束
8 is 偶数
没有结束

跳出(break)

for number in random_numbers:
    if number % 2==0:
        print('{} is 偶数'.format(number))
    else:
        break
    print('没有结束')
2 is 偶数
没有结束

循环中的else

如果循环中没有遇到break语句,就会执行else里的代码
random_numbers = [4,2,4]
for number in random_numbers:
    if number % 2==0:
        print('{} is 偶数'.format(number))
    else:
        break
    print('没有结束')
else:
    print('都是偶数')
4 is 偶数
没有结束
2 is 偶数
没有结束
4 is 偶数
没有结束
都是偶数

for 循环可以构造推导式

random_numbers = list(range(10))
random_numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 一般用法
new_numbers = []
for number in random_numbers:
    new_numbers.append(number*10)
new_numbers
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

列表推导式

new_numbers = [number*10 for number in random_numbers]
new_numbers
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

字典推导式

dict_numbers={number:'A' for number in random_numbers}
dict_numbers
{0: 'A',
 1: 'A',
 2: 'A',
 3: 'A',
 4: 'A',
 5: 'A',
 6: 'A',
 7: 'A',
 8: 'A',
 9: 'A'}

生成器(迭代器)

一个可迭代的序列
tuple_numbers=(number*10 for number in random_numbers)
tuple_numbers
<generator object <genexpr> at 0x02EF87B0>
tuple(tuple_numbers)
#list(tuple_numbers)
(0, 10, 20, 30, 40, 50, 60, 70, 80, 90)
varibles = {
    'a':100,
    'b':100,
    'c':200
}
varibles['a']
100
[key for key,value in varibles.items() if value==100]
['a', 'b']

函数

函数是组织好的,可重复使用的,能够完成特定功能的代码块,它是代码的抽象。
# 函数定义
def get_keys(dict_variables,val):
    return [key for key,value in dict_variables.items() if value == val]
  • get_keys 函数名称
  • () 中为参数:dict_variables为形参,调用的时候传的值才是实参
  • return 是返回值
  1. 位置参数
  2. 关键字参数,可以不按位置顺序去写
# 位置参数调用
get_keys(varibles,200)
['c']
# 关键字参数调用
get_keys(val=200,dict_variables=varibles)
['c']



问题:函数中通过参数获取外部传递的值,函数中修改了参数的值,那么我们传递进去的值会改变吗?
def test(variable):
    variable = 100
    return variable
# 函数内部值改变,外面的值不改变
var = '1'
test(var),var
(100, '1')
def test(variable):
    variable.append(100)
    return variable
# 函数内部值改变,外面的值改变
var = []
test(var),var
([100], [100])



不建议在函数内对可变类型进行修改,建议用函数返回值进行重新赋值
def test(variable):
    temp = [i for i in variable]
    temp.append(100)
    return temp
var = []
test(var),var
([100], [])

参数的收集

* 收集位置参数
** 收集关键字参数
def test(name,age,*args,**kwargs):
    print(name,age,args,kwargs)
test('wong',12,23,'1k1',[23,34],weight=120)
wong 12 (23, '1k1', [23, 34]) {'weight': 120}
def test(name,age,*args,**kwargs):
    print(name,age,*args,kwargs)
test('wong',12,23,'1k1',[23,34],weight=120)
wong 12 23 1k1 [23, 34] {'weight': 120}
a = 10
b = [12,12]

def func():
    print('func run')
def test(func):
    return func #函数作为返回值  
c = func #可以把函数赋值给一个变量
c()#调用func()

f= test(func);
print(f.__name__)
f()#利用函数返回值作函数调用
func run
func
func run

装饰器

#声明装饰器
def decorator(func):
    def wrapper(*args,**kwargs):
        return round(func(*args,**kwargs),2)
    return wrapper

import random
#使用装饰器
@decorator
def test():
    return random.random()
@decorator
def test_two():
    return random.random()*10
print(test())
print(test_two())
8.51
4.44

pass代表什么都不做的占位符
类属性以_开头标识该属性为私有,外部不可见

property装饰器

# property装饰器--通过属性方式访问方法
class Person:
    pass
    def __init__(self,name):
        self._name = name
    @property
    def name(self):
        return self._name
p = Person('liu')
print(p.name)
#print(p.name())#使用Property装饰器后,原始的调用方法报错
liu

属性设置

class Person:
    def __init__(self,name,age):
        self._name = name
        self._age = age
    def get_name(self):
        return self._name
    def rename(self,new_name):
        self._name = new_name
    def get_age(self):
        return self._age
p = Person('wong',12)
print(p.get_name())
p.rename('wong li')
print(p.get_name())
print(p.get_age())
wong
wong li
12

继承

class Student(Person):
    """docstring for Student"""
    def __init__(self, name,age,score):
        # 调用父类初始化方法的两种方式
        # super(Student, self).__init__(name,age) #1
        Person.__init__(self,name,age)#2
        self._score = score
    def get_score(self):
        return self._score
    def to_string(self):
        return "name={},age={},score={}".format(self.get_name(),self.get_age(),self.get_score())
s = Student('liu',24,100)
print(s.to_string())
name=liu,age=24,score=100

空文件

简介

python入门教程,基本使用demo 展开 收起
Python
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Python
1
https://gitee.com/dingnate/python.demo.git
git@gitee.com:dingnate/python.demo.git
dingnate
python.demo
python.demo
master

搜索帮助