2019-12-11(if)
>>> ##条件判断 ... >>> ##应用题:小姐姐买水果,合计金额为32.5,水果店搞活动,男30打九折,小姐姐的实际话费? ... >>> 超过50元,打八折 File "<stdin>", line 1 超过50元,打八折 ^ SyntaxError: invalid syntax >>> >>> total_cost =32.5 >>> if total_cost > 50: ... discoute = 0.8 ... elif total_cost > 30: ... discount =0.9 ... else: ... discount =1 ... >>> total_cost *= discount >>> print("总花费为{}元".format(total_cost)) 总花费为29.25元 >>> >>> >>> ##if ... KeyboardInterrupt >>> ##if 重点 ... >>> ###1、条件判断可以任意组合 ... ##第一层意思:elif可以有0到任意多个,else可有可无 ... ##第二层意思:条件判断可以进行嵌套 ... ###2、着重来看一下condition ... >>> ###从理解的角度来讲,一个值被当成布尔值,概念上更像是有与没有的区别。 ... >>> >>> >>> ##and or not ... >>> ##布尔型变量做运算 ... >>> a= true Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'true' is not defined >>> a= True >>> b = False >>> >>> a='hello world' >>> b=[123] >>> c=[] >>> print('a abd b is {}'.format(a and b)) a abd b is [123] >>> print('a or b is {}'.format(a or b)) a or b is hello world >>> >>> print(bool(a)) True >>> print(bool(b)) True >>> print(bool(c)) False >>> >>> ##分析:两个都是真,返回的是最后的数值,or,一个为真,就在直接返回真的值
2019-12-12 (assert,循环,函数)
assert
>>> ##条件判断的近亲-断言(assert) ... >>> ##它的意思是就是说:我断言他肯定是这样的,如果不是这样,那我就崩溃 ... >>> age =19 >>> assert age >>> assert age ==10 Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError >>> assert age ==10,'他居然不是18岁' Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError: 他居然不是18岁 >>> >>>
##循环
>>> ##循环 ... ## for循环 --遍历循环 ... ##while 循环 --条件 ... >>> >>> cost=[3,4,12,23,43,100] >>> for cost in costs: ... print('消费 {} 元'.fornat(str(cost).center(10))) ... Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'costs' is not defined >>> >>> costs=[3,4,12,23,43,100] >>> for cost in costs: ... print('消费 {} 元'.fornat(str(cost).center(10))) ... Traceback (most recent call last): File "<stdin>", line 2, in <module> AttributeError: 'str' object has no attribute 'fornat' >>> for cost in costs: ... print('消费 {} 元'.format(str(cost).center(10))) ... 消费 3 元 消费 4 元 消费 12 元 消费 23 元 消费 43 元 消费 100 元 >>> >>> ###生成一个长度为20的随机列表 ... >>> import random >>> random_numbers = [] >>> while len(random_numbers) <20: ... random_numbers.append(random.randint(1,10)) ... >>> print(random_numbers,len(random_numbers)) ([1, 6, 10, 4, 5, 4, 2, 9, 5, 3, 6, 8, 7, 4, 1, 8, 6, 6, 7, 6], 20) >>> >>> >>> ##编程建议:就是只要能使用for循环,就不要使用while循环。 ... >>> ###因为while可能会出现死循环 ... >>> ##什么时候必须用while循环:当循环的条件跟数量没有关系时,只能while ... ##题目:往空列表中添加随机数,知道添加的数为9,则终止 ... >>> random_numbers = [] >>> while (9 not in random_numbers): ... random_numbers.append(random.randint(1,10)) ... >>> print(random_numbers,len(random_numbers)) ([7, 6, 9], 3) >>> >>> >>> print(random_numbers,len(random_numbers)) ([7, 6, 9], 3) >>> >>> >>> ##问题:a=[1,2,3],b=1,c=(b in a),大家猜测一下,c是一个什么类型,它是不是一个元祖呢? ... >>> a=[] >>> b=() >>> type(a),type(b),b (<type 'list'>, <type 'tuple'>, ()) >>> a=[123] >>> b=(123) >>> type(a),type(b),b (<type 'list'>, <type 'int'>, 123) >>> >>> ##答案:不是元祖,只有一个元素的列表,需要表现元祖,需要在单元素后面加"," ... >>> b=(123,) >>> type(a),type(b),b (<type 'list'>, <type 'tuple'>, (123,)) >>> >>> >>> >>> ##continue 跳过 ... >>> ##break 跳出循环 ... >>> ##循环加else:如果在循环过程中没有碰到break语句,就会执行else里的代码 >>> ab=[4,2,4] >>> for number in ab: ... if number %2 == 0: ... print('{} is 偶数'.format(number)) ... else: ... break ... print('继续') ... else: ... print('all') ... 4 is 偶数 继续 2 is 偶数 继续 4 is 偶数 继续 all >>> >>> >>> >>> ##for循环可以构建推导式 ... #所谓的推导式,就是一种从一个数据序列构建另外一个数据序列的方法 ... >>> random_number=list(range(10)) >>> random_number [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> new_number=[number*10 for number in random_number] >>> new_number [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] >>> >>> >>> ##上面的是列表推导式 ... ##下面的是字典推导式 ... >>> dict_numbers = {number: 'A' for number in random_numbers} >>> dict_numbers {9: 'A', 6: 'A', 7: 'A'} >>> >>> >>> ##元祖推导式--生成器 ... >>> tuple_numbers= (number*10 for number in random_number) >>> tuple_numbers <generator object <genexpr> at 0x7fcfc576bfa0> >>> ##这个就是生成器 ... >>> tuple(tuple_numbers) (0, 10, 20, 30, 40, 50, 60, 70, 80, 90) >>> >>> >>> >>> >>>
##函数
>>> ##函数 ... >>> varibal = { ... 'a': 100, ... 'b': 100, ... 'c': 200 ... } >>> ##问题:怎么输出value值为100的所有key? ... >>> varibal.items() [('a', 100), ('c', 200), ('b', 100)] >>> [key for key, value in varibal.items() if value == 100 ] ['a', 'b'] >>> >>> >>> ##问题:如果类的计算很多,单单的复制,粘贴是体力活,所以要用到函数 ... >>> def get_keys(dict_varibal,value): ... return [k for k,v in dict_varibal.items() if v == value ] ... >>> get_keys(varibal,200) ['c'] >>> >>> get_keys(varibal,100) ['a', 'b'] >>> >>> >>> ##函数时组织好的,可重复使用的,能够完成特定功能的代码块,它是代码块的抽象。 ... #get_keys 函数名 ... #() 中为参数;dict_varibal:形参,调用的时候传递的值才是实参 ... #return 是返回值 ... #1、位置参数(不可以改变位置) ... #2、关键字参数,可以不按照顺序去写 ... >>> get_keys(dict_varibal={'a':40},value=40) ['a'] >>> >>> get_keys(value=40,dict_varibal={'a':40}) ['a'] >>> >>> >>> >>> ##问题:函数通过参数获取我们传递的值,函数中改变了参数的值,那么我们传递进去的值会改变吗? ... >>> ##分为两类,如果传入的值是不可变的,就不可变,如果传入的值是可变的,就会变 ... ##不建议对可变类型的函数内进行更改,建议用函数返回值进行重新赋值 ... >>> #不可变 ... >>> def test(varibal): ... varibal =100 ... return varibal ... >>> var=1 >>> test(var) 100 >>> print(var) 1 >>> >>> #可变 ... >>> def test(varibal): ... varibal.append(100) ... return varibal ... >>> test(var) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in test AttributeError: 'int' object has no attribute 'append' >>> >>> >>> ##上面的提示就是不可变,不可添加 ... ##重新定义var >>> var=[] >>> test(var) [100] >>> >>> print(var) [100] >>> >>> >>> ##为什么说建议对可变类型的函数内进行更改,建议用函数返回值进行重新赋值呢? ... ##因为这样可以确保,你传出的变量是已经赋值了的,不会因为是不可变类型导致输出的结果有问题,排错难 ... >>> >>> ##参数的收集 ... >>> def test(name,age,*args,**kwargs): ... print(name,age,*args,**kwargs) File "<stdin>", line 2 print(name,age,*args,**kwargs) ^ SyntaxError: invalid syntax >>> >>> >>> def test(name, age, *args, **kwargs): ... print(name, age, *args, **kwargs) File "<stdin>", line 2 print(name, age, *args, **kwargs) ^ SyntaxError: invalid syntax >>> def test(name, age, *args, **kwargs): ... print(name, age, args, **kwargs) File "<stdin>", line 2 print(name, age, args, **kwargs) ^ SyntaxError: invalid syntax >>> def test(name, age, *args, **kwargs): ... print(name, age, args, kwargs) ... >>> test('wong',123,34,'fkdf') ('wong', 123, (34, 'fkdf'), {}) >>> >>> def test(name, age, *args, **kwargs): ... print(name, age, *args, **kwargs) File "<stdin>", line 2 print(name, age, *args, **kwargs) ^ SyntaxError: invalid syntax >>> print(*) File "<stdin>", line 1 print(*) ^ SyntaxError: invalid syntax >>> print(args*) File "<stdin>", line 1 print(args*) ^ SyntaxError: invalid syntax >>> >>> ##问题:print中的*号老是报错
2019-12-16
##装饰器
>>> ##装饰器 ... #可以把函数赋值给一个变量 ... >>> a [123] >>> b (123,) >>> def test(): ... print('test') ... >>> c=test >>> c <function test at 0x7fcfc5779e60> >>> c.__name__ 'test' >>> def test(): ... print('test123') ... >>> c.__name__ 'test' >>> >>> c <function test at 0x7fcfc5779e60> >>> >>> >>> >>> >>> def test(func): ... return func ... >>> def func(): ... print('func run') ... >>> test(func) <function func at 0x7fcfc5779f50> >>> f=test(func) >>> f.__name__ 'func' >>> >>> f.__name__() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object is not callable >>> func() func run >>> >>> f() func run >>> >>> >>> >>> f <function func at 0x7fcfc5779f50> >>> >>> ##python另一个语法糖,装饰器 ... >>> #返回一个从0到1的浮点值 ... >>> @decorator ... def test(): ... return random.random() ... Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'decorator' is not defined >>> >>> @decorator ... File "<stdin>", line 2 ^ SyntaxError: invalid syntax >>> >>> >>>
##类
>>> ##类 ... >>> class Person: ... def __init__(self,name,age): ... self._name = name ... self._age = age ... def get_name(self): ... return self._name ... >>> p = Person('wong',12) >>> p.get_name() 'wong' >>> >>> p_2 = Person('li',11) >>> p_2.get_name <bound method Person.get_name of <__main__.Person instance at 0x7fcfc5778710>> >>> p_2.get_name() 'li' >>> >>> ##__init__,表示的是初始化,self指本身 ... >>> >>> ##继承 ... #pass代表着什么都不做,只是占个位置而已 ... >>> class Student(Person): ... def set_score(self,score): ... self._score = score ... def get_score(self): ... return self._score ... >>> p.set_score(100) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: Person instance has no attribute 'set_score' >>> >>> >>> p=Student('liu',23,100) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: __init__() takes exactly 3 arguments (4 given) >>> >>> p=Student('liu',23) >>> >>> s.get_name() Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 's' is not defined >>> p.get_name() 'liu' >>> >>> p.set_score(100) >>> p.get_score() 100 >>> >>> ###初始化函数中,self后面的是数理化对象的属性,加下划线的意思是,代表这个属性是私有的,不应该访问 ... >>> ###如果需要不加(),就可以输出结果,那么需要在def上加上@property,如p.name(),直接换成p.name,需要在对应的def上加@ ... >>> >>> >>> ##分享一下 ... >>> ###baidu--API封装,py文件 ...
#PYTHON第三节
>>> #PYTHON第三节 ... ##推荐一个python数据结构可视化工具:http://www.pythontutor.com/live.html#mode=edit >>> #课表 ... ##|-mysql数据库的基本操作 ... ##|-用python操作数据库 ... ##|-编写python爬虫并保存到数据库 ... >>> >>> ##数据库 ... >>> ##|-mysql数据库,关系型 ... >>> ##|-MariaDB因为mysql在2012年被微软收购,mysql的创始人为了完全的兼容mysql,包括API和命令行,使之能轻松成为mysql的代替品 ... >>> #关系型数据库 ... ##另外一种类型的数据库是:非关系型数据库,如比较流行的是:Mongadb,redis ... >>> ##非关系型的数据库,其实是以json的格式存储的 ... >>> >>> ##mysql数据库基本操作 ... ##链接数据库 ... >>> ###mysql -uroot -p ... >>> ##查看数据库 ... ###show databases; ... >>> ##选择数据库 ... ###use database_name; ... >>> ##查看数据库中的table表 ... ###show tables; ... >>> ##查看表格的结构 ... ###desc tables; ... >>> ##查看表中的数据 ... ###select * from table_name; ... >>> ##查看数据并限制数量 ... ###select * from table_name limit number; ... >>> >>> ##非关系型数据库 ... >>> import json >>> data_1="{'a':1,'b':2,'c':3}" >>> data_2='{"a":1,"b":2,"c":3}' ###data_1和data_2的不同在于""和''的位置问题,字典的key必须是双引 >>> j_data=json.loads(data_2) >>> type(j_data) <type 'dict'> >>> >>> j_data1=json.loads(data_1) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/root/anaconda2/lib/python2.7/json/__init__.py", line 339, in loads return _default_decoder.decode(s) File "/root/anaconda2/lib/python2.7/json/decoder.py", line 364, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/root/anaconda2/lib/python2.7/json/decoder.py", line 380, in raw_decode obj, end = self.scan_once(s, idx) ValueError: Expecting property name: line 1 column 2 (char 1) >>> >>> >>> ##加载本地json文件 ... >>> with open('/root/data.json',r) as f: ... j_data=json.load(f) ... print(j_data) ...
2019-12-17
##使用python去操作数据库
>>> import MySQLdb
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named MySQLdb
>>> import MySQLdb
>>>
>>> ##上面报错是因为没有安装这个模块:pip install mysql-python
###连接数据库
##python3的写法
>>> db=MySQLdb.connect(host='localhost',user='root',passsword='qweasdzxc',database='taobao')
##python2的写法(主要的区别是db和passwd)
>>> db=MySQLdb.connect(host='localhost',user='root',passwd='qweasdzxc',db='taobao')
>>> #等价于
...
>>> db=MySQLdb.connect('localhost','root','qweasdzxc','taobao')
>>> #等价于
...
>>> DATABASE = {'host':'localhost','db':'taobao','user':'root','passwd':'qweasdzxc','charset':'utf8mb4'}
>>> db=MySQLdb.connect(**DATABASE)
##注意:如果数据库出现了中文,需要定义charset,根据自己的数据库结构来定义
操作数据库(cursor)
>>> ##游标
...
>>> cursor=db.cursor()
>>> sql='select * from tqk_ad;'
>>> cursor.execute(sql)
2L
>>> results=cursor.fetchall()
>>> results
((39L, u'\u624b\u673a', u'http://www.tuiquanke.com/article_view/1987', u'/data/upload/ad/5971438c5f4f5.png', 0L, 255, 1), (37L, u'\u7535\u8111', u'http://www.tuiquanke.com/article_view/1987', u'/data/upload/ad/5971438c5f4f5.png', 0L, 255, 0))
>>>
>>> for row in results:
... print(row)
...
(39L, u'\u624b\u673a', u'http://www.tuiquanke.com/article_view/1987', u'/data/upload/ad/5971438c5f4f5.png', 0L, 255, 1)
(37L, u'\u7535\u8111', u'http://www.tuiquanke.com/article_view/1987', u'/data/upload/ad/5971438c5f4f5.png', 0L, 255, 0)
>>> ##其他更,删,查,等,就sql不同,其他一样,都是用cursor
##使用python去操作数据库
>>> import MySQLdb Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named MySQLdb >>> import MySQLdb >>> >>> ##上面报错是因为没有安装这个模块:pip install mysql-python
###连接数据库
##python3的写法 >>> db=MySQLdb.connect(host='localhost',user='root',passsword='qweasdzxc',database='taobao') ##python2的写法(主要的区别是db和passwd) >>> db=MySQLdb.connect(host='localhost',user='root',passwd='qweasdzxc',db='taobao') >>> #等价于 ... >>> db=MySQLdb.connect('localhost','root','qweasdzxc','taobao') >>> #等价于 ... >>> DATABASE = {'host':'localhost','db':'taobao','user':'root','passwd':'qweasdzxc','charset':'utf8mb4'} >>> db=MySQLdb.connect(**DATABASE) ##注意:如果数据库出现了中文,需要定义charset,根据自己的数据库结构来定义
操作数据库(cursor)
>>> ##游标 ... >>> cursor=db.cursor() >>> sql='select * from tqk_ad;' >>> cursor.execute(sql) 2L >>> results=cursor.fetchall() >>> results ((39L, u'\u624b\u673a', u'http://www.tuiquanke.com/article_view/1987', u'/data/upload/ad/5971438c5f4f5.png', 0L, 255, 1), (37L, u'\u7535\u8111', u'http://www.tuiquanke.com/article_view/1987', u'/data/upload/ad/5971438c5f4f5.png', 0L, 255, 0)) >>> >>> for row in results: ... print(row) ... (39L, u'\u624b\u673a', u'http://www.tuiquanke.com/article_view/1987', u'/data/upload/ad/5971438c5f4f5.png', 0L, 255, 1) (37L, u'\u7535\u8111', u'http://www.tuiquanke.com/article_view/1987', u'/data/upload/ad/5971438c5f4f5.png', 0L, 255, 0) >>> ##其他更,删,查,等,就sql不同,其他一样,都是用cursor
2019-12-18
Comments | NOTHING