从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 ...
随机推荐
- MVC进阶篇(一)——概览
前言 说到MVC,就得先说说框架是什么东西,MVC好多人都知道,是Model.view.controller,但是MVC到底是什么样的一个框架呢,好多人又说了是约定大于配置.下面我来说说我的理解. 内 ...
- 【转】C#控件——DataGridView单元格文本自动换行
源地址:https://www.cnblogs.com/wangshenhe/archive/2012/07/25/2608324.html DataGridView是.NET开发中常用的控件,在开发 ...
- python爬虫的一些小小问题、python动态正则表达式
1.首先urllib不能用了,需要引入的是urllib2,正则re. #coding=utf-8 # import urllib import urllib2 import re def getHtm ...
- Python——变量的引用和函数的参数和返回值的传递方式
变量的引用 在python中,所有的变量都是指向地址,变量本身不保存数据,而是保存数据在内存中的地址.我们用下面的程序来理解: a = 10 print(id(a)) a = 11 print(id( ...
- wpa_supplicant
一 函数接口介绍 wpa_ctrl_open接口用来打开wpa_supplicant的控制接口,在UNIX系统里使用UNIX domain sockets,而在Windows里则是使用UDP sock ...
- 三元运算符,i++(先用后加) ++i (先加后用)区别
三元运算符是软件编程中的一个固定格式,语法是“条件表达式?表达式1:表达式2”.使用这个算法可以使调用数据时逐级筛选. 表达式:“()? :”. ()中进行二元运算 ?在运算,就形成三元运算符 i ...
- HDU-6341 Problem J. Let Sudoku Rotate(dfs 剪枝)
题目:有一个4*4*4*4的数独,每一横每一竖每一个小方块中都无重复的字母,即都为0-9,A-F..有一个已经填好的数独,若干个4*4的方块被逆时针拧转了若干次,问拧转回来至少需要多少次. 分析:很明 ...
- HDU6333 莫队+组合数
题目大意: 给定n m 在n个数中最多选择m个的所有方案 #include <bits/stdc++.h> using namespace std; #define INF 0x3f3f3 ...
- Tarjan算法打包总结(求强连通分量、割点和Tarjan-LCA)
目录 Tarjan打包总结(求强连通分量.割点和Tarjan-LCA) 强连通分量&缩点 原理 伪代码 板子(C++) 割点 原理 伪代码 最近公共祖先(LCA) 原理 伪代码 板子 Tarj ...
- linux安装PHP7以及扩展
Linux下安装PHP7 事先升级gcc4.8,然后安装PHP7,安装步骤参考:CentOS安装PHP7 1.Linux下编译的php没有php.ini 解决办法:从源代码目录中复制php.ini-d ...