从Zero到Hero,一文掌握Python关键代码

简介: # 01基础篇# 变量 1 #int 2 one=1 3 some_number=100 4 5 print("one=",one) #print type1 6 print("some_number=",some_number) #python3 print need a...

# 01基础篇

# 变量

 1 #int
 2 one=1
 3 some_number=100
 4 
 5 print("one=",one)   #print type1
 6 print("some_number=",some_number)   #python3 print need add ()
 7 
 8 """output
 9 one= 1
10 some_number= 100
11 """
 1 #booleans
 2 true_boolean=True
 3 false_boolean=False
 4 
 5 print("true_boolean:",true_boolean)
 6 print("False_boolean;",false_boolean)
 7 
 8 """output
 9 true_boolean: True
10 False_boolean; False
11 """
1 #string
2 my_name="leizeling"
3 
4 print("my_name:{}".format(my_name))    #print type2
5 
6 """output
7 true_boolean: True
8 False_boolean; False
9 """
#float
book_price=15.80

print("book_price:{}".format(book_price))

"""output
book_price:15.8
"""

# 控制流:条件语句

 1 #if
 2 if True:
 3     print("Hollo Python if")
 4 if 2>1:
 5     print("2 is greater than 1")
 6 
 7 """output
 8 Hollo Python if
 9 2 is greater than 1
10 """
 1 #if……else
 2 if 1>2:
 3     print("1 is greater than 2")
 4 else:
 5     print("1 is not greater than 2")
 6 
 7 """output
 8 true_boolean: True
 9 False_boolean; False
10 """
#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
"""
 1 #for
 2 for i in range(1,11):#range(start,end,step),not including end
 3     print(i)
 4 
 5 """output
 6 1
 7 2
 8 3
 9 4
10 5
11 6
12 7
13 8
14 9
15 10
16 """

# 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']
"""
 1 #add item to list
 2 bookshelf=[]
 3 bookshelf.append("The Effective Engineer")
 4 bookshelf.append("The 4 Hour Work Week")
 5 print(bookshelf[0])
 6 print(bookshelf[1])
 7 
 8 """output
 9 The Effective Engineer
10 The 4 Hour Work Week
11 """

# 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
"""
1 #dictionary add item
2 dictionary_tk["age"]=24
3 print(dictionary_tk)
4 
5 """output
6 {'nationality': 'Brazilian', 'nickname': 'Tk', 'name': 'Leandro', 'age': 24}
7 """
#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
"""
 1 #哈希数据结构(iteration of dictionary)
 2 dictionary_tk={"name":"Leandro","nickname":"Tk","nationality":"Brazilian"}
 3 for key in dictionary_tk:  #the attribute can use any name,not only use "key"
 4     print("%s:%s"%(key,dictionary_tk[key])) 
 5 print("===================")
 6 for key,val in dictionary_tk.items():  #attention:this is use dictionary_tk.items().not direct use dictionary_tk
 7     print("{}:{}".format(key,val))
 8 
 9 """output
10 nationality:Brazilian
11 nickname:Tk
12 name:Leandro
13 ===================
14 nationality:Brazilian
15 nickname:Tk
16 name:Leandro
17 """

# 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封装:隐藏信息

 1 #公开实例变量
 2 class Person:
 3     def __init__(self,first_name):
 4         self.first_name=first_name
 5 tk=Person("TK")
 6 print(tk.first_name)
 7 tk.first_name="Kaio"
 8 print(tk.first_name)
 9 
10 """output
11 TK
12 Kaio
13 """
#私有实例变量
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
"""
 1 #私有方法
 2 class Person:
 3     def __init__(self,first_name,age):
 4         self.first_name=first_name
 5         self._age=age
 6     def _show_age(self):
 7         return self._age
 8     def show_age(self):
 9         return self._show_age() #此处的self不要少了
10 tk=Person("TK",24)
11 print(tk.show_age())
12 
13 """output
14 24
15 """
 1 #继承
 2 class Car:#父类
 3     def __init__(self,number_of_wheels,seating_capacity,maximum_velocity):
 4         self.number_of_wheels=number_of_wheels
 5         self.seating_capacity=seating_capacity
 6         self.maximum_velocity=maximum_velocity
 7 class ElectricCar(Car):#派生类
 8     def __init(self,number_of_wheels_1,seating_capacity_1,maximum_velocity_1):
 9         Car.__init__(self,number_of_wheels_1,seating_capacity_1,maximum_velocity_1)  #利用父类进行初始化
10 
11 my_electric_car=ElectricCar(4,5,250)
12 print(my_electric_car.number_of_wheels)
13 print(my_electric_car.seating_capacity)
14 print(my_electric_car.maximum_velocity)
15 
16 """output
17 4
18 5
19 250
20 """

注:从机器之心转载

 

相关文章
|
1月前
|
开发框架 数据建模 中间件
Python中的装饰器:简化代码,增强功能
在Python的世界里,装饰器是那些静悄悄的幕后英雄。它们不张扬,却能默默地为函数或类增添强大的功能。本文将带你了解装饰器的魅力所在,从基础概念到实际应用,我们一步步揭开装饰器的神秘面纱。准备好了吗?让我们开始这段简洁而富有启发性的旅程吧!
37 6
|
2月前
|
存储 缓存 测试技术
Python中的装饰器:功能增强与代码复用的利器
在Python编程中,装饰器是一种强大而灵活的工具,它允许开发者以简洁优雅的方式增强函数或方法的功能。本文将深入探讨装饰器的定义、工作原理、应用场景以及如何自定义装饰器。通过实例演示,我们将展示装饰器如何在不修改原有代码的基础上添加新的行为,从而提高代码的可读性、可维护性和复用性。此外,我们还将讨论装饰器在实际应用中的一些最佳实践和潜在陷阱。
|
7天前
|
Python
课程设计项目之基于Python实现围棋游戏代码
游戏进去默认为九路玩法,当然也可以选择十三路或是十九路玩法 使用pycharam打开项目,pip安装模块并引用,然后运行即可, 代码每行都有详细的注释,可以做课程设计或者毕业设计项目参考
50 33
|
8天前
|
JavaScript API C#
【Azure Developer】Python代码调用Graph API将外部用户添加到组,结果无效,也无错误信息
根据Graph API文档,在单个请求中将多个成员添加到组时,Python代码示例中的`members@odata.bind`被错误写为`members@odata_bind`,导致用户未成功添加。
31 10
|
2月前
|
人工智能 数据挖掘 Python
Python编程基础:从零开始的代码旅程
【10月更文挑战第41天】在这篇文章中,我们将一起探索Python编程的世界。无论你是编程新手还是希望复习基础知识,本文都将是你的理想之选。我们将从最基础的语法讲起,逐步深入到更复杂的主题。文章将通过实例和练习,让你在实践中学习和理解Python编程。让我们一起开启这段代码之旅吧!
|
27天前
|
数据可视化 Python
以下是一些常用的图表类型及其Python代码示例,使用Matplotlib和Seaborn库。
通过这些思维导图和分析说明表,您可以更直观地理解和选择适合的数据可视化图表类型,帮助更有效地展示和分析数据。
66 8
|
1月前
|
API Python
【Azure Developer】分享一段Python代码调用Graph API创建用户的示例
分享一段Python代码调用Graph API创建用户的示例
53 11
|
1月前
|
测试技术 Python
探索Python中的装饰器:简化代码,增强功能
在Python的世界中,装饰器是那些能够为我们的代码增添魔力的小精灵。它们不仅让代码看起来更加优雅,还能在不改变原有函数定义的情况下,增加额外的功能。本文将通过生动的例子和易于理解的语言,带你领略装饰器的奥秘,从基础概念到实际应用,一起开启Python装饰器的奇妙旅程。
41 11
|
1月前
|
Python
探索Python中的装饰器:简化代码,增强功能
在Python的世界里,装饰器就像是给函数穿上了一件神奇的外套,让它们拥有了超能力。本文将通过浅显易懂的语言和生动的比喻,带你了解装饰器的基本概念、使用方法以及它们如何让你的代码变得更加简洁高效。让我们一起揭开装饰器的神秘面纱,看看它是如何在不改变函数核心逻辑的情况下,为函数增添新功能的吧!
|
1月前
|
程序员 测试技术 数据安全/隐私保护
深入理解Python装饰器:提升代码重用与可读性
本文旨在为中高级Python开发者提供一份关于装饰器的深度解析。通过探讨装饰器的基本原理、类型以及在实际项目中的应用案例,帮助读者更好地理解并运用这一强大的语言特性。不同于常规摘要,本文将以一个实际的软件开发场景引入,逐步揭示装饰器如何优化代码结构,提高开发效率和代码质量。
49 6