Home  >  Article  >  Backend Development  >  Complete mastery of Python

Complete mastery of Python

小云云
小云云Original
2017-12-04 09:09:021654browse

Python is a high-level programming language whose core design philosophy is code readability and syntax, allowing programmers to express their ideas with very little code. Python is a language that allows for elegant programming. It makes writing code and implementing my ideas simple and natural. We can use Python in many places: data science, web development, machine learning, etc. can all be developed using Python. Quora, Pinterest, and Spotify all use Python for their backend web development. So let’s learn Python.

Python Basics

1. Variable

You can think of a variable as a word used to store a value. Let's look at an example.

It is very easy to define a variable and assign a value to it in Python. Let's try it out if you want to store the number 1 in the variable "one":

one = 1

Super easy, right? You just need to assign the value 1 to the variable "one".

two = 2
some_number = 10000

As long as you want, you can assign any value to any other variable. As you can see from above, the variable “two” stores the integer variable 2 and the variable “some_number” stores 10000.

In addition to integers, we can also use Boolean values ​​(True/Flase), strings, floating point and other data types.

# booleanstrue_boolean = Truefalse_boolean = False# stringmy_name = "Leandro Tk"# floatbook_price = 15.80

2. Control flow: conditional statement

"If" uses an expression to determine whether a statement is True or False. If it is True, then execute the code in if. The example is as follows:

if True:
  print("Hello Python If")if 2 > 1:
  print("2 is greater than 1")

2 is larger than 1 , so the print code is executed.

When the expression inside "if" is false, the "else" statement will be executed.

if 1 > 2:
  print("1 is greater than 2")else:
  print("1 is not greater than 2")

1 is smaller than 2 , so the code inside "else" will be executed.

You can also use the "elif" statement:

if 1 > 2:
  print("1 is greater than 2")elif 2 > 1:
  print("1 is not greater than 2")else:
  print("1 is equal to 2")

3. Loops and iteration

In Python, we can iterate in different forms. I'll talk about while and for.

While loop: When the statement is True, the code block inside the while will be executed. So the following code will print out 1 to 10 .

num = 1while num <= 10:
    print(num)
    num += 1

The while loop requires a loop condition. If the condition is always True, it will always iterate. When the value of num is 11, the loop condition is false.

Another piece of code can help you better understand the usage of the while statement:

loop_condition = Truewhile loop_condition:
    print("Loop Condition keeps: %s" %(loop_condition))
    loop_condition = False

The loop condition is True, so it will continue to iterate until it is False.

For Loop: You can apply the variable " num " on a block of code, and the "for" statement will iterate over it for you. This code will print the same code as in while : from 1 to 10 .

for i in range(1, 11):
  print(i)

Did you see it? It's too simple. The range of i starts from 1 and goes to the 11th element (10 is the tenth element)

List: Collection | Array | Data structure

If you want to store an integer in a variable 1, but you also need to store 2 and 3, 4, 5...

Instead of using hundreds or thousands of variables, is there any other way for me to store the integers I want to store? As you guessed it, there are other ways to store them.

A list is a collection that can store a column of values ​​(just like the ones you want to store), so let's use it:

my_integers = [1, 2, 3, 4, 5]

It's really simple. We create an array called my_integer and store the data in it.

Maybe you will ask: "How do I get the values ​​in the array?"

Good question. Lists have a concept called indexing. The first element of the lower table is index 0 (0). The index of the second one is 1, and so on, you should understand.

To make it more concise, we can represent the array element by its index. I drew it:

Complete mastery of Python

Using Python syntax, it is also easy to understand:

my_integers = [5, 7, 1, 3, 4]
print(my_integers[0]) # 5print(my_integers[1]) # 7print(my_integers[4]) # 4

If you don’t want to store integers. You just want to store some strings, like a list of your relatives' names. Mine looks like this:

relatives_names = [  "Toshiaki",  "Juliana",  "Yuji",  "Bruno",  "Kaio"]
print(relatives_names[4]) # Kaio

Its principle is the same as storing integers, very friendly.

We only learned how indexing of a list works, I also need to tell you how to add an element to the list's data structure (add an item to the list).

The most common method of adding new data to a list is splicing. Let's take a look at how it is used:

bookshelf = []
bookshelf.append("The Effective Engineer")
bookshelf.append("The 4 Hour Work Week")
print(bookshelf[0]) # The Effective Engineerprint(bookshelf[1]) # The 4 Hour Work W

Splicing is super simple, you only need to pass an element (such as "valid machine") as a splicing parameter.

Okay, that’s enough knowledge about lists, let’s look at other data structures.

Dictionary: Key-Value data structure

Now we know that List is an indexed collection of integer numbers. But what if we don't want to use integers as indexes? We can use other data structures, such as numbers, strings, or other types of indexes.

Let us learn the data structure of dictionary. A dictionary is a collection of key-value pairs. The dictionary looks almost like this:

dictionary_example = {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

Key 是指向  value  的索引。我们如何访问字典中的  value  呢?你应该猜到了,那就是使用  key 。 我们试一下:

dictionary_tk = {
  "name": "Leandro",
  "nickname": "Tk",
  "nationality": "Brazilian"
}
print("My name is %s" %(dictionary_tk["name"])) # My name is Leandro
print("But you can call me %s" %(dictionary_tk["nickname"])) # But you can call me Tk
print("And by the way I&#39;m %s" %(dictionary_tk["nationality"])) # And by the way I&#39;m Brazilian

我们有个 key (age) value (24),使用字符串作为  key  整型作为  value  。

我创建了一个关于我的字典,其中包含我的名字、昵称和国籍。这些属性是字典中的 key 。

就像我们学过的使用索引访问 list 一样,我们同样使用索引(在字典中 key 就是索引)来访问存储在字典中的 value  。

正如我们使用 list 那样,让我们学习下如何向字典中添加元素。字典中主要是指向 value 的 key 。当我们添加元素的时候同样如此:

dictionary_tk = {
  "name": "Leandro",
  "nickname": "Tk",
  "nationality": "Brazilian",
  "age": 24
}
print("My name is %s" %(dictionary_tk["name"])) # My name is Leandro
print("But you can call me %s" %(dictionary_tk["nickname"])) # But you can call me Tk
print("And by the way I&#39;m %i and %s" %(dictionary_tk["age"], dictionary_tk["nationality"])) # And by the way I&#39;m Brazilian

我们只需要将一个字典中的一个 key 指向一个  value  。没什么难的,对吧?

迭代:通过数据结构进行循环

跟我们在 Python 基础中学习的一样,List 迭代十分简单。我们 Python 开发者通常使用 For 循环。我们试试看:

bookshelf = [
  "The Effective Engineer",
  "The 4 hours work week",
  "Zero to One",
  "Lean Startup",
  "Hooked"
]
for book in bookshelf:
    print(book)

对于在书架上的每本书,我们打印( 可以做任何操作 )到控制台上。超级简单和直观吧。这就是 Python 的美妙之处。

对于哈希数据结构,我们同样可以使用 for 循环,不过我们需要使用 key 来进行:

dictionary = { "some_key": "some_value" }
for key in dictionary:
   print("%s --> %s" %(key, dictionary[key])) # some_key --> some_value

上面是如何在字典中使用 For 循环的例子。对于字典中的每个 key ,我们打印出 key 和 key 所对应的 value 。

另一种方式是使用 iteritems 方法。

dictionary = { "some_key": "some_value" }
for key, value in dictionary.items():
    print("%s --> %s" %(key, value))# some_key --> some_value

我们命名两个参数为 key 和 value ,但是这不是必要的。我们可以随意命名。我们看下:

dictionary_tk = {
  "name": "Leandro",
  "nickname": "Tk",
  "nationality": "Brazilian",
  "age": 24
}
for attribute, value in dictionary_tk.items():
    print("My %s is %s" %(attribute, value))
    
# My name is Leandro
# My nickname is Tk
# My nationality is Brazilian
# My age is 24

可以看到我们使用了 attribute 作为字典中 key 的参数,这与使用 key 命名具有同样的效果。真是太棒了!

类&对象

一些理论:

对象是对现实世界实体的表示,如汽车、狗或自行车。 这些对象有两个共同的主要特征: 数据 和 行为 。

汽车有 数据 ,如车轮的数量,车门的数量和座位的空间,并且它们可以表现出其行为:它们可以加速,停止,显示剩余多少燃料,以及许多其他的事情。

我们将 数据 看作是面向对象编程中的属性和行为。 又表示为:

数据→ 属性和行为 → 方法

而 类 是创建单个对象的蓝图。 在现实世界中,我们经常发现许多相同类型的对象。 比如说汽车。 所有的汽车都有相同的构造和模型(都有一个引擎,轮子,门等)。每辆车都是由同一套蓝图构造成的,并具有相同的组件。

Python 面向对象编程模式:ON

Python,作为一种面向对象编程语言,存在这样的概念: 类 和 对象 。

一个类是一个蓝图,是对象的模型。

那么,一个类是一个模型,或者是一种定义 属性 和 行为 的方法(正如我们在理论部分讨论的那样)。举例来说,一个车辆 类 有它自己的 属性 来定义这个 对象 是个什么样的车辆。一辆车的属性有轮子数量,能源类型,座位容量和最大时速这些。

考虑到这一点,让我们来看看 Python 的 类 的语法:

class Vehicle:
   pass

上边的代码,我们使用 class 语句 来定义一个类。是不是很容易?

对象是一个 类 的实例化,我们可以通过类名来进行实例化。

car = Vehicle()
print(car) # <__main__.Vehicle instance at 0x7fb1de6c2638>

在这里,car 是类 Vehicle 的对象(或者实例化)。

记得车辆 类 有四个 属性 :轮子的数量,油箱类型,座位容量和最大时速。当我们新建一个车辆 对象 时要设置所有的 属性 。所以在这里,我们定义一个 类 在它初始化的时候接受参数:

class Vehicle:
    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

这个 init 方法 。我们称之为构造函数。因此当我们在创建一个车辆 对象 时,可以定义这些 属性 。想象一下,我们喜欢 Tesla Model S ,所以我们想创建一个这种类型的 对象。 它有四个轮子,使用电能源,五座并且最大时时速是250千米(155英里)。我们开始创建这样一个 对象 :

tesla_model_s = Vehicle(4, 'electric', 5, 250)

四轮+电能源+五座+最大时速250千米。

以上内容就是Python的具体介绍,希望能帮助到大家。

Related recommendations:

Tutorial on configuring mysql with Python (must read)

A case of Python operating excel files

Introduction to the method of connecting to the database in python

The above is the detailed content of Complete mastery of Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn