python入门指南_Python终极指南:如何从入门到专业

python入门指南

If you have an interest in Data Science, Web Development, Robotics, or IoT you must learn Python. Python has become the fastest-growing programming language due to its heavy usage and wide range of applications.

如果您对数据科学,Web开发,机器人技术或IoT感兴趣,则必须学习Python。 由于Python的大量使用和广泛的应用程序,它已成为增长最快的编程语言。

For a beginner or a person from a non-tech background, learning Python is a good choice. The syntax is like talking and writing plain English. For example, consider this syntax which shows its resemblance to the English language.

对于初学者或非技术背景的人来说,学习Python是一个不错的选择。 语法就像说和写普通英语一样。 例如,考虑显示与英语相似的语法。

print("Hello folks")

We will use Python3 in this tutorial as it is widely used. Most of Python's frameworks and libraries support this version.

我们将使用Python3在本教程中,因为它被广泛使用。 Python的大多数框架和库都支持此版本。

Note: Any version above 3.5.2 supports most of the libraries and frameworks.

注意: 3.5.2以上的任何版本都支持大多数库和框架。

指数: (Index:)

  1. Introduction

    介绍

  2. Installation

    安装

  3. Python shell

    Python外壳

  4. Comment

    评论

  5. Print

    打印

  6. Indentation

    缩进

  7. Variables

    变数

  8. Operators

    经营者

  9. Conditional Statements

    条件语句

  10. For Loops

    对于循环

  11. While loops

    While循环

  12. User Input

    用户输入

  13. Typecasting

    类型转换

  14. Dictionaries

    辞典

  15. Lists

    清单

  16. Tuples

    元组

  17. Sets

    套装

  18. Functions and Arguments

    函数和参数

  19. Args

    精氨酸

  20. keyword Arguments

    关键字参数

  21. Default Arguments

    默认参数

  22. kwargs

    夸格

  23. Scope

    范围

  24. Return Statement

    退货声明

  25. Lambda Expression

    Lambda表达

  26. List comprehension

    清单理解

  27. OOPS concepts

    OOPS概念

  28. Classes

    班级

  29. Methods

    方法

  30. Objects

    对象

  31. Constructor

    建设者

  32. Instance attribute

    实例属性

  33. Class attributes

    类属性

  34. Self

  35. Inheritance

    遗产

  36. Super

  37. Multiple Inheritance

    多重继承

  38. Polymorphism

    多态性

  39. Encapsulation

    封装形式

  40. Decorators

    装饰工

  41. Exceptions

    例外情况

  42. Package Import

    包导入

  43. JSON Handling

    JSON处理

Note: The beginning of this guide is geared towards beginners. If you have intermediate experience in Python, feel free to skip ahead using the links above.

注意:本指南的开头适用于初学者。 如果您具有Python的中级经验,请随时使用上面的链接跳过。

简介(Introduction:)

As per Github's octoverse, Python is the second most used language by developers in 2019.

根据Github的octoverse ,Python是开发人员在2019年使用的第二大语言。

Before learning any language, it's helpful to know how that language came into existence. Well, Python was developed by Guido van Rossum, a Dutch programmer, and was released in 1991.

在学习任何语言之前,了解该语言是如何存在的都会很有帮助。 嗯,Python由荷兰程序员Guido van Rossum开发,并于1991年发布。

Python is an Interpreted language. It uses the CPython Interpreter to compile the Python code to byte code. For a beginner, you don't need to know much about CPython, but you must be aware of how Python works internally.

Python是一种解释性语言。 它使用CPython解释器将Python代码编译为字节代码。 对于初学者来说,您不需要了解CPython,但是您必须了解Python在内部的工作方式。

The philosophy behind Python is that code must be readable. It achieves this with the help of indentation. It supports many programming paradigms like Functional and Object Oriented programming. You will understand more about these as you read through the article.

Python背后的哲学是代码必须可读。 它通过缩进来实现。 它支持许多编程范例,例如功能性编程和面向对象的编程。 阅读本文时,您将对这些有更多的了解。

The basic question that most beginners have in mind is what a language can do. Here are some of the use-cases of Python:

大多数初学者想到的基本问题是语言可以做什么。 以下是一些Python用例:

  • Server-side development ( Django, Flask )

    服务器端开发(Django,Flask)
  • Data Science ( Pytorch, Tensor-flow )

    数据科学(Pytorch,张量流)
  • Data analysis / Visualisation ( Matplotlib )

    数据分析/可视化(Matplotlib)
  • Scripting ( Beautiful Soup )

    脚本(美丽的汤)
  • Embedded development

    嵌入式开发

Note: I do not endorse any of the above-mentioned libraries or frameworks in particular. They are popular and broadly used in their respective domains.

注意:我不特别认可上述任何库或框架。 它们在各自的领域中很流行并且广泛使用。

安装 (Installation)

The first step of learning any programming language is installing it. Python comes bundled with most operating systems nowadays. Use the following command in your terminal to check if Python is available:

学习任何编程语言的第一步是安装它。 如今,Python与大多数操作系统捆绑在一起。 在终端中使用以下命令检查Python是否可用:

python3 --version

You'll see the following output:

您将看到以下输出:

Python 3.7.0

Note that your version of Python might be different. If you have Python installed and the version is above 3.5.2 then you can skip this section.

请注意,您使用的Python版本可能有所不同。 如果您安装了Python,并且版本高于3.5.2,则可以跳过此部分。

For those who don't have Python installed, follow the steps below:

对于未安装Python的用户,请按照以下步骤操作:

Windows用户: (Windows User: )

  • Go to Python's official website.

    转到Python的官方网站

  • Click on the download button ( Download Python 3.8.2 ) [ Note: The version may differ based on when you are reading this article ]

    单击下载按钮(Download Python 3.8.2)[ 注意:根据您阅读本文的时间,版本可能有所不同]

  • Go to the path where the package is downloaded and double-click the installer.

    转到下载软件包的路径,然后双击安装程序。
  • Check the box indicating to "Add Python 3.x to PATH" and then click on "Install Now".

    选中指示“将Python 3.x添加到PATH”的框,然后单击“立即安装”。
  • Once done you'll get a prompt that "Setup was successful". Check again if python is configured properly using the above command.

    完成后,将提示您“安装成功”。 再次检查是否使用上述命令正确配置了python。
  • To confirm if Python is installed and configured properly, use the command python3 --version.

    要确认Python是否已正确安装和配置,请使用命令python3 --version

Mac用户: (Mac User:)

  • First install xcode from the app store.

    首先从应用商店安装xcode

  • If you want to install Xcode using the terminal then use the following command:

    如果要使用终端安装Xcode,请使用以下命令:
xcode-select --install
  • After that, we will use the brew package manager to install Python. To install and configure brew, use the following command:

    之后,我们将使用brew软件包管理器安装Python。 要安装和配置brew ,请使用以下命令:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
  • Once brew setup is done, use the following command to update any outdated packages:

    冲煮设置完成后,请使用以下命令更新所有过时的软件包:
brew update
  • Use the following command to install Python:

    使用以下命令安装Python:
brew install python3
  • To confirm if Python is installed and configured properly, use the command python3 --version.

    要确认Python是否已正确安装和配置,请使用命令python3 --version

Linux用户: (Linux User:)

  • To install Python using apt, use the following command:

    要使用apt安装Python,请使用以下命令:

sudo apt install python3
  • To install the Python using yum, use the following command:

    要使用yum安装Python,请使用以下命令:

sudo yum install python3
  • To confirm if Python is installed and configured properly, use the command python3 --version.

    要确认Python是否已正确安装和配置,请使用命令python3 --version

Python Shell: (Python shell:)

The shell is one of the most useful tools you'll come across. The Python shell gives us the power to quickly test any concept before integrating it into our application.

Shell是您会遇到的最有用的工具之一。 Python外壳使我们能够在将任何概念集成到我们的应用程序之前对其进行快速测试。

Go to the terminal or command line prompt. Enter python3 command and you'll get the following output:

转到终端或命令行提示符。 输入python3命令,您将获得以下输出:

➜ python3.7
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

In this tutorial, we will learn some concepts with the help of the python3 shell which you can see above. From now on, whenever I mention go to the Python shell, it means that you have to use the python3 command.

在本教程中,我们将在上面看到的python3 shell的帮助下学习一些概念。 从现在开始,每当我提到转到Python shell时 ,这意味着您必须使用python3命令。

To learn the remaining concepts we will create a file called "testing" with the extension .py. To run this file we will use the following command:

为了学习其余的概念,我们将创建一个扩展名为.py名为“ testing”的文件。 要运行此文件,我们将使用以下命令:

python3 testing.py

Let's go to the Python shell. Type 10 + 12 after the >>> mark. You'll get the output 22:

让我们进入Python shell。 在>>>标记后键入10 + 12 。 您将获得输出22:

>>> 10 + 12
22

评论: (Commenting:)

Comments make it easy to write code as they help us (and others) understand why a particular piece of code was written. Another awesome thing about comments is that they help improve the readability of the code.

注释使编写代码变得容易,因为注释可以帮助我们(和其他人)理解编写特定代码的原因。 关于注释的另一个很棒的事情是,它们有助于提高代码的可读性。

# Stay Safe

When you add the above syntax, the Python interpreter understands that it is a comment. Everything after # is not executed.

当您添加以上语法时,Python解释器将其理解为注释。 #之后的所有内容都不会执行。

You may be wondering why you should use comments. Imagine you are a developer and you have been assigned to a huge project. The project has more than a thousand lines of code. To understand how everything works you'll need to go line by line and read through all the code.

您可能想知道为什么要使用注释。 假设您是一名开发人员,而您已被分配到一个庞大的项目。 该项目有上千行代码。 要了解一切工作原理,您需要一行一行地阅读所有代码。

What's a better solution than that? Ah-ha! Comments. Comments help us understand why a particular piece of code was written and what it returns or does. Consider it as documentation for every piece of code.

有什么比这更好的解决方案? 啊哈! 注释。 注释可帮助我们理解为什么编写特定代码以及返回或执行的代码。 将其视为每段代码的文档。

Other than debugging tools from the editor, the thing which helps developers solve problems most often is a print statement. The print statement is one of the most underrated pieces of syntax in all of programming.

除了使用编辑器中的调试工具之外,最有助于开发人员解决问题的是打印语句。 print语句是所有编程中最被低估的语法之一。

So how does it help in debugging an issue? Well, consider that you have a module and you want to check the flow of execution to understand or debug it. There are two options. Either you can use a debugger or add a print statement.

那么它如何帮助调试问题? 好吧,假设您有一个模块,并且想要检查执行流程以了解或调试它。 有两种选择。 您可以使用调试器或添加打印语句。

It's not always possible to use a debugger. For example, if you are using the Python shell, then a debugger is not available. In such a scenario, print helps us. Another scenario is when your application is running. You can add a print statement that will display in the logs of your application and monitor them in runtime.

并非总是可以使用调试器。 例如,如果您使用的是Python Shell,则调试器不可用。 在这种情况下,打印可以帮助我们。 另一种情况是您的应用程序正在运行。 您可以添加一条打印语句,该语句将显示在应用程序的日志中并在运行时对其进行监视。

Python provides a inbuilt print method with the following syntax:

Python提供了具有以下语法的内置打印方法:

print("Stay safe...")

缩进: (Indentation:)

Another interesting part of this language is indentation. Why? Well, the answer is simple: It makes the code readable and well-formatted. It is compulsory in Python to follow the rules of indentation. If proper indentation is not followed you'll get the following error:

这种语言的另一个有趣的部分是缩进。 为什么? 好吧,答案很简单:它使代码可读且格式正确。 在Python中必须遵循缩进规则。 如果未遵循正确的缩进,则会出现以下错误:

IndentationError: unexpected indent

See, even the errors in Python are so readable and easy to understand. At the start, you may be annoyed by the compulsion of indentation. But with the time you'll understand that indentation is a developer's friend.

看,即使Python中的错误也是如此易读和易于理解。 一开始,您可能会对缩进的强迫性感到恼火。 但是随着时间的流逝,您将了解缩进是开发人员的朋友。

变量: (Variables:)

As the name implies, a variable is something that can change. A variable is a way of referring to a memory location used by a computer program.

顾名思义,变量可以更改。 变量是一种引用计算机程序使用的存储位置的方法。

Well in most programming languages you need to assign the type to a variable. But in Python, you don’t need to. For example, to declare an integer in C, the following syntax is used: int num = 5;. In Python it's num = 5 .

在大多数编程语言中,您需要将类型分配给变量。 但是在Python中,您不需要这样做。 例如,要在C中声明一个整数,将使用以下语法: int num = 5; 。 在Python中, num = 5

Go to the Python shell and perform the operation step by step:

转到Python shell并逐步执行操作:

  • Integer: Numerical values that can be positive, negative, or zero without a decimal point.

    Integer :可以为正,负或零而没有小数点的数值。

>>> num = 5
>>> print(num)
5
>>> type(num)
<class 'int'>

As you can see here we have declared a num variable and assigned 5 as a value. Python's inbuilt  type method can be used to check the type of variable. When we check the type of num we see the output  <class 'int'>. For now, just focus on the int in that output. int represents an integer.

如您所见,我们已经声明了一个num变量,并将5赋值为一个值。 Python的内置type方法可用于检查变量的类型。 当我们检查num的类型时,我们看到输出<class 'int'> 。 现在,仅关注该输出中的intint代表一个整数。

  • Float: Similar an integer but with one slight difference – floats are a numerical value with a decimal place.

    Float :类似于整数,但略有不同–浮点数是一个带小数位的数值。

>>> num = 5.0
>>> print(num)
5.0
>>> type(num)
<class 'float'>

Here we have assigned a number with a single decimal to the num. When we check the type of num we can see it is float.

在这里,我们为num分配了一个带有一个小数的num 。 当我们检查num的类型时,我们可以看到它是float

  • String: A formation of characters or integers. They can be represented using double or single quotes.

    String :字符或整数的形式。 它们可以用双引号或单引号表示。

>>> greet = "Hello user"
>>> print(greet)
Hello user
>>> type(greet)
<class 'str'>

Here we have assigned a string to greet. The type of greet is a string as you can see from the output.

在这里,我们分配了一个字符串来greet 。 从输出中可以看到,greet的类型是一个字符串。

  • Boolean: A binary operator with a True or False value.

    Boolean :具有True或False值的二进制运算符。

>>> is_available = True
>>> print(is_available)
True
>>> type(is_available)
<class 'bool'>

Here we have assigned a True value to is_available. The type of this variable is boolean. You can only assign True or False. Remember T and F should be capital or it will give an error as follows:

在这里,我们为is_available分配了True值。 此变量的类型为布尔值。 您只能分配TrueFalse 。 请记住, TF应该为大写字母,否则会出现如下错误:

>>> is_available = true
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'true' is not defined
  • NoneType: This is used when we don't have the value of the variable.

    NoneType :当我们没有变量的值时使用。

>>> num = None
>>> print(num)
None
>>> type(num)
<class 'NoneType'>

运营商: (Operators:)

Take a look at the image below to see all the arithmetic operators available in Python:

请看下面的图片,以查看Python中可用的所有算术运算符:

Let's go over the operators one by one.

让我们一一介绍一下运算符。

算术运算符 (Arithmetic operators)

These include addition, subtraction, deletion, exponentiation, modulus, and floor division. Also the shorthand syntax for some operators.

这些包括加,减,删除,乘幂,模数和底除。 也是一些运算符的简写语法。

First, we will declare two variables, a and b.

首先,我们将声明两个变量ab

>>> a = 6 # Assignment
>>> b = 2

Let's try our basic arithmetic operations:

让我们尝试一下基本的算术运算:

>>> a + b # Addition
8
>>> a - b # Subtraction
4
>>> a * b # Multiplication
12
>>> a / b # Division
3.0
>>> a ** b # Exponentiation
36

To test for other arithmetic operations let's change the value of a and b.

为了测试其他算术运算,让我们更改ab的值。

>>> a = 7
>>> b = 3
>>> a % b # Modulus
1
>>> a // b # Floor division
2

Shorthand arithmetic operations are also available in Python. Refer back to the image above to test them out. To print the output of the shorthand operations use the print statement.

速写算术运算在Python中也可用。 请参考上图进行测试。 要打印速记操作的输出,请使用print语句。

比较运算符 (Comparison operators)

These include equal to, greater than, and less than.

这些包括等于,大于和小于。

>>> a = 5 # Assign
>>> b = 2 # Assign
>>> a > b # Greater than
True
>>> a < b # less then
False
>>> a == b # Equal to
False
>>> a >= 5 # Greater than or equal to
True
>>> b <= 1 # Less than or equal to
False

逻辑运算符 (Logical operators)

These operators include not, and, & or.

这些运算符包括not和and&or。

>>> a = 10
>>> b = 2
>>> a == 2 and b == 10 # and
False
>>> a == 10 or b == 10 # or
True
>>> not(a == 10) # not
False
>>> not(a == 2)
True

条件语句: (Conditional Statements:)

As the name suggests, conditional statements are used to evaluate if a condition is true or false.

顾名思义,条件语句用于评估条件是对还是错。

Many times when you are developing an application you need to check a certain condition and do different things depending on the outcome. In such scenarios conditional statements are useful. If, elif and else are the conditional statements used in Python.

很多时候,在开发应用程序时,您需要检查特定条件并根据结果执行不同的操作。 在这种情况下,条件语句很有用。 if,elif和else是Python中使用的条件语句。

We can compare variables, check if the variable has any value or if it's a boolean, then check if it's true or false. Go to the Python shell and perform the operation step by step:

我们可以比较变量,检查变量是否具有任何值或它是否是布尔值,然后检查它是对还是错。 转到Python shell并逐步执行操作:

Condition Number 1: We have an integer and 3 conditions here. The first one is the if condition. It checks if the number is equal to 10.

条件编号1:这里有一个整数和3个条件。 第一个是if条件。 它检查数字是否等于10。

The second one is the elif condition. Here we are checking if the number is less than 10.

第二个是elif条件。 在这里,我们检查数字是否小于10。

The last condition is else. This condition executes when none of the above conditions match.

最后一个条件是else 。 当以上条件都不匹配时,将执行此条件。

>>> number = 5
>>> if number == 10:
...     print("Number is 10")
... elif number < 10:
...     print("Number is less than 10")
... else:
...     print("Number is more than 10")
...

Output:

输出:

Number is less than 10

Note: It is not compulsory to check that two conditions are equal in the if condition. You can do it in the elif also.

注意:不必强制检查if条件中的两个条件是否相等。 您也可以在elif执行此操作。

Condition Number 2: We have a boolean and 2 conditions here. Have you noticed how we are checking if the condition is true? If is_available, then print "Yes it is available", else print "Not available".

条件编号2:这里有一个布尔值和2个条件。 您是否注意到我们正在检查条件是否成立? 如果is_available ,则打印“是,可用”,否则打印“不可用”。

>>> is_available = True
>>> if is_available:
...     print("Yes it is available")
... else:
...     print("Not available")
...

Output:

输出:

Yes it is available

Condition Number 3: Here we have reversed condition number 2 with the help of the not operator.

条件编号3:在此我们借助not运算符反转了条件编号2。

>>> is_available = True
>>> if not is_available:
...     print("Not available")
... else:
...     print("Yes it is available")
...

Output:

输出:

Yes it is available

Condition Number 4: Here we are declaring the data as None and checking if the data is available or not.

条件编号4:在这里,我们将数据声明为“无”,并检查数据是否可用。

>>> data = None
>>> if data:
...     print("data is not none")
... else:
...     print("data is none")
...

Output:

输出:

data is none

Condition Number 5: You can also use an inline if in Python. The syntax to achieve this is the following:

条件编号5:如果在Python中,也可以使用内联。 实现此目的的语法如下:

>>> num_a = 10
>>> num_b = 5
>>> if num_a > num_b: print("num_a is greater than num_b")
...

Output:

输出:

num_a is greater than num_b

Condition Number 6: You can also use an inline if else in Python. The syntax to achieve this is the following:

条件编号6:如果在Python中,还可以使用内联。 实现此目的的语法如下:

expression_if_true if condition else expression_if_false

Example:

例:

>>> num = 5
>>> print("Number is five") if num == 5 else print("Number is not five")

Output:

输出:

Number is five

Conditional Number 7: You can also use nested if-else statements. The syntax to achieve this is the following:

条件编号7:您还可以使用嵌套的if-else语句。 实现此目的的语法如下:

>>> num = 25
>>> if num > 10:
...     print("Number is greater than 10")
...     if num > 20:
...             print("Number is greater than 20")
...     if num > 30:
...             print("Number is greater than 30")
... else:
...     print("Number is smaller than 10")
...

Output:

输出:

Number is greater than 10
Number is greater than 20

Condition Number 8: You can also use the and operator in a conditional statement. It states if condition1 and condition2 both are true then execute it.

条件编号8:您也可以在条件语句中使用and运算符。 它声明condition1和condition2是否都为真,然后执行它。

>>> num = 10
>>> if num > 5 and num < 15:
...     print(num)
... else:
...     print("Number may be small than 5 or larger than 15")
...

Output:

输出:

10

As our number is between 5 and 15 we get the output of 10.

由于我们的数字在5到15之间,因此输出为10。

Condition Number 9: You can also use the or operator in a conditional statement. It states that if either condition1 or condition2 is true then execute it.

条件编号9:您也可以在条件语句中使用or运算符。 它声明如果condition1或condition2为true,则执行它。

>>> num = 10
>>> if num > 5 or num < 7:
...     print(num)
...

Output:

输出:

10

Are you confused because the value of num is 10 and our second condition states that num is less than 7? So why do we get the output as 10? It's because of the or condition. As one of the conditions matches, it will execute it.

您是否感到困惑,因为num值为10,而我们的第二个条件指出num小于7? 那么为什么我们将输出设为10? 是因为or条件。 当条件之一匹配时,它将执行它。

对于循环: (For Loops:)

Another useful method in any programming language is an iterator. If you have to implement something multiple times, what will you do?

任何编程语言中另一个有用的方法是迭代器。 如果您必须多次实施某项操作,该怎么办?

print("Hello")
print("Hello")
print("Hello")

Well, that's one way to do it. But imagine you have to do it a hundred or a thousand times. Well, that's a lot of print statements we have to write. There's a better way called iterators or loops. We can either use a for or while loop.

好吧,这是做到这一点的一种方法。 但是想象一下,您必须做一百或一千次。 好吧,我们必须编写许多打印语句。 有一种更好的方法称为迭代器或循环。 我们可以使用forwhile循环。

Here we are using the range method. It specifies the range until which the loop should be repeated. By default, the starting point is 0.

在这里,我们使用范围方法。 它指定了应该重复循环的范围。 默认情况下,起点是0。

>>> for i in range(3):
...     print("Hello")
...

Output:

输出:

Hello
Hello
Hello

You can also specify the range in this way range(1,3).

您还可以通过这种方式指定范围range(1,3)

>>> for i in range(1,3):
...     print("Hello")
...

Output:

输出:

Hello
Hello

"Hello" is only printed two times as we have specified the range here. Think of the range as Number on right - Number on left.

“ Hello”仅打印两次,因为我们在此处指定了范围。 将范围视为Number on right - Number on left

Well, you can also add an else statement in the for loop.

好了,您也可以在for循环中添加else语句。

>>> for i in range(3):
...     print("Hello")
... else:
...     print("Finished")

Output:

输出:

Hello
Hello
Hello
Finished

See our loop iterated 3 times ( 3 - 0 ) and once that is done it executed the else statement.

请参见我们的循环迭代3次(3-0),一旦完成,它将执行else语句。

We can also nest a for loop inside another for loop.

我们还可以在另一个for循环中嵌套一个for循环。

>>> for i in range(3):
...     for j in range(2):
...             print("Inner loop")
...     print("Outer loop")
...

Output:

输出:

Inner loop
Inner loop
Outer loop
Inner loop
Inner loop
Outer loop
Inner loop
Inner loop
Outer loop

As you can see the inner loop print statement executed two times. After that outer loop print statement executed. Again the inner loop executed two times. So what is happening here? If you are confused then consider this to solve it:

如您所见,内循环打印语句执行了两次。 之后,执行外循环打印语句。 内循环再次执行两次。 那么这里发生了什么? 如果您感到困惑,请考虑以下解决方法:

  • Our Interpreter comes and sees that there is a for loop. It goes down again and checks there is another for loop.

    我们的解释器来了,发现有一个for循环。 它再次下降,并检查是否存在另一个for循环。

  • So now it will execute the inner for loop two times and exit. Once it's finished it knows that outer for loop has instructed it to repeat two more times.

    因此,现在它将执行两次内部for循环并退出。 完成后,它便知道外部for循环已指示其重复两次。

  • It starts again and sees the inner for loop and repeats.

    它再次开始,看到内部的for循环并重复。

Well, you can also choose to pass a certain for loop condition. What does pass mean here? Well whenever that for loop will occur and the Interpreter sees the pass statement it won't execute it and will move to the next line.

好了,您也可以选择传递某个for循环条件。 通过这里意味着什么? 好了,只要发生for循环,并且解释器看到pass语句,它就不会执行它,而将移至下一行。

>>> for i in range(3):
...     pass
...

You will not get any output on the shell.

您将不会在外壳上获得任何输出。

While循环: (While loops:)

Another loop or iterator available in Python is the while loop. We can achieve some of the same results with the help of a while loop as we achieved with the for loop.

Python中可用的另一个循环或迭代器是while循环。 通过while循环,我们可以达到与for循环相同的结果。

>>> i = 0
>>> while i < 5:
...     print("Number", i)
...     i += 1
...

Output:

输出:

Number 0
Number 1
Number 2
Number 3
Number 4

Remember whenever you use a while loop it's important that you add an increment statement or a statement that will end the while loop at some point. If not then the while loop will execute forever.

请记住,每当使用while循环时,重要的是添加一个增量语句或将在某个时刻结束while循环的语句。 如果不是,则while循环将永远执行。

Another option is to add a break statement in a while loop. This will break the loop.

另一种选择是在while循环中添加break语句。 这将打破循环。

>>> i = 0
>>> while i < 5:
...     if i == 4:
...             break
...     print("Number", i)
...     i += 1
...

Output:

输出:

Number 0
Number 1
Number 2
Number 3

Here we are breaking the while loop if we find the value of i to be 4.

如果我们发现i的值为4, while在这里打破while循环。

Another option is to add an else statement in while loop. The statement will be executed after the while loop is completed.

另一种选择是在while循环中添加else语句。 该语句将在while循环完成后执行。

>>> i = 0
>>> while i < 5:
...     print("Number", i)
...     i += 1
... else:
...     print("Number is greater than 4")
...

Output:

输出:

Number 0
Number 1
Number 2
Number 3
Number 4
Number is greater than 4

The continue statement can be used to skip the current execution and to proceed to the next.

可以使用continue语句跳过当前执行并继续执行下一个。

>>> i = 0
>>> while i < 6:
...     i += 1
...     if i == 2:
...             continue
...     print("number", i)
...

Output:

输出:

number 1
number 3
number 4
number 5
number 6

用户输入: (User Input:)

Imagine you are building a command-line application. Now you have to take the user input and act accordingly. To do that you can use Python's inbuilt input method.

假设您正在构建命令行应用程序。 现在,您必须接受用户输入并采取相应的措施。 为此,您可以使用Python的内置input法。

The syntax to achieve this is as follows:

实现此目的的语法如下:

variable = input(".....")

Example:

例:

>>> name = input("Enter your name: ")
Enter your name: Sharvin

When you use the input  method and press enter, you'll be prompted with the text that you enter in the input method. Let's check if our assignment is working or not:

使用input法并按Enter键时,系统会提示您input法中input的文字。 让我们检查一下我们的作业是否有效:

>>> print(name)
Sharvin

There it is! It is working perfectly. Here Sharvin is of the type string.

在那里! 运行良好。 Sharvin在这里是字符串类型。

>>> type(name)
<class 'str'>

Let's try one more example where we will assign an integer rather than a string and check the type.

让我们再尝试一个示例,在该示例中,我们将分配整数而不是字符串并检查类型。

>>> date = input("Today's date: ")
Today's date: 12
>>> type(date)
<class 'str'>

Are you confused? We entered an integer 12 and it's still giving us its type as a string. It's not a bug. It's how input is intended to work. To convert the string to integer we will use typecasting.

你困惑吗? 我们输入了一个整数12,它仍然为字符串提供类型。 这不是错误。 这就是输入的预期工作方式。 要将字符串转换为整数,我们将使用类型转换。

类型转换: (Typecasting:)

We saw that the input method returns a string for the integer also. Now if we want to compare this output with another integer then we need a way to convert it back to an integer.

我们看到input法也返回整数的字符串。 现在,如果要将此输出与另一个整数进行比较,则需要一种将其转换回整数的方法。

>>> date_to_int = int(date)
>>> type(date_to_int)
<class 'int'>

Here we took the date that we have declared above in the User input section and converted it into the integer using the Python's inbuilt int method. This is called typecasting.

在这里,我们使用了上面在“用户输入”部分中声明的日期,并使用Python的内置int方法将其转换为整数。 这称为类型转换。

Basically you can do the following conversion with the help of typecasting:

基本上,您可以在类型转换的帮助下进行以下转换:

  • integer to string: str()

    整数到字符串: str()

  • string to integer: int()

    字符串到整数: int()

  • integer to float: float()

    要浮点的整数: float()

Note: Conversion from float to integer is also possible.
注意:也可以从float转换为integer。
>>> type(date)
<class 'str'>

# Converting from string to float
>>> date_to_float = float(date)
>>> type(date_to_float)
<class 'float'>

# Converting from float to string
>>> date_to_string = str(date_to_float)
>>> type(date_to_string)
<class 'str'>

# Converting from float to integer
>>> date_to_int = int(date_to_float)
>>> type(date_to_int)
<class 'int'>

字典: (Dictionaries:)

Imagine you want to store some user details. So how can you store these details? Yes, we can use variable to store them as follows:

假设您要存储一些用户详细信息。 那么如何存储这些详细信息? 是的,我们可以使用变量将它们存储如下:

>>> fname = "Sharvin"
>>> lname = "Shah"
>>> profession = "Developer"

To access this value we can do the following:

要访问此值,我们可以执行以下操作:

>>> print(fname)
Sharvin

But is this an elegant and optimized way to access it? The answer is no. To make it more friendly, let's store the data in a key-value dictionary.

但这是一种优雅且优化的访问方式吗? 答案是不。 为了使它更友好,让我们将数据存储在键值字典中。

What is a dictionary? A dictionary is a collection that is unordered and mutable ( i.e. it can be updated ).

什么是字典? 字典是无序且易变的集合(即可以更新)。

Following is the format of the dictionary:

以下是字典的格式:

data = {
	"key" : "value"
}

Let's understand the dictionary further by an example:

让我们通过一个例子进一步了解字典:

>>> user_details = {
...     "fname": "Sharvin",
...     "lname": "Shah",
...     "profession": "Developer"
... }

如何访问字典中的值 (How to access a value in a dictionary )

We can access the value inside a dictionary in two ways. We will take a look at both and then debug them to find out which is better.

我们可以通过两种方式访问​​字典中的值。 我们将对两者进行研究,然后对其进行调试,以找出哪个更好。

Method 1: To access the value of fname key from user_details dictionary we can use the following syntax:

方法1: 要从user_details字典访问fname键的值,我们可以使用以下语法:

>>> user_details["fname"]
'Sharvin'

Method 2: We can also access the value of fname key from user_details dictionary using get.

方法2:我们还可以使用getuser_details字典中访问fname键的值。

>>> user_details.get("fname")
'Sharvin'

I know method 1 looks easier to understand. The problem with it occurs when we try to access the data that is not available in our dictionary.

我知道方法1看起来更容易理解。 当我们尝试访问字典中不可用的数据时,就会出现问题。

>>> user_details["age"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'age'

We get a KeyError which indicates that the key is not available. Let's try the same scenario with method 2.

我们得到一个KeyError,它指示密钥不可用。 让我们用方法2尝试相同的场景。

>>> user_details.get("age")

We do not get anything printed in our console. Let's debug it further to know why this happened. Assign a variable age to our get operation and we will print it in our console.

我们没有在控制台中打印任何内容。 让我们进一步调试它,以了解为什么会发生这种情况。 给我们的get操作分配一个可变的年龄,我们将在控制台中打印它。

>>> age = user_details.get("age")
>>> print(age)
None

So when get doesn't find the key it sets the value to None. Because of this, we do not get any error. Now you may be wondering which one is right. Most of the time using method 2 makes more sense, but for some strict checking conditions, we need to use method 1.

因此,当get找不到键时,它将值设置为None。 因此,我们不会出现任何错误。 现在您可能想知道哪一个是正确的。 大部分时间使用方法2 更为合理,但是对于某些严格的检查条件,我们需要使用方法1。

如何检查密钥是否存在 (How to check if a key exists)

You may be wondering how to check if the dictionary has a particular key or not in it. Python provides the built-in method keys() to solve this issue.

您可能想知道如何检查字典中是否有特定的键。 Python提供了内置方法keys()来解决此问题。

>>> if "age" in user_details.keys():
...     print("Yes it is present")
... else:
...     print("Not present")
...

We will get the following output:

我们将获得以下输出:

Not present

What if we want to check if the dictionary is empty or not? To understand this let's declare an empty dictionary as follows:

如果我们要检查字典是否为空怎么办? 为了理解这一点,让我们声明一个空字典,如下所示:

>>> user_details = {}

When we use if-else on a dictionary directly it either returns true if data is present or false if empty.

当我们直接在字典上使用if-else时,如果存在数据,则返回true,否则返回false。

>>> if user_details:
...     print("Not empty")
... else:
...     print("Empty")
...

Output:

输出:

Empty

We can also use Python's inbuilt method bool to check if the dictionary is empty or not. Remember bool returns False if the dictionary is empty and True if it is filled.

我们还可以使用Python的内置方法bool来检查字典是否为空。 请记住,如果字典为空,则bool返回False;如果字典已填充,则返回True。

>>> bool(user_details)
False

>>> user_details = {
...     "fname" : "Sharvin"
... }
>>> bool(user_details)
True

如何更新现有键的值 (How to update the value of an existing key)

So now we know how to get a particular key and find if it exists – but how do you update it in the dictionary?

因此,现在我们知道如何获取特定的密钥并查找它是否存在-但是如何在字典中更新它呢?

Declare a dictionary as follows:

声明字典如下:

>>> user_details = {
...     "fname":"Sharvin",
...     "lname": "Shah",
...     "profession": "Developer"
... }

To update the value use the following syntax:

要更新值,请使用以下语法:

>>> user_details["profession"] = "Software Developer"
>>> print(user_details)
{'fname': 'Sharvin', 'lname': 'Shah', 'profession': 'Software Developer'}

Updating a value of key in dictionary is same as assigning a value to the variable.

更新字典中键的值与为变量分配值相同。

如何添加键值对 (How to add a key-value pair)

The next question is how to add a new value to the dictionary? Let's add an age key with a value of 100.

下一个问题是如何向字典添加新值? 让我们添加一个值为100的age密钥。

>>> user_details["age"] = "100"
>>> print(user_details)
{'fname': 'Sharvin', 'lname': 'Shah', 'profession': 'Software Developer', 'age': '100'}

As you can see a new key-value is added in our dictionary.

如您所见,我们的字典中添加了新的键值。

如何删除键值对 (How to remove a key-value pair)

To remove a key-value from the dictionary, Python provides an inbuilt method called pop.

为了从字典中删除键值,Python提供了一个内置方法pop

>>> user_details.pop("age")
'100'

>>> print(user_details)
{'fname': 'Sharvin', 'lname': 'Shah', 'profession': 'Software Developer'}

This removes the age key-value pair from the user_details dictionary. We can also use a del operator to delete the value.

这将从user_details词典中删除age键值对。 我们还可以使用del运算符删除该值。

>>> del user_details["age"]

>>> print(user_details)
{'fname': 'Sharvin', 'lname': 'Shah', 'profession': 'Software Developer'}

The del method can also be used to delete complete dictionary. Use the following syntax to delete complete dictionary del user_details.

del方法也可以用于删除完整的字典 。 使用以下语法删除完整的字典del user_details

如何复制字典 (How to copy a dictionary)

A dictionary cannot be copied in a traditional way. For example, you cannot copy value of dictA to dictB as follows:

无法以传统方式复制字典。 例如,不能将dictA值复制到dictB ,如下所示:

dictA = dictB

To copy the values you need to use the copy method.

要复制值,您需要使用copy方法。

>>> dictB = user_details.copy()

>>> print(dictB)
{'fname': 'Sharvin', 'lname': 'Shah', 'profession': 'Software Developer'}

清单: (Lists:)

Imagine you have a bunch of data that is not labeled. In other words, each piece of data doesn't have a key that defines it. So how will you store it? Lists to the rescue. They are defined as follows:

假设您有一堆未标记的数据。 换句话说,每个数据都没有定义它的键。 那么您将如何存储它? 列出来进行救援。 它们的定义如下:

data = [ 1, 5, "xyz", True ]

A list is a collection of random, ordered, and mutable data (i.e., it can be updated).

列表是随机,有序和可变数据的集合(即可以更新)。

如何访问列表元素 (How to access list elements)

Let's try to access the first element:

让我们尝试访问第一个元素:

>>> data[1]
5

Wait what happened here? We are trying to access the first element but we are getting the second element. Why?

等等这里发生了什么? 我们正在尝试访问第一个元素,但正在获取第二个元素。 为什么?

Indexing of the list begins from zero. So what do I mean by this? The indexing of the position of the elements begins from zero. The syntax to access an element is as follows:

列表的索引从零开始。 那我是什么意思呢? 元素位置的索引从零开始。 访问元素的语法如下:

list[position_in_list]

To access the first element we need to access it as follows:

要访问第一个元素,我们需要按以下方式访问它:

>>> data[0]
1

You can also specify a range to access the element between those positions.

您还可以指定一个范围以访问这些位置之间的元素。

>>> data[2:4]
['xyz', True]

Here, the first value represents the start while the last value represents the position until which we want the value.

在这里,第一个值代表起点,最后一个值代表我们想要该值之前的位置。

如何将项目添加到列表 (How to add an item to a list)

To add an item in the list we need to use the append method provided by python.

要在列表中添加项目,我们需要使用python提供的append方法。

>>> data.append("Hello")

>>> data
[1, 5, 'abc', True, 'Hello']

如何更改物品的价值 (How to change the value of an item)

To change the value of an item, use the following syntax:

要更改项目的值,请使用以下语法:

>>> data[2] = "abc"

>>> data
[1, 5, 'abc', True]

如何从列表中删除项目 (How to remove an item from a list)

To remove an item from a list we can use the Python's inbuilt remove method.

要从列表中删除项目,我们可以使用Python的内置remove方法。

>>> data.remove("Hello")
>>> data
[1, 5, 'abc', True]

如何遍历列表 (How to loop through a list)

We can also loop through the list to find a certain element and operate on it.

我们还可以遍历列表以查找某个元素并对其进行操作。

>>> for i in data:
...     print(i)
...

Output:

输出:

1
5
abc
True

如何检查项目是否存在 (How to check if an item exists or not)

To check if a particular item exists or not in list we can use if loop as follows:

要检查列表中是否存在特定项目,我们可以使用if循环,如下所示:

>>> if 'abc' in data:
...     print("yess..")
...
yess..

如何复制清单资料 (How to copy list data)

To copy list data from one list to another we need to use copy method.

要将列表数据从一个列表复制到另一个列表,我们需要使用copy方法。

>>> List2 = data.copy()
>>> List2
[1, 5, 'abc', True]

如何检查清单的长度 (How to check the length of a list)

We can also check the length of list using Python's inbuilt len method.

我们还可以使用Python的内置len方法检查列表的长度。

>>> len(data)
4

如何加入两个清单 (How to join two lists)

To join two list we can use the + operator.

要加入两个列表,我们可以使用+运算符。

>>> list1 = [1, 4, 6, "hello"]
>>> list2 = [2, 8, "bye"]
>>> list1 + list2
[1, 4, 6, 'hello', 2, 8, 'bye']

What happens if we try to access a element position which is not available in the list? We get a list index out of range error in such a condition.

如果我们尝试访问列表中不可用的元素位置,会发生什么? 在这种情况下,我们得到list index out of range error

>>> list1[6]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

元组: (Tuples:)

The tuple is a data type which is ordered and immutable (i.e. data cannot be changed).

元组是一种有序且不可更改的数据类型(即,无法更改数据)。

Let's create a tuple:

让我们创建一个元组:

>>> data = ( 1, 3 , 5, "bye")
>>> data
(1, 3, 5, 'bye')

如何访问元组元素 (How to access a tuple element)

We can access elements in the tuple the same way as we access them in a list:

我们可以像访问列表中的元素一样访问元组中的元素:

>>> data[3]
'bye'

We can access the index range as follows:

我们可以如下访问索引范围:

>>> data[2:4]
(5, 'bye')

如何更改元组的值 (How to change a tuple's value)

If you are thinking wait – how can we change the value of tuple, then you are right my friend. We cannot change the value of tuple as it is immutable. We get the following error if we try to change the value of a tuple:

如果您正在考虑等待-我们如何更改元组的值,那么您就是我的朋友。 我们不能更改元组的值,因为它是不可变的。 如果尝试更改元组的值,则会出现以下错误:

>>> data[1] = 8
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

There's a workaround available to change the value of a tuple:

有一个变通办法可以更改元组的值:

>>> data = ( 1, 3 , 5, "bye")
>>> data_two = list(data) # Convert data to list
>>> data_two[1] = 8 # Update value as list is mutable
>>> data = tuple(data_two) # Convert again to tuple
>>> data
(1, 8, 5, 'bye')

All other methods that we have seen in the list are applicable for the tuple also.

我们在列表中看到的所有其他方法也适用于元组。

[ Note: Once a tuple is created a new value cannot be added in it. ].

[注意:创建元组后,无法在其中添加新值。 ]

套装: (Sets:)

Sets are another data type in Python which are unordered and unindexed. Sets are declared as follows:

集合是Python中的另一种无序且无索引的数据类型。 集声明如下:

>>> data = { "hello", "bye", 10, 15 }
>>> data
{10, 15, 'hello', 'bye'}

如何获取价值 (How to access a value)

As sets are unindexed we cannot directly access the value in a set. Thus to access the value in the set you need to use a for loop.

由于集合没有索引,因此我们无法直接访问集合中的值。 因此,要访问集合中的值,您需要使用for循环。

>>> for i in data:
...     print(i)
...

10
15
hello
bye

如何改变价值 (How to change a value)

Once the set is created, values cannot be changed.

创建集后,就无法更改值。

如何添加项目 (How to add an item  )

To add an item to the set python provides an inbuilt method called add.

要将项目添加到集合中,python提供了一个名为add的内置方法。

>>> data.add("test")
>>> data
{10, 'bye', 'hello', 15, 'test'}

如何检查长度 (How to check length)

To check the length of the set we use the len method.

要检查集合的长度,我们使用len方法。

>>> len(data)
5

如何删除物品 (How to remove an item)

To remove an item use the remove method:

要删除项目,请使用remove方法:

>>> data.remove("test")
>>> data
{10, 'bye', 'hello', 15}

函数和参数: (Functions and Arguments:)

Functions are a handy way to declare an operation that we want to perform. With the help of functions, you can separate logic according to the operation.

函数是声明我们要执行的操作的便捷方法。 借助功能,可以根据操作分离逻辑。

Functions are a block of code that helps us in the reusability of the repetitive logic. Functions can be both inbuilt and user-defined.

函数是一段代码,可以帮助我们重复逻辑的可重用性。 函数可以是内置的,也可以是用户定义的。

To declare a function we use the def keyword. Following is the syntax of the functions:

为了声明一个函数,我们使用def关键字。 以下是函数的语法:

>>> def hello_world():
...     print("Hello world")
...

Here we are declaring a function which, when called, prints a "Hello world" statement. To call a function we use the following syntax:

在这里,我们声明一个函数,该函数在调用时将打印“ Hello world”语句。 要调用函数,我们使用以下语法:

>>> hello_world()

We will get the following output:

我们将获得以下输出:

Hello world

Remember that the () brackets in a function call means to execute it. Remove those round brackets and try the call again.

请记住,函数调用中的()括号表示要执行它。 卸下那些圆括号,然后重试通话。

>>> hello_world

You'll get the following output:

您将获得以下输出:

<function hello_world at 0x1083eb510>

When we remove the round brackets from the function call then it gives us a function reference. Here above as you can see the reference of function hello_world points to this memory address 0x1083eb510.

当我们从函数调用中删除圆括号时,它将为我们提供函数参考。 如上所示,您可以在此处看到function hello_world的引用指向此内存地址0x1083eb510

Consider you have to perform an addition operation. You can do it by declaring a and b and then performing the addition.

考虑您必须执行加法运算。 您可以通过声明ab然后执行加法来实现。

>>> a = 5
>>> b = 10
>>> a + b
15

This is one way to go. But now consider that the value of a and b have changed and you need to do it again.

这是一种方法。 但是,现在考虑ab的值已更改,您需要再次进行更改。

>>> a = 5
>>> b = 10
>>> a + b
15
>>> a = 2
>>> b = 11
>>> a + b
13

This still looks doable. Now imagine we need to add a set of two numbers a hundred times. The numbers within the set are different for every calculation. That's a lot to do. Don't worry – we have a function at our disposal to solve this issue.

这看起来仍然可行。 现在想象一下,我们需要将一组两个数字相加一百次。 对于每次计算,集合中的数字都不同。 有很多事情要做。 不用担心-我们有一个功能可以解决此问题。

>>> def add(a,b):
...     print(a+b)
...

Here we are adding a and b as a compulsory argument to the add function. To call this function we will use the following syntax:

在这里,我们将ab作为强制参数addadd函数。 要调用此函数,我们将使用以下语法:

>>> add(10,5)

Output:

输出:

15

See how easy it is to define a function and use it? So what happens if we don't pass an argument?

看到定义和使用函数有多容易? 那么,如果我们不通过辩论会怎样?

>>> add()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: add() missing 2 required positional arguments: 'a' and 'b'

Python throws a TypeError and informs us that the function requires two arguments.

Python引发TypeError并通知我们该函数需要两个参数。

Can you guess what will happen if we pass a third argument?

您能猜出如果我们通过第三个论点会发生什么?

>>> add(10,5,1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: add() takes 2 positional arguments but 3 were given

Well, Python will inform us that we have passed 3 arguments but there are only 2 positional arguments.

好吧,Python会通知我们,我们已经传递了3个参数,但是只有2个位置参数。

So what can we do when we don't know how many arguments a function can take? To solve this issue we use args and kwargs.

那么,当我们不知道一个函数可以接受多少个参数时,我们该怎么办? 为了解决这个问题,我们使用args和kwargs。

精氨酸: (Args:)

When you don't know how many arguments will be passed to the function, use args and kwargs (kwargs are discussed below).

当您不知道将有多少参数传递给该函数时,请使用args和kwargs(以下将讨论kwargs)。

To pass n number of arguments to a function we use args. We add a * in front of the argument.

要将n个参数传递给函数,我们使用args。 我们在参数前面添加一个*

Remember when you attach a * in front, you will be receiving a tuple of arguments.

请记住,当您在前面加上*时,将收到一个元组参数。

>>> def add(*num):
...     print(num)
...

Here *num is an instance of args. Now when we call the function add we can pass in n number of arguments and it won't throw a TypeError.

*num是args的实例。 现在,当我们调用函数add我们可以传入n个参数,并且不会抛出TypeError

>>> add(1,2,3)
(1, 2, 3)

>>> add(1,2,3,4)
(1, 2, 3, 4)

Now to perform the addition operation we will use the Python's builtin function sum

现在要执行加法运算,我们将使用Python的内置函数sum

>>> def add(*num):
...     print(sum(num))
...

Now when we call the add function we will get the following output:

现在,当我们调用add函数时,将获得以下输出:

>>> add(1,2,3) # Function call
6
>>> add(1,2,3,4) # Function call
10

关键字参数: (Keyword Arguments:)

There are times when we don't know the order of the arguments that will be passed to our function when it's called. In such a scenario we use keyword arguments because you can pass them in any order in your call and our function will know the value. Take a look at this example:

有时候,我们不知道调用函数时传递给我们函数的参数顺序。 在这种情况下,我们使用关键字参数,因为您可以在调用中以任何顺序传递它们,而我们的函数将知道该值。 看一下这个例子:

>>> def user_details(username, age):
...     print("Username is", username)
...     print("Age is", age)
...

Let's call this function as follows:

让我们将此函数称为如下:

>>> user_details("Sharvin", 100)

We will get the following output:

我们将获得以下输出:

Username is Sharvin
Age is 100

Well this looks correct, but imagine if we called our function in this way:

好吧,这看起来是正确的,但是想像一下我们是否以这种方式调用函数:

>>> user_details(100, "Sharvin")

We will get the following output:

我们将获得以下输出:

Username is 100
Age is Sharvin

This does not look right. What happened is username took the value of 100 while age took the value of "Sharvin". In scenarios like this where we don't know the order of arguments we can use keyword arguments when calling the function:

这看起来不对。 发生的情况是username的值为100,而age的值为“ Sharvin”。 在这种情况下,我们不知道参数的顺序,可以在调用函数时使用关键字参数:

>>> user_details(age=100, username="Sharvin")

Output:

输出:

Username is Sharvin
Age is 100

默认参数: (Default Argument:)

Suppose there is a condition where we are not sure if a particular argument will get a value or not when the function is called. In such a scenario we can use Default arguments as follows:

假设存在一个条件,即我们不确定在调用函数时特定参数是否会获取值。 在这种情况下,我们可以使用Default参数,如下所示:

>>> def user_details(username, age = None):
...     print("Username is", username)
...     print("Age is", age)
...

Here we are assigning a None to our age argument. If we don't pass a second argument while calling the function it will take None as a default value.

在这里,我们为年龄参数指定了“ None 。 如果我们在调用函数时没有传递第二个参数,它将以None为默认值。

Let's call the function:

让我们调用该函数:

>>> user_details("Sharvin")

Output:

输出:

Username is Sharvin
Age is None

If we pass in the second argument it will override None and use it as the value.

如果我们传入第二个参数,它将覆盖None并将其用作值。

>>> user_details("Sharvin", 200)
Username is Sharvin
Age is 200

But what will happen if we assign the first argument in our function as default and the second as a compulsory argument? Go to the Python shell and try this out:

但是,如果我们将函数中的第一个参数分配为默认参数,而第二个参数作为强制参数,将会发生什么呢? 转到Python shell并尝试以下方法:

>>> def user_details(username=None, age):
...     print("Username is", username)
...     print("Age is", age)
...

You'll get the following error:

您将收到以下错误:

File "<stdin>", line 1
SyntaxError: non-default argument follows default argument

Remember: All compulsory arguments must be declared first and then the default argument must be declared.

切记:必须先声明所有强制性参数,然后必须声明默认参数。

夸克 (kwargs:)

There can be a situation where you don't know how many keyword arguments will be passed into the function. In such a scenario we can use Kwargs.

在某些情况下,您可能不知道将有多少关键字参数传递给该函数。 在这种情况下,我们可以使用Kwargs。

To use kwargs we put ** in front of the argument.

要使用kwargs,我们在参数前放置**

Remember: When you attach a ** in front, you will be receiving a dictionary of arguments.

切记:在前面加上**时,您将收到一个参数字典。

Let's understand this by example. We will declare a function which accepts username as it's argument with ** in front of it.

让我们通过示例来了解这一点。 我们将声明一个函数,该函数接受用户名作为参数,并在其前面带有**

>>> def user(**username):
...     print(username)
...

When we call the user function as follows we will receive a dictionary.

当我们如下调用user函数时,我们将收到一个字典。

>>> user(username1="xyz",username2="abc")

Output:

输出:

{'username1': 'xyz', 'username2': 'abc'}

So what's happening here? It looks the same as args, right?

那么这是怎么回事? 看起来和args一样,对吧?

No, it's not. In args, you cannot access a particular value by its name as it is in the form of a tuple. Here we get the data in the form of a dictionary so we can easily access the value.

不,这不对。 在args中,您不能按元组的形式按名称访问特定值。 在这里,我们以字典的形式获取数据,因此我们可以轻松地访问该值。

Consider this example:

考虑以下示例:

>>> def user(**user_details):
...     print(user_details['username'])
...

Let's call our function:

让我们调用函数:

>>> user(username="Sharvin",age="1000")

And you'll get the following output:

您将获得以下输出:

Sharvin

范围: (Scope:)

A scope defines where a variable or function is available. There are two types of scope in Python: Global and Local.

范围定义了变量或函数在何处可用。 Python中有两种作用域:全局和局部。

全球范围 (Global Scope)

A variable or function created in the main body of Python code is called a global variable or function and is part of the global scope. For example:

在Python代码主体中创建的变量或函数称为全局变量或函数,并且是全局范围的一部分。 例如:

>>> greet = "Hello world"
>>> def testing():
...     print(greet)
...
>>> testing()
Hello world

Here the variable greet is available globally because it is declared in the body of the program.

此处, greet变量在全局范围内可用,因为它是在程序主体中声明的。

当地范围 (Local Scope)

A variable or function created inside a function is called a local variable or function and is part of the local scope:

在函数内部创建的变量或函数称为局部变量或函数,并且是局部范围的一部分:

>>> def testing():
...     greet = "Hello world"
...     print(greet)
...
>>> testing()
Hello world

Here greet is created inside the testing function and is only available there. Let's try to access it in our main body and see what happens:

greet是在测试功能内部创建的,仅在此处可用。 让我们尝试在我们的主体中访问它,看看会发生什么:

>>> print(greet)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'greet' is not defined

Remember: Restart the Python console by pressing ctrl + d and starting the shell again by using the python3 command before testing the code above. The first example has you declare the greet variable in the global scope meaning it will still be available in memory when you run the second example.

切记:在测试上面的代码之前,请按ctrl + d重新启动Python控制台,并使用python3命令再次启动Shell。 第一个示例让您在全局范围内声明greet变量,这意味着当您运行第二个示例时,它仍将在内存中可用。

As greet is not available globally we get the error that it is not defined.

由于无法在全球范围内使用greet ,因此会收到未定义的错误。

退货说明: (Return Statement:)

Until now our functions are pretty simple. They are receiving data, processing it, and printing them. But in the real world, you need a function to return output so that it can be used in different operations.

到目前为止,我们的功能还很简单。 他们正在接收数据,对其进行处理并进行打印。 但是在现实世界中,您需要一个函数来返回输出,以便可以在不同的操作中使用它。

To achieve this, return statements are used. Remember, return statements are only part of functions and methods. The syntax for the return statement is quite easy.

为此,使用return语句。 请记住,return语句只是函数和方法的一部分。 return语句的语法非常简单。

>>> def add(a, b):
...     return a + b
...
>>> add(1,3)
4

Instead of printing our addition, we are returning the output. The value of the returned output can also be stored in a variable.

而不是打印添加内容,我们返回输出。 返回的输出值也可以存储在变量中。

>>> sum = add(5,10)
>>> print(sum)
15

Lambda表达式: (Lambda Expression:)

Consider a situation where you don't want to perform much computation in a function. In such a situation writing a full-fledged function doesn't make sense. To solve this we use a lambda expression or lambda function.

考虑一种情况,您不想在一个函数中执行太多计算。 在这种情况下,编写完整的函数是没有意义的。 为了解决这个问题,我们使用了lambda表达式或lambda函数。

So what is a lambda expression? It is an anonymous function and they are restricted to a single expression. The lambda expression can take n number of arguments.

那么什么是lambda表达式? 它是一个匿名函数,它们被限制为单个表达式。 lambda表达式可以接受n个参数。

The syntax for lambda expression is:

lambda表达式的语法为:

variable = lambda arguments: operation

Let's understand it more by example:

让我们通过示例进一步了解它:

>>> sum = lambda a: a + 10

Here we have declared a variable sum which we are using to call the lambda function. a represents the argument that is passed to that function.

在这里,我们声明了一个变量sum ,用于调用lambda函数。 a表示传递给该函数的参数。

Let's call our function:

让我们调用函数:

>>> x(5)
15

清单理解: (List comprehension:)

Consider a situation where you want a list of squares. Normally you'll declare a  squares list and then in a for loop you'll square out the numbers.

考虑一种情况,您需要一个正方形列表。 通常,您将声明一个squares列表,然后在for循环中将数字平方。

>>> squares = []
>>> for x in range(10):
...     squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Well this is doable, but we can achieve this in a single line with the help of list comprehension.

嗯,这是可行的,但是我们可以借助列表理解功能在一行中实现。

There are two ways to achieve this. Let's understand both of them.

有两种方法可以实现此目的。 让我们了解它们两者。

>>> squares = list(map(lambda x: x**2, range(10)))
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Here we are using list constructor to build a list and inside that lambda function which squares out the number. Another way to achieve the same result is as follows:

在这里,我们使用list构造函数来构建列表,并在该lambda函数内部对数字求平方。 实现相同结果的另一种方法如下:

>>> squares = list(x**2 for x in range(10))
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

I prefer this way because it is easier to more concise and easier to understand.

我更喜欢这种方式,因为它更易于理解和理解。

What about when we have a condition where we want a set of two numbers that are the same? Well, we need to write two for loops and one if loop.

当我们有一个条件,我们想要一组两个相同的数字时,该怎么办? 好吧,我们需要编写两个for循环和一个if循环。

Let's see how that will look:

让我们看看它的外观:

>>> num_list = []
>>> for i in range(10):
...     for j in range(10):
...             if i == j:
...                     num_list.append((i,j))
...
>>> num_list
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]

That's a lot of work. And in terms of readability it's hard to understand.

这是很多工作。 而且在可读性方面很难理解。

Let's use list comprehension to achieve the same result.

让我们使用列表理解来获得相同的结果。

>>> num_list = list((i,j) for i in range(10) for j in range(10) if i == j)

>>> num_list
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]

See how easy it is to get the same output in a single expression? Well, that's the power of list comprehension.

看看在单个表达式中获得相同的输出有多么容易? 好吧,这就是列表理解的能力。

OOP概念: (OOP concepts:)

Python is a multi-paradigm programming language. It means Python can use different approaches to solve a problem. One of the paradigms is procedural or functional programming. It structures the code like a recipe – a set of steps in the form of functions and code blocks.

Python是一种多范式编程语言。 这意味着Python可以使用不同的方法来解决问题。 范例之一是过程或功能编程。 它像配方一样构造代码-以功能和代码块的形式的一组步骤。

Another approach to solving the problem is by creating classes and objects. This is known as object-oriented oriented programming. An object is a collection of data (variables) and methods that act on those data. And classes are a blueprint for each object.

解决问题的另一种方法是创建类和对象。 这就是所谓的面向对象编程。 对象是数据(变量)和作用于这些数据的方法的集合。 类是每个对象的蓝图。

The important thing to understand in object-oriented programming is that objects are at the center of the paradigm – they not only represent the data but also the structure of the program.

在面向对象的编程中要理解的重要一点是,对象是范例的中心–它们不仅代表数据,而且代表程序的结构。

You can choose the paradigm that best suits the problem at hand, mix different paradigms in one program, and/or switch from one paradigm to another as your program evolves.

您可以选择最适合当前问题的范例,在一个程序中混合使用不同的范例,和/或随着程序的发展从一个范例切换到另一个范例。

面向对象编程的优点 (Advantages of object oriented programming)

  • Inheritance: This is one of the most useful concepts in OOP. It specifies that the child object will have all the properties and behavior of the parent object. Thus Inheritance allows us to define a class that inherits all the methods and properties from another class.

    继承:这是OOP中最有用的概念之一。 它指定子对象将具有父对象的所有属性和行为。 因此,继承允许我们定义一个类,该类继承另一个类的所有方法和属性。

  • Polymorphism: To understand polymorphism let’s divide the word into two parts. The first part "poly" means many and "morph" means to form or shape. Thus polymorphism means one task can be performed in many different ways.

    多态性:要了解多态性,我们将单词分为两个部分。 第一部分“聚”是指许多,“变形”是指形成或成形。 Thus polymorphism means one task can be performed in many different ways.

    Polymorphism: To understand polymorphism let’s divide the word into two parts. The first part "poly" means many and "morph" means to form or shape. Thus polymorphism means one task can be performed in many different ways.

    Polymorphism: To understand polymorphism let's divide the word into two parts. The first part "poly" means many and "morph" means to form or shape. Thus polymorphism means one task can be performed in many different ways.

    For example, you have a class

    For example, you have a class

    animal, and all animals speak. But they speak differently. Here, the “speak” behavior is polymorphic and depends on the animal. So, the abstract “animal” concept does not actually “speak”, but specific animals (like dogs and cats) have a concrete implementation of the action “speak”.

    animal , and all animals speak. But they speak differently. Here, the “speak” behavior is polymorphic and depends on the animal. So, the abstract “animal” concept does not actually “speak”, but specific animals (like dogs and cats) have a concrete implementation of the action “speak”.

    animal, and all animals speak. But they speak differently. Here, the “speak” behavior is polymorphic and depends on the animal. So, the abstract “animal” concept does not actually “speak”, but specific animals (like dogs and cats) have a concrete implementation of the action “speak”.

    animal , and all animals speak. But they speak differently. Here, the “speak” behavior is polymorphic and depends on the animal. So, the abstract “animal” concept does not actually “speak”, but specific animals (like dogs and cats) have a concrete implementation of the action “speak”.

    Polymorphism means the same function name or method name being used for different types.

    Polymorphism means the same function name or method name being used for different types.

  • Encapsulation: In object-oriented programming you can restrict access to methods and variables – we can make the methods and variables private. This can prevent the data from being modified by accident and is known as encapsulation.

    Encapsulation: In object-oriented programming you can restrict access to methods and variables – we can make the methods and variables private. This can prevent the data from being modified by accident and is known as encapsulation.

First, we will understand classes, objects, and constructors. Then after that, we will look into the above properties again. If you already know about classes, objects, and constructors, feel free to skip ahead.

First, we will understand classes, objects, and constructors. Then after that, we will look into the above properties again. If you already know about classes, objects, and constructors, feel free to skip ahead.

Classes: (Classes:)

There are primitive data structures available in Python, for example, numbers, strings, and lists. These can all be used for simple representations like name, place, cost, and so on.

There are primitive data structures available in Python, for example, numbers, strings, and lists. These can all be used for simple representations like name, place, cost, and so on.

But what if we have more complex data? If there is a pattern in the repetition of the properties of that data, what can we do?

But what if we have more complex data? If there is a pattern in the repetition of the properties of that data, what can we do?

Suppose we have 100 different animals. Every animal has a name, age, legs, etc. What if we want to add other properties to each animal, or one more animal gets added to that list? To manage such a complex scenario we need classes.

Suppose we have 100 different animals. Every animal has a name, age, legs, etc. What if we want to add other properties to each animal, or one more animal gets added to that list? To manage such a complex scenario we need classes.

According to the official Python documentation:

According to the official Python documentation :

Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made.
Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made.

Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state.

Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state.

Syntax of class:

Syntax of class:

class ClassName:

    <expression-1>
    .
    .
    .
    <expression-N>

We use class keyword to define a class. We will define a class Car.

We use class keyword to define a class. We will define a class Car .

class Car:
    pass

Methods: (Methods:)

Methods look the same as functions. The only difference is that methods are dependent on an object. A function can be invoked by name while methods need to be invoked by using their class reference. They are defined inside the class.

Methods look the same as functions. The only difference is that methods are dependent on an object. A function can be invoked by name while methods need to be invoked by using their class reference. They are defined inside the class.

In our example, let's create two methods. One is an engine and another is a wheel. These two methods define the parts available in our car.

In our example, let's create two methods. One is an engine and another is a wheel. These two methods define the parts available in our car.

The below program will give us a better idea of classes:

The below program will give us a better idea of classes:

>>> class Car:
...     def engine(self):
...             print("Engine")
...

>>> Car().engine()
Engine

Here we are calling the engine method by using the Car() reference.

Here we are calling the engine method by using the Car() reference.

To summarize, the class provides a blueprint of what should be defined but it does not provide any real content. The Car class above defines the engine but it will not state what a specific car’s engine is. It is specified by the object.

To summarize, the class provides a blueprint of what should be defined but it does not provide any real content. The Car class above defines the engine but it will not state what a specific car's engine is. It is specified by the object.

Objects: (Objects:)

The object is an instance of the class. Let’s consider the above example of a car. Here Car is our class and toyota is the object of the car. We can create multiple copies of the object. Every object must be defined using the class.

The object is an instance of the class. Let's consider the above example of a car. Here Car is our class and toyota is the object of the car. We can create multiple copies of the object. Every object must be defined using the class.

The syntax for creating an object is:

The syntax for creating an object is:

toyota = Car()

Let’s consider our Car example to understand objects a bit better:

Let's consider our Car example to understand objects a bit better:

class Car:

    def engine(self):
        print("Engine")

    def wheel(self):
        print("Wheel")

toyota = Car()

The above toyota = Car() is a class object. Class objects support two kinds of operations: attribute references and instantiation.

The above toyota = Car() is a class object . Class objects support two kinds of operations: attribute references and instantiation.

Class instantiation uses function notation. The instantiation operation (“calling” a class object) creates an empty object.

Class instantiation uses function notation. The instantiation operation (“calling” a class object) creates an empty object.

Now we can call different methods from our class Car using the object toyota that we have created. let’s call the method engine and wheel.

Now we can call different methods from our class Car using the object toyota that we have created. let's call the method engine and wheel .

Open your editor and create a file named mycar.py. In that file copy the code below:

Open your editor and create a file named mycar.py . In that file copy the code below:

class Car:

    def engine(self):
        print("Engine")

    def wheel(self):
        print("Wheel")

if __name__ == "__main__":
    toyota = Car()
    toyota.engine()
    toyota.wheel()

Save the above code. Now let's take a closer look at our program.

Save the above code. Now let's take a closer look at our program.

Here we are creating a toyota object with the help of Car class. The toyota.engine() is a method object. What exactly happens when a method object is called?

Here we are creating a toyota object with the help of Car class. The toyota.engine() is a method object. What exactly happens when a method object is called?

In the call toyota.engine() doesn't take any argument but if you see the method declaration we can see that it takes a self argument.

In the call toyota.engine() doesn't take any argument but if you see the method declaration we can see that it takes a self argument.

You may be confused about why it is not throwing an error. Well whenever we use a method object, the call toyota.engine() is converted to Car.engine(toyota). We will understand more about the self in the upcoming section.

You may be confused about why it is not throwing an error. Well whenever we use a method object, the call toyota.engine() is converted to Car.engine(toyota) . We will understand more about the self in the upcoming section.

Run the program using the following command.

Run the program using the following command.

python mycar.py

You'll get the following output:

You'll get the following output:

Engine
Wheel

Constructor: (Constructor:)

The __init__ method is the constructor method in Python. The constructor method is used to initialize the data.

The __init__ method is the constructor method in Python. The constructor method is used to initialize the data.

Go to the Python shell and enter this example:

Go to the Python shell and enter this example:

>>> class Car():
...     def __init__(self):
...             print("Hello I am the constructor method.")
...

When we will call our class we will get the following output:

When we will call our class we will get the following output:

>>> toyota = Car()
Hello I am the constructor method.

Note: You will never have to call the init() method – it gets called automatically when you create a class instance.

Note: You will never have to call the init () method – it gets called automatically when you create a class instance.

Instance attributes: (Instance attributes:)

All the classes have objects and all the objects have attributes. Attributes are the properties. We use __init__() method to specify an object’s initial attribute.

All the classes have objects and all the objects have attributes. Attributes are the properties. We use __init__() method to specify an object's initial attribute.

Let’s consider our car example:

Let's consider our car example:

class Car():
    def __init__(self, model): 
        self.model = model  #instance attribute

In our example, each Car() has a specific model. Thus instance attributes are unique data to each instance.

In our example, each Car() has a specific model. Thus instance attributes are unique data to each instance.

Class attributes: (Class attributes:)

We saw that instance attributes are specific to each object but class attributes are the same for all the instances. Let us look at the example of the car with the help of class attributes.

We saw that instance attributes are specific to each object but class attributes are the same for all the instances. Let us look at the example of the car with the help of class attributes.

class Car():

    no_of_wheels = 4 #class attribute

So each car can have different models but all the cars will have only 4 wheels.

So each car can have different models but all the cars will have only 4 wheels.

Self: (Self:)

Now let’s understand what self means and how we use it in object-oriented programming. self represents the instance of a class. By using the self keyword we can access the data initialized in the constructor and methods of a class.

Now let's understand what self means and how we use it in object-oriented programming. self represents the instance of a class. By using the self keyword we can access the data initialized in the constructor and methods of a class.

Let's look at an example of how self can be used. Let’s create a method named brand under our class Car.

Let's look at an example of how self can be used. Let's create a method named brand under our class Car .

Inside that __init__ method, we will pass a model by passing our car’s model name when we are instantiating our object. This name can be accessed anywhere in the class, for example self.model in our case.

Inside that __init__ method, we will pass a model by passing our car's model name when we are instantiating our object. This name can be accessed anywhere in the class, for example self.model in our case.

Go to the file named mycar.py and replace old code with this code:

Go to the file named mycar.py and replace old code with this code:

class Car(): 

  def __init__(self, model): 
    self.model = model
  		
  def brand(self): 
    print("The brand is", self.model)  

if __name__ == "__main__":
  car = Car("Bmw")
  car.brand()

Now when we run our above program using the following command:

Now when we run our above program using the following command:

python mycar.py

We will get the following output:

We will get the following output:

The brand is Bmw

Note: self is a convention and not a real Python keyword. self is an argument in a method and we can use another name in place of it. But it is recommended to use self because it increases the readability of  your code.

Note: self is a convention and not a real Python keyword. self is an argument in a method and we can use another name in place of it. But it is recommended to use self because it increases the readability of your code.

Inheritance: (Inheritance:)

Inheritance refers to when a class inherits the property of another class.

Inheritance refers to when a class inherits the property of another class.

The class from which properties are inherited is called the base class. The class which inherits the property of another class is called the derived class.

The class from which properties are inherited is called the base class. The class which inherits the property of another class is called the derived class.

Inheritance can be defined as a parent and child relationship. The child inherits the properties of the parent. Thus making the child a derived class while parent is a base class. Here the term property refers to attributes and methods.

Inheritance can be defined as a parent and child relationship. The child inherits the properties of the parent. Thus making the child a derived class while parent is a base class. Here the term property refers to attributes and methods.

The syntax for a derived class definition looks like this:

The syntax for a derived class definition looks like this:

class DerivedClassName(BaseClassName):
    <statement-1>
    .
    .
    .
    <statement-N>

It’s important to note that child classes override or extend the attributes and behaviors of parent class methods. This is to say that child classes inherit all of the the attributes and behaviors of their parents – but they're also able to specify different behavior to follow.

It's important to note that child classes override or extend the attributes and behaviors of parent class methods. This is to say that child classes inherit all of the the attributes and behaviors of their parents – but they're also able to specify different behavior to follow.

The most basic type of class is an object, which generally all other classes inherit as their parent. Let’s modify our previous example to understand how inheritance works.

The most basic type of class is an object, which generally all other classes inherit as their parent. Let's modify our previous example to understand how inheritance works.

We will create a base class named vehicle:

We will create a base class named vehicle :

class Vehicle:
    def __init__(self, name):
        self.name = name
    
    def getName(self):
        return self.name

We have created a class Vehicle and instantiated a constructor with self.name which we are using in getName method. Whenever this method will be called, it will return the name that has been passed when an object is instantiated for that class.

We have created a class Vehicle and instantiated a constructor with self.name which we are using in getName method. Whenever this method will be called, it will return the name that has been passed when an object is instantiated for that class.

Now let’s create a child class Car:

Now let's create a child class Car :

class Vehicle:
    def __init__(self, name):
        self.name = name
    
    def getName(self):
        return self.name

class Car(Vehicle):
  pass

Car is a child class of Vehicle. It inherits all the method and attributes of parent class.

Car is a child class of Vehicle . It inherits all the method and attributes of parent class.

Now let’s use methods and attribute from the Vehicle class in our child class Car.

Now let's use methods and attribute from the Vehicle class in our child class Car .

class Vehicle:

    def __init__(self, name, color='silver'):
        self.name = name
        self.color = color
    
    def get_name(self):
        return self.name
    
    def get_color(self):
        return self.color

class Car(Vehicle):
  pass

audi = Car("Audi r8")
print("The name of our car is", audi.get_name(), "and color is", audi.get_color())

Let's understand what we have done here.

Let's understand what we have done here.

We have declared a class named Vehicle with a constructor that takes name as an argument while color has a default argument.

We have declared a class named Vehicle with a constructor that takes name as an argument while color has a default argument.

We have two methods inside it. get_name returns name while get_color returns the color. We have instantiated an object and passed the car name.

We have two methods inside it. get_name returns name while get_color returns the color. We have instantiated an object and passed the car name.

One thing you'll notice here that we are using base class methods in our child class declaration.

One thing you'll notice here that we are using base class methods in our child class declaration.

Run the above program using the following command:

Run the above program using the following command:

python mycar.py

Output:

输出:

The name of our car is Audi r8 and color is silver

We can also override a parent method or attribute. In the above example, we have defined our vehicle color has silver. But what if the color of our car is black?

We can also override a parent method or attribute. In the above example, we have defined our vehicle color has silver. But what if the color of our car is black?

Now for every child class, we can’t make changes in the parent class. There comes the overriding functionality.

Now for every child class, we can't make changes in the parent class. There comes the overriding functionality.

class Vehicle:

    def __init__(self, name, color='silver'):
        self.name = name
        self.color = color
    
    def get_name(self):
        return self.name
    
    def get_color(self):
        return self.color

class Car(Vehicle):

    def get_color(self):
        self.color = 'black'
        return self.color

audi = Car("Audi r8")
print("The name of our car is", audi.get_name(), "and color is", audi.get_color()

As you can see in the above program, I have not instantiated a constructor. The reason behind this is that our child class Car is only using attributes from the Vehicle class and it is already inheriting them. So in such a scenario, there is no need to re-instantiate these attributes.

As you can see in the above program, I have not instantiated a constructor. The reason behind this is that our child class Car is only using attributes from the Vehicle class and it is already inheriting them. So in such a scenario, there is no need to re-instantiate these attributes.

Now when we run the above program we will get the following output:

Now when we run the above program we will get the following output:

The name of our car is Audi r8 and color is black

Super: (Super:)

super()  returns a temporary object of the superclass that then allows us to call that superclass’s methods.

super() returns a temporary object of the superclass that then allows us to call that superclass's methods.

Calling the previously built methods with super() saves us from needing to rewrite those methods in our subclass, and allows us to swap out superclasses with minimal code changes. Thus super extends the functionality of the inherited method.

Calling the previously built methods with super() saves us from needing to rewrite those methods in our subclass, and allows us to swap out superclasses with minimal code changes. Thus super extends the functionality of the inherited method.

Let’s extend our car example using super(). We will instantiate a constructor with brand_name and color in the parent class, Vehicle. Now we will call this constructor from our child class (Car) using super. We will create a get_description method which is returning self.model from Car class and self.brand_name, self.color from the Vehicle class.

Let's extend our car example using super() . We will instantiate a constructor with brand_name and color in the parent class, Vehicle . Now we will call this constructor from our child class ( Car ) using super . We will create a get_description method which is returning self.model from Car class and self.brand_name , self.color from the Vehicle class.

class Vehicle:
 
    def __init__(self, brand_name, color):
        self.brand_name = brand_name
        self.color = color
 
    def get_brand_name(self):
        return self.brand_name
 
class Car(Vehicle):
 
    def __init__(self, brand_name, model, color):  
        super().__init__(brand_name, color)       
        self.model = model
 
    def get_description(self):
        return "Car Name: " + self.get_brand_name() + self.model + " Color:" + self.color
 
c = Car("Audi ",  "r8", " Red")
print("Car description:", c.get_description())
print("Brand name:", c.get_brand_name())

When we run the above program we get following output:

When we run the above program we get following output:

Car description: Car Name: Audi r8 Color: Red
Brand name: Audi

Multiple Inheritance: (Multiple Inheritance:)

When a class inherits the method and attributes from multiple parent class then it is called multiple inheritance. This allows us to use the property from multiple base classes or parent classes in a derived or child class.

When a class inherits the method and attributes from multiple parent class then it is called multiple inheritance. This allows us to use the property from multiple base classes or parent classes in a derived or child class.

The general syntax of multiple Inheritance is as follows:

The general syntax of multiple Inheritance is as follows:

class DerivedClassName(Base1, Base2, Base3):
    <statement-1>
    .
    .
    .
    <statement-N>

Let’s extend our vehicle example using the multiple inheritance property. Here in this example, we will create 3 classes i.e. Vehicle, Cost and Car

Let's extend our vehicle example using the multiple inheritance property. Here in this example, we will create 3 classes ie Vehicle , Cost and Car

The classes Vehicle and Cost will be the Parent class. A Vehicle class represents the general property while the Cost class represents its pricing.

The classes Vehicle and Cost will be the Parent class. A Vehicle class represents the general property while the Cost class represents its pricing.

As Car has a general property and cost will have two parent classes. Thus we will inherit multiple parent classes.

As Car has a general property and cost will have two parent classes. Thus we will inherit multiple parent classes.

class Vehicle:

    def __init__(self, brand_name):
        self.brand_name = brand_name
    
    def get_brand_name(self):
        return self.brand_name


class Cost:		

    def __init__(self, cost):
        self.cost = cost
    
    def get_cost(self):
        return self.cost

 
class Car(Vehicle, Cost):	

    def __init__(self, brand_name, model, cost): 
        self.model = model 
        Vehicle.__init__(self, brand_name) 
        Cost.__init__(self, cost) 

    def get_description(self):
        return self.get_brand_name() + self.model + " is the car " + "and it's cost is " + self.get_cost()
		
c = Car("Audi ",  "r8", "2 cr")
print("Car description:", c.get_description())

Here you will find one thing in the above program that is different from all the other programs in this tutorial. I have used Vehicle.__init__(self, brand_name) in the constructor of Car class. This is one way of calling attributes from the parent class. Another was is super which I have explained above.

Here you will find one thing in the above program that is different from all the other programs in this tutorial. I have used Vehicle.__init__(self, brand_name) in the constructor of Car class. This is one way of calling attributes from the parent class. Another was is super which I have explained above.

When we run the above program we will get the following output:

When we run the above program we will get the following output:

Car description: Audi r8 is the car and it's cost is 2 cr

Though it can be used effectively, multiple inheritance should be done with care so that our programs do not become ambiguous and difficult for other programmers to understand.

Though it can be used effectively, multiple inheritance should be done with care so that our programs do not become ambiguous and difficult for other programmers to understand.

Polymorphism: (Polymorphism:)

The word polymorphism means having many forms. In programming, polymorphism means same function name (but different signatures) being uses for different types.

The word polymorphism means having many forms. In programming, polymorphism means same function name (but different signatures) being uses for different types.

Let’s extend our car program using polymorphism. We will create two classes, Car and Bike. Both the classes have common method or function, but they are printing different data. The program is pretty self-explanatory:

Let's extend our car program using polymorphism. We will create two classes, Car and Bike . Both the classes have common method or function, but they are printing different data. The program is pretty self-explanatory:

class Car: 

    def company(self): 
        print("Car belongs to Audi company.")
   
    def model(self): 
        print("The Model is R8.") 
   
    def color(self): 
        print("The color is silver.") 
   
class Bike: 

    def company(self): 
        print("Bike belongs to pulsar company.") 
   
    def model(self): 
        print("The Model is dominar.") 
   
    def color(self): 
        print("The color is black.") 
  
def func(obj): 
    obj.company() 
    obj.model() 
    obj.color() 
   
car = Car() 
bike = Bike() 
   
func(car) 
func(bike)

When we run the above code we will get the following output:

When we run the above code we will get the following output:

Car belongs to Audi company.
The Model is R8.
The color is silver.
Bike belongs to pulsar company.
The Model is dominar.
The color is black.

Encapsulation: (Encapsulation:)

In most object-oriented programming, we can restrict access to methods and variables. This can prevent the data from being modified by accident and is known as encapsulation.

In most object-oriented programming, we can restrict access to methods and variables. This can prevent the data from being modified by accident and is known as encapsulation.

Let’s use encapsulation in our car example. Now imagine we have a super-secret engine. In the first example, we will hide our engine using a private variable. In the second example, we will hide our engine using a private method.

Let's use encapsulation in our car example. Now imagine we have a super-secret engine. In the first example, we will hide our engine using a private variable . In the second example, we will hide our engine using a private method .

Example 1:

Example 1:

class Car:

  def __init__(self): 
    self.brand_name = 'Audi '
    self.model = 'r8'
    self.__engine = '5.2 L V10'
    
  def get_description(self):
        return self.brand_name + self.model + " is the car"
  
c = Car()
print(c.get_description)
print(c.__engine)

In this example self.__engine is a private attribute. When we run this program we will get the following output.

In this example self.__engine is a private attribute. When we run this program we will get the following output.

Audi r8 is the car
AttributeError: 'Car' object has no attribute '__engine'

We get an error that Car object doesn't have _engine because it is a private object.

We get an error that Car object doesn't have _engine because it is a private object.

Example 2:

Example 2:

We can also define a private method by adding __ in front of the method name. Following is the example of how we can define a private method.

We can also define a private method by adding __ in front of the method name. Following is the example of how we can define a private method.

class Car:

  def __init__(self):
      self.brand_name = 'Audi '
      self.model = 'r8'

  def __engine(self):
      return '5.2 L V10'

  def get_description(self):
      return self.brand_name + self.model + " is the car"
    
    
c = Car()
print(c.get_description())
print(c.__engine())

In this example def __engine(self) is a private method. When we run this program we will get the following output.

In this example def __engine(self) is a private method. When we run this program we will get the following output.

Audi r8 is the car
AttributeError: 'Car' object has no attribute '__engine'

Now suppose we want to access the private attribute or method we can do it in the following way:

Now suppose we want to access the private attribute or method we can do it in the following way:

class Car:

  def __init__(self):
      self.brand_name = 'Audi '
      self.model = 'r8'
      self.__engine_name = '5.2 L V10'

  def __engine(self):
      return '5.2 L V10'

  def get_description(self):
      return self.brand_name + self.model + " is the car"
    
    
c = Car()
print(c.get_description())
print("Accessing Private Method: ", c._Car__engine()) 
print("Accessing Private variable: ", c._Car__engine_name)

The output of the following program is:

The output of the following program is:

Audi r8 is the car
Accessing Private Method:  5.2 L V10
Accessing Private variable:  5.2 L V10

Encapsulation gives you more control over the degree of coupling in your code. It allows a class to change its implementation without affecting other parts of the code.

Encapsulation gives you more control over the degree of coupling in your code. It allows a class to change its implementation without affecting other parts of the code.

Decorator: (Decorator:)

Imagine you have to extend the functionality of multiple functions. How will you do that?

Imagine you have to extend the functionality of multiple functions. 你会怎么做?

Well, one way is you can make functional calls and in that function, you can handle it. Making changes in 30 to 40 function calls and remembering where to place the call is a messy task. But the more elegant way provided by Python is with decorators.

Well, one way is you can make functional calls and in that function, you can handle it. Making changes in 30 to 40 function calls and remembering where to place the call is a messy task. But the more elegant way provided by Python is with decorators.

What is a decorator? A decorator is a function that takes a function and extends its functionality without modifying it explicitly. Well, I understand if you are still confused about what decorators are. Don't worry – we have a tool named example to explain it.

What is a decorator? A decorator is a function that takes a function and extends its functionality without modifying it explicitly. Well, I understand if you are still confused about what decorators are. Don't worry – we have a tool named example to explain it.

Let's try an example to understand the decorator. There are two ways to write a decorator.

Let's try an example to understand the decorator. There are two ways to write a decorator.

Method 1 (Method 1)

We declare a decorator function and in the arguments of the function we expect the function to be passed as an argument. Inside that, we write a wrapper function where operations are carried out and it is returned.

We declare a decorator function and in the arguments of the function we expect the function to be passed as an argument. Inside that, we write a wrapper function where operations are carried out and it is returned.

>>> def my_decorator(func):
...     def wrapper():
...             print("Line Number 1")
...             func()
...             print("Line Number 3")
...     return wrapper
...
>>> def say_hello():
...     print("Hello I am line Number 2")
...

To call the function we assign the decorator with say_hello as an argument.

To call the function we assign the decorator with say_hello as an argument.

>>> say_hello = my_decorator(say_hello)

We can also check the reference using say_hello. We will get the output that tells us it has been wrapped by the my_decorator function.

We can also check the reference using say_hello . We will get the output that tells us it has been wrapped by the my_decorator function.

<function my_decorator.<locals>.wrapper at 0x10dc84598>

Let's call our say_hello function:

Let's call our say_hello function:

>>> say_hello()
Line Number 1
Hello I am line Number 2
Line Number 3

See the magic the line "Hello I am line Number 2" gets printed in between Line Number 1 and 3 because the function call gets executed there.

See the magic the line "Hello I am line Number 2" gets printed in between Line Number 1 and 3 because the function call gets executed there.

Method 1 is clunky, and because of that many people prefer a different approach.

Method 1 is clunky, and because of that many people prefer a different approach.

Method 2 (Method 2)

Here our decorator declaration remains same but we change how the call is assigned to that decorator. Whichever function requires that decorator wraps itself with @decorator_name.

Here our decorator declaration remains same but we change how the call is assigned to that decorator. Whichever function requires that decorator wraps itself with @decorator_name .

>>> def my_decorator(func):
...     def wrapper():
...             print("Line Number 1")
...             func()
...             print("Line Number 3")
...     return wrapper
...
>>> @my_decorator
... def say_hello():
...     print("Hello I am line Number 2")
...
>>> say_hello()

Output is the same:

Output is the same:

Line Number 1
Hello I am line Number 2
Line Number 3

A decorator is a powerful tool and it is used in the following development scenarios of an application:

A decorator is a powerful tool and it is used in the following development scenarios of an application:

  • Setup logger

    Setup logger
  • Setup configuration

    Setup configuration
  • Setup Error catching

    Setup Error catching
  • Extending common functionality for all function and classes

    Extending common functionality for all function and classes

例外情况: (Exceptions:)

When we were learning various syntax we came across various errors. Those errors occurred because of the syntax. But in a real-world application, errors (or commonly known as bugs) not only occur due to syntax issues but also because of network errors or some other cause.

When we were learning various syntax we came across various errors. Those errors occurred because of the syntax. But in a real-world application, errors (or commonly known as bugs) not only occur due to syntax issues but also because of network errors or some other cause.

To handle these issues we use Try - Except. In try block, we write the expression that we want to be executed, while in except block we catch the error. The Try-Except block looks as follows:

To handle these issues we use Try - Except. In try block, we write the expression that we want to be executed, while in except block we catch the error. The Try-Except block looks as follows:

try:
	expression
except:
	catch error

Let's understand this by an example:

Let's understand this by an example:

>>> try:
...     print(value)
... except:
...     print("Something went wrong")
...

Here we are trying to print the value variable but it is not defined. So we get the following output:

Here we are trying to print the value variable but it is not defined. So we get the following output:

Something went wrong

You may be thinking that the line "something went wrong" is not that helpful. So how can we know what went wrong here?

You may be thinking that the line "something went wrong" is not that helpful. So how can we know what went wrong here?

We can print the exception and use it to find out what went wrong. Let's test this in our example:

We can print the exception and use it to find out what went wrong. Let's test this in our example:

>>> try:
...     print(value)
... except Exception as e:
...     print(e)
...

And the result is:

结果是:

name 'value' is not defined

Whoa! That's magic. It is notifying me that 'value' is not defined.

哇! 太神奇了。 It is notifying me that 'value' is not defined.

Python also provides a tool named raise. Suppose you don't want a certain condition to occur and if it occurs you want to raise it. In such condition you can use raise. Consider the example below:

Python also provides a tool named raise . Suppose you don't want a certain condition to occur and if it occurs you want to raise it. In such condition you can use raise . Consider the example below:

>>> i = 5
>>> if i < 6:
...     raise Exception("Number below 6 are not allowed")
...

The output we get is as follows:

The output we get is as follows:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
Exception: Number below 6 are not allowed

There are many sub-types of Exceptions, so I recommend that you go through the Python Documentation to understand them.

There are many sub-types of Exceptions, so I recommend that you go through the Python Documentation to understand them.

Package Import: (Package Import:)

You have learned the basics of Python and now you are all ready to build awesome applications. But hold on – we are still missing some important topics.

You have learned the basics of Python and now you are all ready to build awesome applications. But hold on – we are still missing some important topics.

Without package import, you will be forced to write everything in one single file. Imagine what a mess it will be.

Without package import, you will be forced to write everything in one single file. Imagine what a mess it will be.

Create two files named main.py and hello.py. Remember both file needs to be in the same directory.

Create two files named main.py and hello.py . Remember both file needs to be in the same directory.

Under hello.py copy paste the following code:

Under hello.py copy paste the following code:

def say_hello():
    print("Hello world")

Under main.py copy paste the following code:

Under main.py copy paste the following code:

import hello

if __name__ == "__main__":
    hello.say_hello()

In hello.py we have declared a say_hello() function which prints "Hello world". In main.py you'll see an import statement. We are importing the hello module and calling the say_hello() function from that module.

In hello.py we have declared a say_hello() function which prints "Hello world". In main.py you'll see an import statement. We are importing the hello module and calling the say_hello() function from that module.

Run our program using the following command:

Run our program using the following command:

➜ python main.py

Output:

输出:

Hello world

Now let's understand how to import a module which is in another directory.

Now let's understand how to import a module which is in another directory.

Let's create a directory named "data" and move our hello.py inside that directory.

Let's create a directory named "data" and move our hello.py inside that directory.

Go to the main.py and change the previous import statement.

Go to the main.py and change the previous import statement.

from data import hello

if __name__ == "__main__":
    hello.say_hello()

There are two ways to import from a directory.

There are two ways to import from a directory.

  • Method 1: from data import hello

    Method 1: from data import hello

  • Method 2: import data.hello

    Method 2: import data.hello

I prefer method 1 because of its readability. You can choose whichever method looks better to you.

I prefer method 1 because of its readability. You can choose whichever method looks better to you.

Let's run our application using the following command:

Let's run our application using the following command:

➜ python main.py

And an error occurs. Wait why did this happen? We did everything right. Let's go through the error:

And an error occurs. Wait why did this happen? We did everything right. Let's go through the error:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    from data import hello
ImportError: No module named data

Well Python is telling us that it doesn't recognize a module named data. To solve this issue create a __init__.py inside data directory. Leave the file blank and run the program again and you'll get the following output:

Well Python is telling us that it doesn't recognize a module named data. To solve this issue create a __init__.py inside data directory. Leave the file blank and run the program again and you'll get the following output:

Hello world

Well python by default does not treat a directory as a module. To inform Python to treat a directory as a module, __init__.py is required.

Well python by default does not treat a directory as a module. To inform Python to treat a directory as a module, __init__.py is required.

JSON Handling: (JSON Handling:)

If you have worked previously with web development or app development you may be aware that all the API calls take place in JSON format. While JSON looks similar to a dictionary in Python, remember that it's very different.

If you have worked previously with web development or app development you may be aware that all the API calls take place in JSON format. While JSON looks similar to a dictionary in Python, remember that it's very different.

To handle JSON, Python provides an inbuilt json package. To use this package we need to import it as follows:

To handle JSON, Python provides an inbuilt json package. To use this package we need to import it as follows:

import json

This library provides two methods which help us in handling the JSON. Let's understand them one by one.

This library provides two methods which help us in handling the JSON. Let's understand them one by one.

JSON loads: (JSON loads:)

If you have a JSON string and want to convert it back to a dictionary you need to use the loads method. Go to the Python shell and copy-paste the following code:

If you have a JSON string and want to convert it back to a dictionary you need to use the loads method. Go to the Python shell and copy-paste the following code:

>>> import json
>>> json_string = '{ "user_name":"Sharvin", "age":1000}' #JSON String
>>> type(json_string)
<class 'str'>
>>> data = json.loads(json_string)
>>> type(data)
<class 'dict'>
>>> data
{'user_name': 'Sharvin', 'age': 1000}

JSON dumps: (JSON dumps:)

Now let's convert our data back to the JSON string format using the dumps method.

Now let's convert our data back to the JSON string format using the dumps method.

>>> jsonString = json.dumps(data)
>>> type(jsonString)
<class 'str'>
>>> jsonString
'{"user_name": "Sharvin", "age": 1000}'

To learn more about JSON Manipulation, go through the Python Documentation.

To learn more about JSON Manipulation, go through the Python Documentation .

而已! (That's it!)

And we're done! I hope you now understand the basics of Python. Congratulations! That's a huge achievement.

我们完成了! I hope you now understand the basics of Python. 恭喜你! That's a huge achievement.

Feedback is welcomed. Also if you want to learn about any other topic you can tweet the topic name on Twitter and include my Twitter handle. [ @sharvinshah26 ]

Feedback is welcomed. Also if you want to learn about any other topic you can tweet the topic name on Twitter and include my Twitter handle. [ @sharvinshah26 ]

Feel free to connect with me on Twitter and Github.

随时在TwitterGithub上与我联系。

翻译自: https://www.freecodecamp.org/news/the-ultimate-guide-to-python-from-beginner-to-intermediate-to-pro/

python入门指南

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:编程工作室 设计师:CSDN官方博客 返回首页
评论
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值