从Zero到Hero,一文掌握Python关键代码
# 01基础篇
# 变量
#int
one=1
some_number=100 print("one=",one) #print type1
print("some_number=",some_number) #python3 print need add () """output
one= 1
some_number= 100
"""
#booleans
true_boolean=True
false_boolean=False print("true_boolean:",true_boolean)
print("False_boolean;",false_boolean) """output
true_boolean: True
False_boolean; False
"""
#string
my_name="leizeling" print("my_name:{}".format(my_name)) #print type2 """output
true_boolean: True
False_boolean; False
"""
#float
book_price=15.80 print("book_price:{}".format(book_price)) """output
book_price:15.8
"""
# 控制流:条件语句
#if
if True:
print("Hollo Python if")
if 2>1:
print("2 is greater than 1") """output
Hollo Python if
2 is greater than 1
"""
#if……else
if 1>2:
print("1 is greater than 2")
else:
print("1 is not greater than 2") """output
true_boolean: True
False_boolean; False
"""
#if……elif……else
if 1>2:
print("1 is greater than 2")
elif 1<2:
print("1 is not greater than 2")
else:
print("1 is equal to 2") """output
1 is not greater than 2
"""
# 循环/迭代器
#while
num=1
while num<=10:
print(num)
num+=1 """output
1
2
3
4
5
6
7
8
9
10
"""
#for
for i in range(1,11):#range(start,end,step),not including end
print(i) """output
1
2
3
4
5
6
7
8
9
10
"""
# 02列表:数组数据结构
#create integers list
my_integers=[1,2,3,4,5]
print(my_integers[0])
print(my_integers[1])
print(my_integers[4]) """output
1
2
5
"""
#create str list
relatives_name=["Toshiaki","Juliana","Yuji","Bruno","Kaio"]
print(relatives_name) """output
['Toshiaki', 'Juliana', 'Yuji', 'Bruno', 'Kaio']
"""
#add item to list
bookshelf=[]
bookshelf.append("The Effective Engineer")
bookshelf.append("The 4 Hour Work Week")
print(bookshelf[0])
print(bookshelf[1]) """output
The Effective Engineer
The 4 Hour Work Week
"""
# 03字典:键-值数据结构
#dictionary struct
dictionary_example={"key1":"value1","key2":"value2","key3":"value3"}
dictionary_example """output
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
"""
#create dictionary
dictionary_tk={"name":"Leandro","nickname":"Tk","nationality":"Brazilian"}
print("My name is %s"%(dictionary_tk["name"]))
print("But you can call me %s"%(dictionary_tk["nickname"]))
print("And by the waay I am {}".format(dictionary_tk["nationality"])) """output
My name is Leandro
But you can call me Tk
And by the waay I am Brazilian
"""
#dictionary add item
dictionary_tk["age"]=24
print(dictionary_tk) """output
{'nationality': 'Brazilian', 'nickname': 'Tk', 'name': 'Leandro', 'age': 24}
"""
#dictionayr del item
dictionary_tk.pop("age")
print(dictionary_tk) """output
{'nationality': 'Brazilian', 'nickname': 'Tk', 'name': 'Leandro'}
"""
# 04迭代:数据结构中的循环
#iteration of list
bookshelf=["The Effective Engineer","The 4 hours work week","Zero to One","Lean Startup","Hooked"]
for book in bookshelf:
print(book) """output
The Effective Engineer
The 4 hours work week
Zero to One
Lean Startup
Hooked
"""
#哈希数据结构(iteration of dictionary)
dictionary_tk={"name":"Leandro","nickname":"Tk","nationality":"Brazilian"}
for key in dictionary_tk: #the attribute can use any name,not only use "key"
print("%s:%s"%(key,dictionary_tk[key]))
print("===================")
for key,val in dictionary_tk.items(): #attention:this is use dictionary_tk.items().not direct use dictionary_tk
print("{}:{}".format(key,val)) """output
nationality:Brazilian
nickname:Tk
name:Leandro
===================
nationality:Brazilian
nickname:Tk
name:Leandro
"""
# 05 类和对象
#define class
class Vechicle:
pass
#create instance
car=Vechicle()
print(car) ""output
<__main__.Vechicle object at 0x000000E3014EED30>
"""
#define class
class Vechicle(object):#object is a base class
def __init__(self,number_of_wheels,type_of_tank,seating_capacity,maximum_velocity):
self.number_of_wheels=number_of_wheels
self.type_of_tank=type_of_tank
self.seating_capacity=seating_capacity
self.maximum_velocity=maximum_velocity
def get_number_of_wheels(self):
return self.number_of_wheels
def set_number_of_wheels(self,number):
self.number_of_wheels=number #create instance(object)
tesla_models_s=Vechicle(4,"electric",5,250)
tesla_models_s.set_number_of_wheels(8)#方法的调用显得复杂
tesla_models_s.get_number_of_wheels() """output
8
"""
#use @property让方法像属性一样使用
#define class
class Vechicle_1(object):#object is a base class
def __init__(self,number_of_wheels,type_of_tank,seating_capacity,maximum_velocity):#first attr must is self,do not input the attr
self._number_of_wheels=number_of_wheels ###属性名和方法名不要重复
self.type_of_tank=type_of_tank
self.seating_capacity=seating_capacity
self.maximum_velocity=maximum_velocity
@property #读属性
def number_of_wheels(self):
return self._number_of_wheels
@number_of_wheels.setter #写属性
def number_of_wheels(self,number):
self._number_of_wheels=number
def make_noise(self):
print("VRUUUUUUUM") tesla_models_s_1=Vechicle_1(4,"electric",5,250)
print(tesla_models_s_1.number_of_wheels)
tesla_models_s_1.number_of_wheels=2
print(tesla_models_s_1.number_of_wheels)
print(tesla_models_s_1.make_noise()) """output
4
2
VRUUUUUUUM
None
"""
# 06封装:隐藏信息
#公开实例变量
class Person:
def __init__(self,first_name):
self.first_name=first_name
tk=Person("TK")
print(tk.first_name)
tk.first_name="Kaio"
print(tk.first_name) """output
TK
Kaio
"""
#私有实例变量
class Person:
def __init__(self,first_name,email):
self.first_name=first_name
self._email=email
def get_email(self):
return self._email
def update_email(self,email):
self._email=email
tk=Person("TK","tk@mail.com")
tk.update_email("new_tk@mail.com")
print(tk.get_email()) """output
new_tk@mail.com
"""
#公有方法
class Person:
def __init__(self,first_name,age):
self.first_name=first_name
self._age=age
def show_age(self):
return self._age
tk=Person("TK",24)
print(tk.show_age()) """output
24
"""
#私有方法
class Person:
def __init__(self,first_name,age):
self.first_name=first_name
self._age=age
def _show_age(self):
return self._age
def show_age(self):
return self._show_age() #此处的self不要少了
tk=Person("TK",24)
print(tk.show_age()) """output
24
"""
#继承
class Car:#父类
def __init__(self,number_of_wheels,seating_capacity,maximum_velocity):
self.number_of_wheels=number_of_wheels
self.seating_capacity=seating_capacity
self.maximum_velocity=maximum_velocity
class ElectricCar(Car):#派生类
def __init(self,number_of_wheels_1,seating_capacity_1,maximum_velocity_1):
Car.__init__(self,number_of_wheels_1,seating_capacity_1,maximum_velocity_1) #利用父类进行初始化 my_electric_car=ElectricCar(4,5,250)
print(my_electric_car.number_of_wheels)
print(my_electric_car.seating_capacity)
print(my_electric_car.maximum_velocity) """output
4
5
250
"""
注:从机器之心转载
从Zero到Hero,一文掌握Python关键代码的更多相关文章
- 从零上手Python关键代码
来源 https://www.kesci.com/home/project/59e4331c4663f7655c499bc3
- Python实现代码统计工具——终极加速篇
Python实现代码统计工具--终极加速篇 声明 本文对于先前系列文章中实现的C/Python代码统计工具(CPLineCounter),通过C扩展接口重写核心算法加以优化,并与网上常见的统计工具做对 ...
- LDA处理文档主题分布代码
[python] LDA处理文档主题分布代码入门笔记 http://blog.csdn.net/eastmount/article/details/50824215
- Python静态代码检查工具Flake8
简介 Flake8 是由Python官方发布的一款辅助检测Python代码是否规范的工具,相对于目前热度比较高的Pylint来说,Flake8检查规则灵活,支持集成额外插件,扩展性强.Flake8是对 ...
- 孤荷凌寒自学python第三十二天python的代码块中的异常的捕获
孤荷凌寒自学python第三十二天python的代码块中的异常的捕获 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 今天简单了解了Python的错误陷阱,了解到其与过去学过的其它语言非常类似 ...
- Python pep8代码规范
title: Python pep8代码规范 tags: Python --- 介绍(Introduction) 官方文档:PEP 8 -- Style Guide for Python Code 很 ...
- Python 控制流代码混淆简介,加大别人分析你代码逻辑和流程难度
前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者: 王平 PS:如有需要Python学习资料的小伙伴可以加点击下方链接自 ...
- Python一行代码
1:Python一行代码画出爱心 print]+(y*-)**-(x**(y*<= ,)]),-,-)]) 2:终端路径切换到某文件夹下,键入: python -m SimpleHTTPServ ...
- python爬虫代码
原创python爬虫代码 主要用到urllib2.BeautifulSoup模块 #encoding=utf-8 import re import requests import urllib2 im ...
随机推荐
- 金庸笔下的"程序员" | 附金庸武侠全集
金庸 飞雪连天射白鹿,笑书神侠倚碧鸳当您八十高龄取得牛津大学唐朝史学博士学位,我还以为这是另一部史诗开始的信号,然而没有后续了.我的高中到大学,是十遍<笑傲江湖>的距离,我的整个青春,是大 ...
- 用python实现按权重对N个数据进行选择
需求:某公司有N个人,根据每个人的贡献不同,按贡献值给每个人赋予一个权重.设计一种算法实现公平的抽奖. 需求分析:按照权重对数据进行选择. 代码实现: 1 def fun(n,p): 2 " ...
- mysql双机互相备份
互备/***************************************master服务器**************************************/vi my.cnf[ ...
- 如何离线Windows server 2008R2 激活教程?
服务器离线激活,可是费了老大劲了,不过最后还不是离线激活,还必须联网,也或许你运气好,不联网也能激活. 如果由于种种原因不能有线的话,那就可以试试这种方法了. 1.首先,开启无线LAN服务.(不会开启 ...
- Freeman链码
[简介] 链码(又称为freeman码)是用曲线起始点的坐标和边界点方向代码来描述曲线或边界的方法,常被用来在图像处理.计算机图形学.模式识别等领域中表示曲线和区域边界.它是一种边界的编码表示法,用边 ...
- ubuntu下QtCreator启动无响应问题解决
打开Qt后就卡死. 解决方法:删除系统配置目录下的QtProject文件夹: find / -name QtProject 输出: /root/.config/QtProject 删除QtProjec ...
- 26.Generate Parentheses(生产有效括号的种类)
Level: Medium 题目描述: Given n pairs of parentheses, write a function to generate all combinations of ...
- SQL语句之行操作
SQL语句系列 1.SQL语句之行操作 2.SQL语句之表操作 3.SQL语句之数据库操作 4.SQL语句之用户管理 关系型数据库的存储形式 在关系型数据库中,数据都是以类似于Excel表格的形式存储 ...
- CentOS 7 设置日期和时间
现代操作系统分为以下两种类型的时钟: 实时时钟(Real-Time Clock,RTC),通常称为硬件时钟(一般是系统主板上的集成电路),它完全独立于操作系统的当前状态,即使在计算机关闭时也能运行. ...
- Javascript 连接两个数组
JS合并两个数组的方法 我们在项目过程中,有时候会遇到需要将两个数组合并成为一个的情况.比如: var a = [1,2,3]; var b = [4,5,6]; 有两个数组a.b,需求是将两个数组合 ...