search
HomeBackend DevelopmentPHP TutorialComplete mastery of Python

Complete mastery of Python

Dec 04, 2017 am 09:09 AM
pythonmaster

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
What is PEAR in PHP?What is PEAR in PHP?Apr 28, 2025 pm 04:38 PM

PEAR is a PHP framework for reusable components, enhancing development with package management, coding standards, and community support.

What are the uses of PHP?What are the uses of PHP?Apr 28, 2025 pm 04:37 PM

PHP is a versatile scripting language used mainly for web development, creating dynamic pages, and can also be utilized for command-line scripting, desktop apps, and API development.

What was the old name of PHP?What was the old name of PHP?Apr 28, 2025 pm 04:36 PM

The article discusses PHP's evolution from "Personal Home Page Tools" in 1995 to "PHP: Hypertext Preprocessor" in 1998, reflecting its expanded use beyond personal websites.

How can you prevent session fixation attacks?How can you prevent session fixation attacks?Apr 28, 2025 am 12:25 AM

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

How do you implement sessionless authentication?How do you implement sessionless authentication?Apr 28, 2025 am 12:24 AM

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

What are some common security risks associated with PHP sessions?What are some common security risks associated with PHP sessions?Apr 28, 2025 am 12:24 AM

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

How do you destroy a PHP session?How do you destroy a PHP session?Apr 28, 2025 am 12:16 AM

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How can you change the default session save path in PHP?How can you change the default session save path in PHP?Apr 28, 2025 am 12:12 AM

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools