从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 ...
随机推荐
- SpringMVC+Hibernate 项目开发之一(Maven环境搭建)
Maven环境搭建网上一大堆文章,直接引用leiOOlei同学的了:http://www.cnblogs.com/leiOOlei/p/3359561.html Maven版本:apache-mave ...
- 630. Course Schedule III
There are n different online courses numbered from 1 to n. Each course has some duration(course leng ...
- ajax标准格式
jquery向服务器发送一个ajax请求后,可以返回多种类型的数据格式,包括:html,xml,json,text等. $.ajax({ url:"http://www.test.co ...
- MATLAB版本(2012b 64bit),在尝试调用svmtrain函数时报错
问题:MATLAB版本(2012b 64bit),在尝试调用svmtrain函数时报错: 解决方案:参照https://blog.csdn.net/TIME_LEAF/article/details/ ...
- SDUT OJ 数据结构实验之链表六:有序链表的建立
数据结构实验之链表六:有序链表的建立 Time Limit: 1000 ms Memory Limit: 65536 KiB Submit Statistic Discuss Problem Desc ...
- 2、Numpy常用函数
创建单位矩阵和读写文件使用eye()创建单位矩阵 # -*- coding: utf-8 -*- import numpy as np i = np.eye(3) print(i) 结果: [[ 1. ...
- SpringBoot application.properties 配置项详解
参考: http://blog.csdn.net/lpfsuperman/article/details/78287265### # spring boot application.propertie ...
- 动态规划 70.climbing Stairs
1. 记忆化搜索 - 自上向下的解决问题:使用vector来保存每次计算的结果,如果下次再碰到同样的需要计算的式子就不需要重复计算了. 2. 动态规划 - 自下向上的解决问题 解法一:自顶向下 解法二 ...
- poj3417 Network 树上差分+LCA
题目传送门 题目大意:给出一棵树,再给出m条非树边,先割掉一条树边,再割掉一条非树边,问有几种割法,使图变成两部分. 思路:每一条 非树边会和一部分的树边形成一个环,分三种情况: 对于那些没有形成环的 ...
- Tyvj - 1305 单调队列优化dp
今天有点头痛就不写具体细节了,贴完走人 #include<iostream> #include<algorithm> #include<cstdio> #inclu ...