python初學者_終極Python初學者手冊

python初學者

Python has become one of the fastest-growing programming languages over the past few years.

在過去的幾年中,Python已成為增長最快的編程語言之一。

Not only it is widely used, it is also an awesome language to tackle if you want to get into the world of programming.

如果您想進入編程世界,它不僅被廣泛使用,而且還是一種很棒的語言。

This Python Guide for Beginners allows you to learn the core of the language in a matter of hours instead of weeks.

這份Python初學者指南可讓您在數小時而不是數周的時間內學習該語言的核心。

Quick info: You can download a PDF version of this Python Guide for Beginners.

快速信息: 您可以下載此Python初學者指南的PDF版本 。

Ready to dive in?

準備潛水了嗎?

目錄 (Table of contents)

  1. Introduction to Python

    Python簡介

  2. Installing Python 3

    安裝Python 3

  3. Running Code

    運行代碼

  4. Syntax

    句法

  5. Comments

    注釋

  6. Variables

    變數

  7. Types

    種類

  8. Typecasting

    類型轉換

  9. User Input

    用戶輸入

  10. Operators

    經營者

  11. Conditionals

    有條件的

  12. Lists

    清單

  13. Tuples

    元組

  14. Sets

    套裝

  15. Dictionaries

    辭典

  16. while Loops

    while循環

  17. for Loops

    循環

  18. Functions

    功能

  19. Scope

    范圍

  20. List Comprehensions

    清單理解

  21. Lambda Functions

    Lambda函數

  22. Modules

    模組

  23. if name == 'main'

    如果name ==' main '

  24. Files

    檔案

  25. Classes and Objects

    類和對象

  26. Inheritance

    遺產

  27. Exceptions

    例外情況

  28. Conclusion

    結論

Python簡介 (Introduction to Python)

Python was created in 1990 by Guido van Rossum in Holland.

Python由荷蘭的Guido van Rossum于1990年創建。

One of the objectives of the language was to be accessible to non-programmers.

該語言的目標之一是非程序員可以使用。

Python was also designed to be a second language for programmers to learn due to its low learning curve and ease of use.

由于Python的學習曲線較低且易于使用,因此它也被設計為程序員學習的第二語言。

Python runs on Mac, Linux, Windows, and many other platforms.

Python可在Mac,Linux,Windows和許多其他平臺上運行。

Python is:

Python是:

  • Interpreted: it can execute at runtime, and changes in a program are instantly perceptible. To be very technical, Python has a compiler. The difference when compared to Java or C++ is how transparent and automatic it is. With Python, we don't have to worry about the compilation step as it's done in real-time. The tradeoff is that interpreted languages are usually slower than compiled ones.

    解釋:它可以在運行時執行,并且程序中的更改立即可見。 從技術上講,Python有一個編譯器。 與Java或C ++相比,區別在于它的透明性和自動性。 使用Python,我們不必擔心編譯步驟,因為它是實時完成的。 折衷是解釋型語言通常比編譯型語言慢。

  • Semantically Dynamic: you don't have to specify types for variables and there is nothing that makes you do it.

    語義動態:您不必為變量指定類型,也沒有什么可以使您做到這一點。

  • Object-Oriented: everything in Python is an object. But you can choose to write code in an object-oriented, procedural, or even functional way.

    面向對象:Python中的一切都是對象。 但是您可以選擇以面向對象,過程甚至功能的方式編寫代碼。

  • High level: you don't have to deal with low-level machine details.

    高級別:您不必處理低級別的計算機詳細信息。

Python has been growing a lot recently partly because of its many uses in the following areas:

Python最近得到了長足的發展,部分原因是它在以下領域的許多用途:

  • System scripting: it's a great tool to automate everyday repetitive tasks.

    系統腳本:這是自動化日常重復任務的好工具。

  • Data Analysis: it is a great language to experiment with and has tons of libraries and tools to handle data, create models, visualize results and even deploy solutions. This is used in areas like Finance, E-commerce, and Research.

    數據分析:這是一種很棒的語言,可以進行試驗,并擁有大量的庫和工具來處理數據,創建模型,可視化結果甚至部署解決方案。 它用于金融,電子商務和研究等領域。

  • Web Development: frameworks like Django and Flask allow the development of web applications, API's, and websites.

    Web開發:Django和Flask之類的框架允許開發Web應用程序,API和網站。

  • Machine Learning: Tensorflow and Pytorch are some of the libraries that allow scientists and the industry to develop and deploy Artificial Intelligence solutions in Image Recognition, Health, Self-driving cars, and many other fields.

    機器學習:Tensorflow和Pytorch是一些庫,可讓科學家和業界在圖像識別,健康,自動駕駛汽車和許多其他領域中開發和部署人工智能解決方案。

You can easily organize your code in modules and reuse them or share them with others.

您可以輕松地在模塊中組織代碼,然后重復使用或與他人共享。

Finally, we have to keep in mind that Python had breaking changes between versions 2 and 3. And since Python 2 support ended in 2020, this article is solely based on Python 3.

最后,我們必須記住,Python在版本2和版本3之間進行了重大更改。由于Python 2支持在2020年結束,因此本文僅基于Python 3。

So let's get started.

因此,讓我們開始吧。

安裝Python 3 (Installing Python 3)

If you use a Mac or Linux you already have Python installed. But Windows doesn't come with Python installed by default.

如果您使用Mac或Linux,則已經安裝了Python。 但是Windows默認沒有安裝Python。

You also might have Python 2, and we are going to use Python 3. So you should check to see if you have Python 3 first.

您可能還擁有Python 2,我們將使用Python3。因此,您應該檢查一下是否首先擁有Python 3。

Type the following in your terminal.

在終端中鍵入以下內容。

python3 -V

Notice the uppercase V.

注意大寫的V

If your result is something similar to 'Python 3.x.y', for instance, Python 3.8.1, then you are ready to go.

如果您的結果類似于“ Python 3.x.y”(例如Python 3.8.1 ,則可以開始使用了。

If not, follow the next instructions according to your Operating System.

如果不是,請根據您的操作系統按照以下說明進行操作。

在Windows上安裝Python 3 (Installing Python 3 on Windows)

Go to https://www.python.org/downloads/.

前往https://www.python.org/downloads/ 。

Download the latest version.

下載最新版本。

After the download, double-click the installer.

下載后,雙擊安裝程序。

On the first screen, check the box indicating to "Add Python 3.x to PATH" and then click on "Install Now".

在第一個屏幕上,選中指示“將Python 3.x添加到PATH”的框,然后單擊“立即安裝”。

Wait for the installation process to finish until the next screen with the message "Setup was successful".

等待安裝過程完成,直到出現下一個屏幕,提示“安裝成功”。

Click on "Close".

點擊“關閉”。

在Mac上安裝Python 3 (Installing Python 3 on Mac)

Install XCode from the App Store.

從App Store安裝XCode 。

Install the command line tools by running the following in your terminal.

通過在終端中運行以下命令來安裝命令行工具。

xcode-select --install

I recommend using Homebrew. Go to https://brew.sh/ and follow the instructions on the first page to install it.

我建議使用自制軟件。 轉到https://brew.sh/并按照第一頁上的說明進行安裝。

After installing Homebrew, run the following brew commands to install Python 3.

安裝Homebrew后,運行以下brew命令以安裝Python 3。

brew update
brew install python3

Homebrew already adds Python 3 to the PATH, so you don't have to do anything else.

Homebrew已經將Python 3添加到PATH中,因此您無需執行其他任何操作。

在Linux上安裝Python 3 (Installing Python 3 on Linux)

To install using apt, available in Ubuntu and Debian, enter the following:

要使用Ubuntu和Debian中可用的apt安裝,請輸入以下內容:

sudo apt install python3

To install using yum, available in RedHat and CentOS, enter the following:

要使用RedHat和CentOS中可用的yum安裝,請輸入以下內容:

sudo yum install python3

運行代碼 (Running Code)

You can run Python code directly in the terminal as commands or you can save the code in a file with the .py extension and run the Python file.

您可以直接在終端中將Python代碼作為命令運行,也可以將代碼保存在擴展名為.py的文件中并運行Python文件。

終奌站 (Terminal)

Running commands directly in the terminal is recommended when you want to run something simple.

如果要運行簡單的命令,建議直接在終端中運行命令。

Open the command line and type python3

打開命令行并輸入python3

renan@mypc:~$ python3

You should see something like this in your terminal indicating the version (in my case, Python 3.6.9), the operating system (I'm using Linux), and some basic commands to help you.

您應該在終端上看到類似這樣的信息,其中指出了版本(在我的情況下為Python 3.6.9),操作系統(我正在使用Linux)以及一些基本命令可以為您提供幫助。

The >>> tells us we are in the Python console.

>>>告訴我們我們在Python控制臺中。

Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Let's test it by running our first program to perform basic math and add two numbers.

讓我們通過運行第一個程序執行基本數學運算并加兩個數字來對其進行測試。

>>> 2 + 2

The output is:

輸出為:

4

To exit the Python console simply type exit().

要退出Python控制臺,只需鍵入exit()

>>> exit()

運行.py文件 (Running .py files)

If you have a complex program, with many lines of code, the Python console isn't the best option.

如果您有一個復雜的程序且包含許多代碼行,那么Python控制臺不是最佳選擇。

The alternative is simply to open a text editor, type the code, and save the file with a .py extension.

另一種方法是簡單地打開文本編輯器,鍵入代碼,然后以.py擴展名保存文件。

Let's do that, create a file called second_program.py with the following content.

為此,創建一個包含以下內容的文件second_program.py

print('Second Program')

The print() function prints a message on the screen.

print()函數在屏幕上打印一條消息。

The message goes inside the parentheses with either single quotes or double quotes, both work the same.

該消息用單引號或雙引號括在括號內,二者的作用相同。

To run the program, on your terminal do the following:

要運行該程序,請在您的終端上執行以下操作:

renan@mypc:~$ python3 second_program.py

The output is:

輸出為:

Second Program

句法 (Syntax)

Python is known for its clean syntax.

Python以其干凈的語法而聞名。

The language avoids using unnecessary characters to indicate some specificity.

該語言避免使用不必要的字符來表示某些特定性。

分號 (Semicolons)

Python doesn't use semicolons to finish lines. A new line is enough to tell the interpreter that a new command is beginning.

Python不使用分號來結束行。 換行足以告知解釋器新命令正在開始。

The print() method will display something.

print()方法將顯示某些內容。

In this example, we have two commands that will display the messages inside the single quotes.

在此示例中,我們有兩個命令將在單引號內顯示??消息。

print('First command')
print('Second command')

Output:

輸出:

First command
Second command

But the following is wrong due to the semicolons in the end:

但是由于最后的分號,以下是錯誤的:

print('First command');
print('Second command');

縮進 (Indentation)

Many languages use curly-brackets to define scope.

許多語言使用花括號來定義范圍。

Python's interpreter uses only indentation to define when a scope ends and another one starts.

Python的解釋器僅使用縮進來定義范圍的結束時間和另一個范圍的開始時間。

This means you have to be aware of white spaces at the beginning of each line -- they have meaning and might break your code if misplaced.

這意味著您必須注意每行開頭的空格-它們具有含義,如果放錯位置,可能會破壞您的代碼。

This definition of a function works:

這個函數的定義起作用:

def my_function():print('First command')

This doesn't work because the indentation of the second line is missing and will throw an error:

不起作用,因為缺少第二行的縮進,將引發錯誤:

def my_function():
print('First command')

區分大小寫和變量 (Case sensitivity and variables)

Python is case sensitive. So the variables name and Name are not the same thing and store different values.

Python區分大小寫。 因此,變量nameName不是同一件事,并且存儲不同的值。

name = 'Renan'
Name = 'Moura'

As you can see, variables are easily created by just assigning values to them using the = symbol.

如您所見,只需使用=符號為變量賦值即可輕松創建變量。

This means name stores 'Renan' and Name stores 'Moura'.

這意味著name存儲“ Renan”和Name存儲“ Moura”。

注釋 (Comments)

Finally, to comment something in your code, use the hash mark #.

最后,要在代碼中添加注釋,請使用井號#

The commented part does not influence the program flow.

注釋的部分不會影響程序流程。

# this function prints something
def my_function():print('First command')

This was just an overview. The details of each of these will become clearer in the next chapters with examples and broader explanations.

這只是一個概述。 在下面的章節中,將通過示例和更廣泛的解釋使這些內容的細節變得更加清晰。

注釋 (Comments)

The purpose of comments is to explain what is happening in the code.

注釋的目的是解釋代碼中正在發生的事情。

Comments are written along with your code but do not influence your program flow.

注釋與您的代碼一起編寫,但不會影響您的程序流程。

When you work by yourself, maybe comments don't feel like something you should write. After all, at the moment, you know the whys of every single line of code.

當您自己工作時,注釋可能不適合您編寫。 畢竟,您現在知道每一行代碼的原因。

But what if new people come on board your project after a year and the project has 3 modules, each with 10,000 lines of code?

但是,如果一年后有新人加入您的項目,并且該項目有3個模塊,每個模塊有10,000行代碼,該怎么辦?

Think about people who don't know a thing about your app and who are suddenly having to maintain it, fix it, or add new features.

考慮一下那些對您的應用一無所知的人,而這些人突然不得不維護,修復或添加新功能。

Remember, there is no single solution for a given problem. Your way of solving things is yours and yours only. If you ask 10 people to solve the same problem, they will come up with 10 different solutions.

請記住,對于給定的問題,沒有單一的解決方案。 您解決問題的方式僅屬于您自己。 如果您要求10個人解決同一問題,他們將提出10種不同的解決方案。

If you want others to fully understand your reasoning, good code design is mandatory, but comments are an integral part of any codebase.

如果您希望其他人完全理解您的推理,則必須進行良好的代碼設計,但是注釋是任何代碼庫的組成部分。

如何用Python編寫注釋 (How to Write Comments in Python)

The syntax of comments in Python is rather easy: just use the hash mark # symbol in front of the text you want to be a comment.

Python中注釋的語法非常簡單:只需在要注釋的文本前面使用井號#符號即可。

#This is a comment and it won't influence my program flow

You can use a comment to explain what some piece of code does.

您可以使用注釋來解釋某些代碼的作用。

#calculates the sum of any given two numbers
a + b

多行注釋 (Multiline Comments)

Maybe you want to comment on something very complex or describe how some process works in your code.

也許您想評論一些非常復雜的東西,或者描述某些過程在代碼中的工作方式。

In these cases, you can use multiline comments.

在這些情況下,您可以使用多行注釋。

To do that, just use a single hash mark # for each line.

為此,只需為每行使用一個井號#

#Everything after the hash mark # is a comment
#This is a comment and it won't influence my program flow#Calculates the cost of the project given variables a and b
#a is the time in months it will take until the project is finished
#b is how much money it will cost per month
a + b * 10

變數 (Variables)

In any program, you need to store and manipulate data to create a flow or some specific logic.

在任何程序中,都需要存儲和操作數據以創建流或某些特定邏輯。

That's what variables are for.

這就是變量的用途。

You can have a variable to store a name, another one to store the age of a person, or even use a more complex type to store all of this at once like a dictionary.

您可以使用一個變量來存儲名稱,使用另一個變量來存儲人的年齡,甚至可以使用更復雜的類型像字典一樣一次存儲所有這些變量。

創建,也稱為聲明 (Creating, also known as Declaring)

Declaring a variable is a basic and straightforward operation in Python

聲明變量是Python中基本而直接的操作

Just pick a name and attribute a value to it using the = symbol.

只需選擇一個名稱,然后使用=符號為其賦予一個值。

name='Bob'age=32

You can use the print() function to show the value of a variable.

您可以使用print()函數顯示變量的值。

print(name)print(age)
Bob32

Notice that in Python there is no special word to declare a variable.

請注意,在Python中,沒有特殊的詞來聲明變量。

The moment you assign a value, the variable is created in memory.

分配值后,將在內存中創建變量。

Python also has dynamic typing, which means you don't have to tell it if your variable is a text or a number, for instance.

Python還具有動態類型,這意味著您不必告訴它變量是文本還是數字。

The interpreter infers the typing based on the value assigned.

解釋器根據分配的值推斷類型。

If you need it, you can also re-declare a variable just by changing its value.

如果需要,也可以僅通過更改其值來重新聲明該變量。

#declaring name as a string
name='Bob'
#re-declaring name as an int
name = 32

Keep in my mind, though, that this is not recommended since variables must have meaning and context.

但是請記住,不建議這樣做,因為變量必須具有含義和上下文。

If I have a variable called name I don't expect it to have a number stored in it.

如果我有一個名為name的變量,我不希望它中存儲有數字。

命名約定 (Naming Conventions)

Let's continue from the last section when I talked about meaning and context.

讓我們從上一節繼續講起意義和上下文。

Don't use random variable names like x or y.

不要使用xy這樣的隨機變量名。

Say you want to store the time of a party, just call it party_time.

假設您要存儲聚會的時間,只需將其party_time

Oh, did you notice the underscore _?

哦,您注意到下劃線_嗎?

By convention, if you want to use a variable name that is composed of two or more words, you separate them by underscores. This is called Snake Case.

按照慣例,如果要使用由兩個或多個單詞組成的變量名,請用下劃線將它們分開。 這就是所謂的蛇案。

Another option would be using CamelCase as in partyTime. This is very common in other languages, but not the convention in Python as stated before.

另一種選擇是在partyTime使用CamelCase。 這在其他語言中非常常見,但不是前面提到的Python中的約定。

Variables are case sensitive, so party_time and Party_time are not the same. Also, keep in mind that the convention tells us to always use lower case.

變量區分大小寫,因此party_timeParty_time不相同。 另外,請記住,約定告訴我們始終使用小寫字母。

Remember, use names that you can recall inside your program easily. Bad naming can cost you a lot of time and cause annoying bugs.

請記住,使用可以在程序中輕松調用的名稱。 不好的命名會花費您很多時間,并導致令人討厭的錯誤。

In summary, variable names:

總之,變量名:

  • Are Case sensitive: time and TIME are not the same

    區分大小寫: timeTIME不同

  • Have to start with an underscore _ or a letter (DO NOT start with a number)

    必須以下劃線_或字母開頭(請勿以數字開頭)

  • Are allowed to have only numbers, letters and underscores. No special characters like: #, $, &, @, etc.

    只能包含數字,字母和下劃線。 沒有特殊字符,例如#,$,&,@等。

This, for instance, is not allowed: party#time, 10partytime.

這一點,例如,是不允許的: party#time10partytime

種類 (Types)

To store data in Python you need to use a variable. And every variable has its type depending on the value of the data stored.

要在Python中存儲數據,您需要使用一個變量。 每個變量的類型取決于存儲的數據的值。

Python has dynamic typing, which means you don't have to explicitly declare the type of your variable -- but if you want to, you can.

Python具有動態類型,這意味著您不必顯式聲明變量的類型-但如果愿意,可以。

Lists, Tuples, Sets, and Dictionaries are all data types and have dedicated sections later on with more details, but we'll look at them briefly here.

列表,元組,集合和字典都是數據類型,稍后將在專用部分中提供更多詳細信息,但我們將在此處對其進行簡要介紹。

This way I can show you the most important aspects and operations of each one in their own section while keeping this section more concise and focused on giving you a broad view of the main data types in Python.

這樣,我可以在各自的部分中向您展示每個部分的最重要方面和操作,同時使本部分更加簡潔,并專注于為您提供Python主要數據類型的廣泛視圖。

確定類型 (Determining the Type)

First of all, let's learn how to determine the data type.

首先,讓我們學習如何確定數據類型。

Just use the type() function and pass the variable of your choice as an argument, like the example below.

只需使用type()函數并將您選擇的變量作為參數傳遞,就像下面的示例一樣。

print(type(my_variable))

布爾型 (Boolean)

The boolean type is one of the most basic types of programming.

布爾類型是最基本的編程類型之一。

A boolean type variable can only represent either True or False.

布爾類型變量只能表示TrueFalse

my_bool = True
print(type(my_bool))my_bool = bool(1024)
print(type(my_bool))
<class 'bool'>
<class 'bool'>

號碼 (Numbers)

There are three types of numeric types: int, float, and complex.

共有三種類型的數字類型:int,float和complex。

整數 (Integer)

my_int = 32
print(type(my_int))my_int = int(32)
print(type(my_int))
<class 'int'>
<class 'int'>

浮動 (Float)

my_float = 32.85
print(type(my_float))my_float = float(32.85)
print(type(my_float))
<class 'float'>
<class 'float'>

復雜 (Complex)

my_complex_number = 32+4j
print(type(my_complex_number))my_complex_number = complex(32+4j)
print(type(my_complex_number))
<class 'complex'>
<class 'complex'>

(String)

The text type is one of the most commons types out there and is often called string or, in Python, just str.

文本類型是最常見的類型之一,通常稱為字符串,或者在Python中僅稱為str

my_city = "New York"
print(type(my_city))#Single quotes have exactly
#the same use as double quotes
my_city = 'New York'
print(type(my_city))#Setting the variable type explicitly
my_city = str("New York")
print(type(my_city))
<class 'str'>
<class 'str'>
<class 'str'>

You can use the + operator to concatenate strings.

您可以使用+運算符來連接字符串。

Concatenation is when you have two or more strings and you want to join them into one.

串聯是指當您有兩個或多個字符串并且想要將它們連接成一個字符串時。

word1 = 'New '
word2 = 'York'print(word1 + word2)
New York

The string type has many built-in methods that let us manipulate them. I will demonstrate how some of these methods work.

字符串類型具有許多內置方法,可讓我們對其進行操作。 我將演示其中一些方法的工作原理。

The len() function returns the length of a string.

len()函數返回字符串的長度。

print(len('New York'))
8

The replace() method replaces a part of the string with another. As an example, let's replace 'New' for 'Old'.

replace()方法將字符串的一部分替換為另一部分。 例如,讓我們用“舊”替換“新”。

print('New York'.replace('New', 'Old'))
Old York

The upper() method will return all characters as uppercase.

upper()方法將以大寫形式返回所有字符。

print('New York'.upper())
NEW YORK

The lower() method does the opposite, and returns all characters as lowercase.

lower()方法執行相反的操作,并以小寫形式返回所有字符。

print('New York'.lower())
new york

清單 (Lists)

A list has its items ordered and you can add the same item as many times as you want. An important detail is that lists are mutable.

列表中的項目已排序,您可以根據需要添加相同的項目多次。 一個重要的細節是列表是可變的。

Mutability means you can change a list after its creation by adding items, removing them, or even just changing their values. These operations will be demonstrated later in the section dedicated to Lists.

可變性意味著您可以在列表創建后通過添加項目,刪除它們甚至更改其值來更改列表。 這些操作將在后面的“列表”部分中進行演示。

my_list = ["bmw", "ferrari", "maclaren"]
print(type(my_list))my_list = list(("bmw", "ferrari", "maclaren"))
print(type(my_list))
<class 'list'>
<class 'list'>

元組 (Tuples)

A tuple is just like a list: ordered, and allows repetition of items.

元組就像一個列表:有序,并且允許重復項。

There is just one difference: a tuple is immutable.

只有一個區別:元組是不可變的。

Immutability means you can't change a tuple after its creation. If you try to add an item or update one, for instance, the Python intepreter will show you an error. I will show that these errors occur later in the section dedicated to Tuples.

不變性意味著創建元組后不能更改它。 例如,如果您嘗試添加一項或更新一項,Python解釋器將向您顯示錯誤。 我將在后面有關元組的部分中說明這些錯誤。

my_tuple = ("bmw", "ferrari", "maclaren")
print(type(my_tuple))my_tuple = tuple(("bmw", "ferrari", "maclaren"))
print(type(my_tuple))
<class 'tuple'>
<class 'tuple'>

套裝 (Sets)

Sets don't guarantee the order of the items and are not indexed.

集合不保證項目的順序,也不會建立索引。

A key point when using sets: they don't allow repetition of an item.

使用集合時的關鍵點:它們不允許重復項。

my_set = {"bmw", "ferrari", "maclaren"}
print(type(my_set))my_set = set(("bmw", "ferrari", "maclaren"))
print(type(my_set))
<class 'set'>
<class 'set'>

辭典 (Dictionaries)

A dictionary doesn't guarantee the order of the elements and is mutable.

字典不能保證元素的順序,并且是可變的。

One important characteristic in dictionaries is that you can set your own access keys for each element.

字典的一個重要特征是您可以為每個元素設置自己的訪問鍵。

my_dict = {"country" : "France", "worldcups" : 2}
print(type(my_dict))my_dict = dict(country="France", worldcups=2)
print(type(my_dict))
<class 'dict'>
<class 'dict'>

類型轉換 (Typecasting)

Typecasting allows you to convert between different types.

類型轉換使您可以在不同類型之間進行轉換。

This way you can have an int turned into a str, or a float turned into an int, for instance.

這樣,您可以將int轉換為str ,或者將float轉換為int

顯式轉換 (Explicit conversion)

To cast a variable to a string just use the str() function.

要將變量轉換為字符串,只需使用str()函數。

# this is just a regular explicit intialization
my_str = str('32') 
print(my_str)# int to str
my_str = str(32) 
print(my_str)# float to str
my_str = str(32.0)
print(my_str)
32
32
32.0

To cast a variable to an integer just use the int() function.

要將變量轉換為整數,只需使用int()函數。

# this is just a regular explicit intialization
my_int = int(32) 
print(my_int)# float to int: rounds down to 3
my_int = int(3.2) 
print(my_int)# str to int
my_int = int('32') 
print(my_int)
32
3
32

To cast a variable to a float just use the float() function.

要將變量強制轉換為浮點數,只需使用float()函數。

# this is an explicit intialization
my_float = float(3.2)   
print(my_float)# int to float
my_float = float(32)     
print(my_float)# str to float
my_float = float('32')  
print(my_float)
3.2
32.0
32.0

What I did above is called an explicit type conversion.

我在上面所做的稱為顯式類型轉換。

In some cases you don't need to do the conversion explicitly, since Python can do it by itself.

在某些情況下,您不需要顯式進行轉換,因為Python可以自己進行轉換。

隱式轉換 (Implicit conversion)

The example below shows implicit conversion when adding an int and a float.

下面的示例顯示了添加intfloat時的隱式轉換。

Notice that my_sum is float. Python uses float to avoid data loss since the int type can not represent the decimal digits.

注意my_sumfloat 。 Python使用float來避免數據丟失,因為int類型不能表示十進制數字。

my_int = 32
my_float = 3.2my_sum = my_int + my_floatprint(my_sum)print(type(my_sum))
35.2
<class 'float'>

On the other hand, in this example, when you add an int and a str, Python will not be able to make the implicit conversion, and the explicit type conversion is necessary.

另一方面,在此示例中,當添加intstr ,Python將無法進行隱式轉換,因此顯式類型轉換是必需的。

my_int = 32
my_str = '32'# explicit conversion works
my_sum = my_int + int(my_str)
print(my_sum)#implicit conversion throws an error
my_sum = my_int + my_str
64Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

The same error is thrown when trying to add float and str types without making an explicit conversion.

嘗試添加floatstr類型而不進行顯式轉換時,將引發相同的錯誤。

my_float = 3.2
my_str = '32'# explicit conversion works
my_sum = my_float + float(my_str)
print(my_sum)#implicit conversion throws an error
my_sum = my_float + my_str
35.2Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'float' and 'str'

用戶輸入 (User Input)

If you need to interact with a user when running your program in the command line (for example, to ask for a piece of information), you can use the input() function.

如果在命令行中運行程序時需要與用戶進行交互(例如,要求提供一條信息),則可以使用input()函數。

country = input("What is your country? ") #user enters 'Brazil'print(country)
Brazil

The captured value is always string. Just remember that you might need to convert it using typecasting.

捕獲的值始終為string 。 請記住,您可能需要使用類型轉換對其進行轉換。

age = input("How old are you? ") #user enters '29'print(age)print(type(age))age = int(age)print(type(age))

The output for each print() is:

每個print()的輸出是:

29<class 'str'><class 'int'>

Notice the age 29 is captured as string and then converted explicitly to int.

請注意,年齡29被捕獲為string ,然后顯式轉換為int

經營者 (Operators)

In a programming language, operators are special symbols that you can apply to your variables and values in order to perform operations such as arithmetic/mathematical and comparison.

在編程語言中,運算符是特殊符號,可以將其應用于變量和值,以執行算術/數學和比較等操作。

Python has lots of operators that you can apply to your variables and I will demonstrate the most used ones.

Python有很多運算符,您可以將它們應用于變量,我將演示最常用的運算符。

算術運算符 (Arithmetic Operators)

Arithmetic operators are the most common type of operators and also the most recognizable ones.

算術運算符是最常見的運算符,也是最易識別的運算符。

They allow you to perform simple mathematical operations.

它們使您可以執行簡單的數學運算。

They are:

他們是:

  • +: Addition

    + :加法

  • -: Subtraction

    - :減法

  • *: Multiplication

    * :乘法

  • /: Division

    / :部門

  • **: Exponentiation

    ** :求冪

  • //: Floor Division, rounds down the result of a division

    // :底數除法,將四舍五入的結果取整

  • %: Modulus, gives you the remainder of a division

    % :模數,給你除法的余數

Let's see a program that shows how each of them is used.

讓我們來看一個顯示如何使用它們的程序。

print('Addition:', 5 + 2)
print('Subtraction:', 5 - 2)
print('Multiplication:', 5 * 2)
print('Division:', 5 / 2)
print('Floor Division:', 5 // 2)
print('Exponentiation:', 5 ** 2)
print('Modulus:', 5 % 2)
Addition: 7Subtraction: 3Multiplication: 10Division: 2.5Floor Division: 2Exponentiation: 25Modulus: 1

級聯 (Concatenation)

Concatenation is when you have two or more strings and you want to join them into one.

串聯是指當您有兩個或多個字符串并且想要將它們連接成一個字符串時。

This useful when you have information in multiple variables and want to combine them.

當您有多個變量中的信息并希望將它們組合在一起時,此功能很有用。

For instance, in this next example I combine two variables that contain my first name and my last name respectively to have my full name.

例如,在下一個示例中,我組合了兩個變量,分別包含我的名字和我的姓氏以擁有我的全名。

The + operator is also used to concatenate.

+運算符還用于連接。

first_name = 'Renan '
last_name = 'Moura'print(first_name + last_name)
Renan Moura

Since concatenation is applied to strings, to concatenate strings with other types, you have to do an explicit typecast using str().

由于將串聯應用于字符串,因此要將字符串與其他類型串聯,您必須使用str()進行顯式類型轉換。

I have to typecast the int value 30 to string with str() to concatenate it with the rest of the string.

我必須使用str()int值30轉換為字符串,以將其與其余字符串連接起來。

age = 'I have ' + str(30) + ' years old'print(age)
I have 30 years old

比較運算符 (Comparison Operators)

Use comparison operators to compare two values.

使用比較運算符比較兩個值。

These operators return either True or False.

這些運算符返回TrueFalse

They are:

他們是:

  • ==: Equal

    == :等于

  • !=: Not equal

    != :不相等

  • >: Greater than

    > :大于

  • <: Less than

    < :小于

  • >=: Greater than or equal to

    >= :大于或等于

  • <=: Less than or equal to

    <= :小于或等于

Let's see a program that shows how each of them is used.

讓我們來看一個顯示如何使用它們的程序。

print('Equal:', 5 == 2)
print('Not equal:', 5 != 2)
print('Greater than:', 5 > 2)
print('Less than:', 5 < 2)
print('Greater than or equal to:', 5 >= 2)
print('Less than or equal to:', 5 <= 2)
Equal: FalseNot equal: TrueGreater than: TrueLess than: FalseGreater than or equal to: TrueLess than or equal to: False

賦值運算符 (Assignment Operators)

As the name implies, these operators are used to assign values to variables.

顧名思義,這些運算符用于為變量分配值。

x = 7 in the first example is a direct assignment storing the number 7 in the variable x.

第一個示例中的x = 7是將數字7存儲在變量x的直接賦值。

The assignment operation takes the value on the right and assigns it to the variable on the left.

賦值操作將右邊的值分配給左邊的變量。

The other operators are simple shorthands for the Arithmetic Operators.

其他運算符是算術運算符的簡單簡寫。

In the second example x starts with 7 and x += 2 is just another way to write x = x + 2. This means the previous value of x is added by 2 and reassigned to x that is now equal to 9.

在第二個示例中, x7開頭, x += 2是寫x = x + 2另一種方式。 這意味著x的先前值被2并重新分配給x ,現在等于9

  • =: simple assignment

    = :簡單分配

x = 7
print(x)
7
  • +=: addition and assignment

    += :加法和賦值

x = 7
x += 2
print(x)
9
  • -=: subtraction and assignment

    -= :減法和賦值

x = 7
x -= 2
print(x)
5
  • *=: multiplication and assignment

    *= :乘法和賦值

x = 7
x *= 2
print(x)
14
  • /=: division and assignment

    /= :除法和賦值

x = 7
x /= 2
print(x)
3.5
  • %=: modulus and assignment

    %= :模數和賦值

x = 7
x %= 2
print(x)
1
  • //=: floor division and assignment

    //= :樓層劃分和分配

x = 7
x //= 2
print(x)
3
  • **=: exponentiation and assignment

    **= :求冪和賦值

x = 7
x **= 2
print(x)
49

邏輯運算符 (Logical Operators)

Logical operators are used to combine statements applying boolean algebra.

邏輯運算符用于組合使用布爾代數的語句。

They are:

他們是:

  • and: True only when both statements are true

    andTrue只有當兩個陳述是真實的

  • or: False only when both x and y are false

    orFalse只有當X和Y都是假的

  • not: The not operator simply inverts the input, True becomes False and vice versa.

    notnot運算符會簡單地反轉輸入, True變為False ,反之亦然。

Let's see a program that shows how each one is used.

讓我們看一個顯示如何使用每個程序的程序。

x = 5
y = 2print(x == 5 and y > 3) print(x == 5 or y > 3) print(not (x == 5))
FalseTrueFalse

會員運營商 (Membership Operators)

These operators provide an easy way to check if a certain object is present in a sequence: string, list, tuple, set, and dictionary.

這些運算符提供了一種簡便的方法來檢查序列中是否存在某個對象: stringlisttuplesetdictionary

They are:

他們是:

  • in: returns True if the object is present

    in :如果存在對象,則返回True

  • not in: returns True if the object is not present

    not in :如果不存在該對象,則返回True

Let's see a program that shows how each one is used.

讓我們看一個顯示如何使用每個程序的程序。

number_list = [1, 2, 4, 5, 6]print( 1 in number_list)print( 5 not in number_list)print( 3 not in number_list)
TrueFalseTrue

有條件的 (Conditionals)

Conditionals are one of the cornerstones of any programming language.

條件是任何編程語言的基石之一。

They allow you to control the program flow according to specific conditions you can check.

它們使您可以根據可以檢查的特定條件控制程序流程。

if語句 (The if statement)

The way you implement a conditional is through the if statement.

實現條件的方式是通過if語句。

The general form of an if statement is:

if語句的一般形式為:

if expression:statement

The expression contains some logic that returns a boolean, and the statement is executed only if the return is True.

expression包含一些返回布爾值的邏輯,并且僅在返回值為True時才執行該statement

A simple example:

一個簡單的例子:

bob_age = 32
sarah_age = 29if bob_age > sarah_age:print('Bob is older than Sarah')
Bob is older than Sarah

We have two variables indicating the ages of Bob and Sarah. The condition in plain English says "if Bob's age is greater than Sarah's age, then print the phrase 'Bob is older than Sarah'".

我們有兩個變量指示鮑勃和莎拉的年齡。 普通英語的條件是“如果Bob的年齡大于Sarah的年齡,則打印短語'Bob比Sarah大”。

Since the condition returns True, the phrase will be printed on the console.

由于條件返回True ,因此該短語將被打印在控制臺上。

if elseelif語句 (The if else and elif statements)

In our last example, the program only does something if the condition returns True.

在我們的最后一個示例中,僅當條件返回True ,程序才會執行某些操作。

But we also want it to do something if it returns False or even check a second or third condition if the first one wasn't met.

但是,我們也希望它在返回False執行某些操作,或者甚至在不滿足第一個條件時檢查第二個或第三個條件。

In this example, we swapped Bob's and Sarah's age. The first condition will return False since Sarah is older now, and then the program will print the phrase after the else instead.

在此示例中,我們交換了鮑勃和莎拉的年齡。 由于Sarah現在年齡較大,第一個條件將返回False ,然后程序將在else后面打印該短語。

bob_age = 29
sarah_age = 32if bob_age > sarah_age:print('Bob is older than Sarah')
else:print('Bob is younger than Sarah')
Bob is younger than Sarah

Now, consider the example below with the elif.

現在,考慮下面帶有elif的示例。

bob_age = 32
sarah_age = 32if bob_age > sarah_age:print('Bob is older than Sarah')
elif bob_age == sarah_age:print('Bob and Sarah have the same age')
else:print('Bob is younger than Sarah')
Bob and Sarah have the same age

The purpose of the elif is to provide a new condition to be checked before the else is executed.

elif的目的是提供一個在執行else之前要檢查的新條件。

Once again we changed their ages and now both are 32 years old.

我們再次改變了他們的年齡,現在他們都已經32歲了。

As such, the condition in the elif is met. Since both have the same age the program will print "Bob and Sarah have the same age".

這樣,滿足了elif的條件。 由于兩者的年齡相同,程序將打印“ Bob和Sarah具有相同的年齡”。

Notice you can have as many elifs as you want, just put them in sequence.

請注意,您可以根據需要設置任意多個elif ,只需將它們依次放置即可。

bob_age = 32
sarah_age = 32if bob_age > sarah_age:print('Bob is older than Sarah')
elif bob_age < sarah_age:print('Bob is younger than Sarah')
elif bob_age == sarah_age:print('Bob and Sarah have the same age')
else:print('This one is never executed')
Bob and Sarah have the same age

In this example, the else is never executed because all the possibilities are covered in the previous conditions and thus could be removed.

在此示例中,永遠不會執行else因為所有可能性在先前條件中均已涵蓋,因此可以刪除。

嵌套條件 (Nested conditionals)

You might need to check more than one conditional for something to happen.

您可能需要檢查多個條件才能發生某些事情。

In this case, you can nest your if statements.

在這種情況下,您可以嵌套if語句。

For instance, the second phrase "Bob is the oldest" is printed only if both ifs pass.

例如,只有if s和b都通過時,才會打印第二個短語“鮑勃是最老的”。

bob_age = 32
sarah_age = 28
mary_age = 25if bob_age > sarah_age:print('Bob is older than Sarah')if bob_age > mary_age:print('Bob is the oldest')
Bob is older than Sarah
Bob is the oldest

Or, depending on the logic, make it simpler with Boolean Algebra.

或者,根據邏輯,使用布爾代數使其更簡單。

This way, your code is smaller, more readable and easier to maintain.

這樣,您的代碼更小,更易讀且更易于維護。

bob_age = 32
sarah_age = 28
mary_age = 25if bob_age > sarah_age and bob_age > mary_age:print('Bob is the oldest')
Bob is the oldest

三元運算符 (Ternary Operators)

The ternary operator is a one-line if statement.

三元運算符是單行if語句。

It's very handy for simple conditions.

對于簡單的條件,它非常方便。

This is how it looks:

看起來是這樣的:

<expression> if <condition> else <expression>

Consider the following Python code:

考慮以下Python代碼:

a = 25
b = 50
x = 0
y = 1result = x if a > b else yprint(result)
1

Here we use four variables, a and b are for the condition, while x and y represent the expressions.

這里我們使用四個變量, ab表示條件,而xy表示表達式。

a and b are the values we are checking against each other to evaluate some condition. In this case, we are checking if a is greater than b.

ab是我們為了確定某種條件而相互檢查的值。 在這種情況下,我們正在檢查a是否大于b

If the expression holds true, i.e., a is greater than b, then the value of x will be attributed to result which will be equal to 0.

如果表達式為真,即a大于b ,則x的值將歸因于result ,該值等于0。

However, if a is less than b, then we have the value of y assigned to result, and result will hold the value 1.

但是,如果a小于b ,那么我們將y的值分配給result ,并且result將保持值1

Since a is less than b, 25 < 50, result will have 1 as final value from y.

由于a小于b ,25 <50, result將具有1從最終值y

The easy way to remember how the condition is evaluated is to read it in plain English.

記住條件評估方式的簡單方法是用簡單的英語閱讀。

Our example would read: result will be x if a is greater than b otherwise y.

我們的示例將顯示為:如果a大于bresultx ,否則為y

清單 (Lists)

As promised in the Types section, this section and the next three about Tuples, Sets, and Dictionaries will have more in depth explanations of each of them since they are very important and broadly used structures in Python to organize and deal with data.

正如“ 類型”部分中所承諾的那樣,本部分以及有關元組,集合和字典的下三部分將對它們中的每一個進行更深入的說明,因為它們是非常重要的,并且在Python中被廣泛使用以組織和處理數據。

A list has its items ordered and you can add the same item as many times as you want.

列表中的項目已排序,您可以根據需要添加相同的項目多次。

An important detail is that lists are mutable.

一個重要的細節是列表是可變的。

Mutability means you can change a list after its creation by adding items, removing them, or even just changing their values.

可變性意味著您可以在列表創建后通過添加項目,刪除它們甚至更改其值來更改列表。

初始化 (Initialization)

空清單 (Empty List)

people = []

列出初始值 (List with initial values)

people = ['Bob', 'Mary']

新增清單 (Adding in a List)

To add an item in the end of a list, use append().

要在列表末尾添加項目,請使用append()

people = ['Bob', 'Mary']
people.append('Sarah')print(people)
['Bob', 'Mary', 'Sarah']

To specify the position for the new item, use the insert() method.

要指定新項目的位置,請使用insert()方法。

people = ['Bob', 'Mary']
people.insert(0, 'Sarah')print(people)
['Sarah', 'Bob', 'Mary']

更新清單 (Updating in a List)

Specify the position of the item to update and set the new value

指定要更新的項目的位置并設置新值

people = ['Bob', 'Mary']
people[1] = 'Sarah'
print(people)
['Bob', 'Sarah']

刪除列表 (Deleting in a List)

Use the remove() method to delete the item given as an argument.

使用remove()方法刪除作為參數給出的項目。

people = ['Bob', 'Mary']
people.remove('Bob')
print(people)
['Mary']

To delete everybody, use the clear() method:

要刪除所有人,請使用clear()方法:

people = ['Bob', 'Mary']
people.clear()

檢索列表 (Retrieving in a List)

Use the index to reference the item.

使用索引來引用項目。

Remember that the index starts at 0.

請記住,索引從0開始。

So to access the second item use the index 1.

因此,要訪問第二項,請使用索引1。

people = ['Bob', 'Mary']
print(people[1])
Mary

檢查列表中是否已存在給定項目 (Check if a given item already exists in a List)

people = ['Bob', 'Mary']if 'Bob' in people:print('Bob exists!')
else:print('There is no Bob!')

元組 (Tuples)

A tuple is similar to a list: it's ordered, and allows repetition of items.

元組類似于列表:它是有序的,并且允許重復項。

There is just one difference: a tuple is immutable.

只有一個區別:元組是不可變的。

Immutability, if you remember, means you can't change a tuple after its creation. If you try to add an item or update one, for instance, the Python interpreter will show you an error.

如果您還記得,不變性意味著在創建元組之后就不能更改它。 例如,如果您嘗試添加一項或更新一項,Python解釋器將向您顯示錯誤。

初始化 (Initialization)

空元組 (Empty Tuple)

people = ()

具有初始值的元組 (Tuple with initial values)

people = ('Bob', 'Mary')

添加一個元組 (Adding in a Tuple)

Tuples are immutable. This means that if you try to add an item, you will see an error.

元組是不可變的。 這意味著,如果您嘗試添加項目,將看到錯誤。

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

在元組中更新 (Updating in a Tuple)

Updating an item will also return an error.

更新項目也會返回錯誤。

But there is a trick: you can convert into a list, change the item, and then convert it back to a tuple.

但是有一個竅門:您可以轉換為列表,更改項目,然后將其轉換回元組。

people = ('Bob', 'Mary')
people_list = list(people)
people_list[1] = 'Sarah'
people = tuple(people_list)
print(people)
('Bob', 'Sarah')

在元組中刪除 (Deleting in a Tuple)

For the same reason you can't add an item, you also can't delete an item, since they are immutable.

出于相同的原因,您不能添加項目,也不能刪除項目,因為它們是不可變的。

在元組中檢索 (Retrieving in a Tuple)

Use the index to reference the item.

使用索引來引用項目。

people = ('Bob', 'Mary')
print(people[1])
Mary

檢查給定項目在元組中是否已經存在 (Check if a given item already exists in a Tuple)

people = ('Bob', 'Mary')if 'Bob' in people:print('Bob exists!')
else:print('There is no Bob!')

套裝 (Sets)

Sets don't guarantee the order of items and are not indexed.

集合不保證項目的順序,也不會建立索引。

A key point when using sets: they don't allow repetition of an item.

使用集合時的關鍵點:它們不允許重復項。

初始化 (Initialization)

空集 (Empty Set)

people = set()

設置初始值 (Set with initial values)

people = {'Bob', 'Mary'}

集合中 (Adding in a Set)

Use the add() method to add one item.

使用add()方法添加一項。

people.add('Sarah')

Use the update() method to add multiple items at once.

使用update()方法一次添加多個項目。

people.update(['Carol', 'Susan'])

Remember, Sets do not allow repetition, so if you add 'Mary' again, nothing changes.

請記住,集合不允許重復,因此如果再次添加“ Mary”,則不會發生任何變化。

people = {'Bob', 'Mary'}people.add('Mary')print(people)
{'Bob', 'Mary'}

一組更新 (Updating in a Set)

Items in a set are not mutable. You have to either add or delete an item.

集合中的項目是不可變的。 您必須添加或刪除項目。

刪除集合 (Deleting in a Set)

To remove Bob from the dictionary:

要從字典中刪除Bob:

people = {'Bob', 'Mary'}
people.remove('Bob')
print(people)
{'Mary'}

To delete everybody:

要刪除所有人:

people.clear()

檢查給定項目是否已存在于集合中 (Check if a given item already exists in a set)

people = {'Bob', 'Mary'}if 'Bob' in people:print('Bob exists!')
else:print('There is no Bob!')

辭典 (Dictionaries)

The dictionary doesn't guarantee the order of the elements and it is mutable.

字典不保證元素的順序,并且是可變的。

One important characteristic of dictionaries is that you can set your customized access keys for each element.

詞典的一個重要特征是可以為每個元素設置自定義的訪問鍵。

字典的初始化 (Initialization of a Dictionary)

空字典 (Empty Dictionary)

people = {}

具有初始值的字典 (Dictionary with initial values)

people = {'Bob':30, 'Mary':25}

添加字典 (Adding in a Dictionary)

If the key doesn't exist yet, it is appended to the dictionary.

如果該鍵尚不存在,則將其附加到字典中。

people['Sarah']=32

更新字典 (Updating a Dictionary)

If the key already exists, the value is just updated.

如果鍵已經存在,則僅更新值。

#Bob's age is 28 now
people['Bob']=28

Notice that the code is pretty much the same.

注意,代碼幾乎相同。

刪除字典 (Deleting in a Dictionary)

To remove Bob from the dictionary:

要從字典中刪除Bob:

people.pop('Bob')

To delete everybody:

要刪除所有人:

people.clear()

檢索字典 (Retrieving in a Dictionary)

bob_age = people['Bob']
print(bob_age)
30

檢查字典中是否已存在給定鍵 (Check if a given key already exists in a Dictionary)

if 'Bob' in people:print('Bob exists!')
else:print('There is no Bob!')

while循環 (while Loops)

Loops are used when you need to repeat a block of code a certain number of times or apply the same logic over each item in a collection.

當您需要重復一段代碼或對集合中的每個項目應用相同的邏輯時,可以使用循環。

There are two types of loops: for and while.

循環有兩種類型: forwhile

You will learn about for loops in the next section.

您將在下一部分中了解for循環。

基本語法 (Basic Syntax)

The basic syntax of a while loop is as below.

while循環的基本語法如下。

while condition:statement

The loop will continue while the condition is True.

條件為True ,循環將繼續。

一個數字的平方是 (The square of a number is)

The example below takes each value of number and calculates its squared value.

下面的例子中采用的每個值number并計算其平方值。

number = 1
while number <= 5:print(number, 'squared is', number**2)number = number + 1
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25

You can use any variable name, but I chose number because it makes sense in the context. A common generic choice would be simply i.

您可以使用任何變量名,但是我選擇了number因為它在上下文中很有意義。 常見的通用選擇就是i

The loop will go on until number (initialized with 1) is less than or equal to 5.

循環將繼續進行,直到number (用1初始化)小于或等于5。

Notice that after the print() command, the variable number is incremented by 1 to take the next value.

注意,在print()命令之后,變量number增加1以獲取下一個值。

If you don't do the incrementation you will have an infinite loop since number will never reach a value greater than 5. This is a very important detail!

如果不進行遞增,則將有無限循環,因為number永遠不會達到大于5的值。這是非常重要的細節!

else阻止 (else block)

When the condition returns False, the else block will be called.

當條件返回False ,將調用else塊。

number = 1
while number <= 5:print(number, 'squared is', number**2)number = number + 1
else:print('No numbers left!')
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
No numbers left!

Notice the phrase 'No numbers left!' is printed after the loop ends, that is after the condition number <= 5 evaluates to False.

注意短語“沒有數字了!” 在循環結束之后(即條件number <= 5計算為False之后)打印。

如何在Python中打破while循環 (How to break out of a while loop in Python)

Simply use the break keyword, and the loop will stop its execution.

只需使用break關鍵字,循環就會停止執行。

number = 1
while number <= 5:print(number, 'squared is', number**2)number = number + 1if number == 4:break
1 squared is 1
2 squared is 4
3 squared is 9

The loop runs normally, and when number reaches 4 the if statement evaluates to True and the break command is called. This finishes the loop before the squared value of the numbers 4 and 5 are calculated.

循環正常運行,當number達到4時, if語句的值為True并調用break命令。 這樣就完成了循環,然后計算出數字4和5的平方值。

如何在while循環中跳過項目 (How to skip an item in a while loop)

The continue will do that for you.

continue將為您做到這一點。

I had to invert the order of the if statement and the print() to show how it works properly.

我必須反轉if語句和print()的順序,以顯示其如何正常工作。

number = 0
while number < 5:number = number + 1if number == 4:continueprint(number, 'squared is', number**2)
1 squared is 1
2 squared is 4
3 squared is 9
5 squared is 25

The program always checks if 4 is the current value of number. If it is, the square of 4 won't be calculated and the continue will skip to the next iteration when the value of number is 5. *

程序將始終檢查4是否為number的當前值。 如果是,則不會計算4的平方,并且當number值為5時, continue將跳至下一個迭代。

for循環 (for Loops)

for loops are similar to while loops in the sense that they are used to repeat blocks of code.

for循環與while循環在某種意義上類似,因為它們被用來重復代碼塊。

The most important difference is that you can easily iterate over sequential types.

最重要的區別是您可以輕松地迭代順序類型。

基本語法 (Basic Syntax)

The basic syntax of a for loop is as below.

for循環的基本語法如下。

for item in collection:statement

遍歷列表 (Loop over a list)

To loop over a list or any other collection, just proceed as shown in the example below.

要遍歷列表或任何其他集合,只需執行下面的示例所示。

cars = ['BMW', 'Ferrari', 'McLaren']
for car in cars:print(car)
BMW
Ferrari
McLaren

The list of cars contains three items. The for loop will iterate over the list and store each item in the car variable, and then execute a statement, in this case print(car), to print each car in the console.

cars列表包含三個項目。 for循環將遍歷列表并將每個項目存儲在car變量中,然后執行一條語句(在本例中為print(car)在控制臺中打印每個car。

range()函數 (range() function)

The range function is widely used in for loops because it gives you a simple way to list numbers.

范圍函數在for循環中得到廣泛使用,因為它為您提供了列出數字的簡單方法。

This code will loop through the numbers 0 to 5 and print each of them.

該代碼將循環顯示數字0到5,并打印每個數字。

for number in range(5):print(number)
0
1
2
3
4

In contrast, without the range() function, we would do something like this.

相反,如果沒有range()函數,我們將執行以下操作。

numbers = [0, 1, 2, 3, 4]
for number in numbers:print(number)
0
1
2
3
4

You can also define a start and stop using range().

您還可以使用range()定義startstop

Here we are starting in 5 and a stoping in 10. The number you set to stop is not included.

在這里,我們從5開始,在10中停止。不包含您設置為停止的數字。

for number in range(5, 10):print(number)
5
6
7
8
9

Finally, it is also possible to set a step.

最后,也可以設置一個步驟。

Here we starting in 10 and incrementing by 2 until 20, since 20 is the stop, it is not included.

在這里,我們從10開始,再增加2直到20,因為20是stop ,所以不包括在內。

for number in range(10, 20, 2):print(number)
10
12
14
16
18

else阻止 (else block)

When the items in the list are over, the else block will be called.

當列表中的項目結束時,將調用else塊。

cars = ['BMW', 'Ferrari', 'McLaren']
for car in cars:print(car)
else:print('No cars left!')
BMW
Ferrari
McLaren
No cars left!

如何在Python中突破for循環 (How to break out of a for loop in Python)

Simply use the break keyword, and the loop will stop its execution.

只需使用break關鍵字,循環就會停止執行。

cars = ['BMW', 'Ferrari', 'McLaren']
for car in cars:print(car)if car == 'Ferrari':break
BMW
Ferrari

The loop will iterate through the list and print each car.

該循環將遍歷列表并打印每輛車。

In this case, after the loop reaches 'Ferrari', the break is called and 'McLaren' won't be printed.

在這種情況下,循環到達“ Ferrari”后,將調用該break ,并且不會打印“ McLaren”。

如何跳過for循環中的項目 (How to skip an item in a for loop)

In this section, we'll learn how continue can do this for you.

在本節中,我們將學習continue如何為您完成此操作。

I had to invert the order of the if statement and the continue to show how it works properly.

我不得不反轉if語句的順序,并continue顯示它如何正常工作。

Notice that I always check if 'Ferrari' is the current item. If it is, 'Ferrari' won't be printed, and the continue will skip to the next item 'McLaren'.

請注意,我始終檢查“ Ferrari”是否為當前項目。 如果是,則不會打印“法拉利”, continue將跳至下一個“邁凱輪”。

cars = ['BMW', 'Ferrari', 'McLaren']
for car in cars:if car == 'Ferrari':continueprint(car)
BMW
McLaren

循環循環:嵌套循環 (Loop over a Loop: Nested Loops)

Sometimes you have more complex collections, like a list of lists.

有時您有更復雜的集合,例如列表列表。

To iterate over these lists, you need nested for loops.

要遍歷這些列表,您需要嵌套for循環。

In this case, I have three lists: one of BMW models, another on Ferrari models, and finally one with McLaren models.

在這種情況下,我有三個列表:一個是寶馬模型,另一個是法拉利模型,最后一個是邁凱輪模型。

The first loop iterates over each brand's list, and the second will iterate over the models of each brand.

第一個循環遍歷每個品牌的列表,第二個循環遍歷每個品牌的模型。

car_models = [ 
['BMW I8', 'BMW X3', 
'BMW X1'], 
['Ferrari 812', 'Ferrari F8', 
'Ferrari GTC4'], 
['McLaren 570S', 'McLaren 570GT', 
'McLaren 720S']
]for brand in car_models:for model in brand:print(model)
BMW I8
BMW X3
BMW X1
Ferrari 812
Ferrari F8
Ferrari GTC4
McLaren 570S
McLaren 570GT
McLaren 720S

遍歷其他數據結構 (Loop over other Data Structures)

The same logic that applies for loops over a list can be extended to the other data structures: tuple, set, and dictionary.

適用for list循環的相同邏輯可以擴展到其他數據結構: tuplesetdictionary

I will briefly demonstrate how to make a basic loop over each one of them.

我將簡要演示如何對它們每個進行基本循環。

遍歷元組 (Loop over a Tuple)

people = ('Bob', 'Mary')for person in people:print(person)
Bob
Mary

遍歷一組 (Loop over a Set)

people = {'Bob', 'Mary'}for person in people:print(person)
Bob
Mary

循環字典 (Loop over a Dictionary)

To print the keys:

要打印密鑰:

people = {'Bob':30, 'Mary':25}for person in people:print(person)
Bob
Mary

To print the values:

要打印值:

people = {'Bob':30, 'Mary':25}for person in people:print(people[person])
30
25

功能 (Functions)

As the code grows the complexity also grows. And functions help organize the code.

隨著代碼的增長,復雜性也隨之增長。 功能有助于組織代碼。

Functions are a handy way to create blocks of code that you can reuse.

函數是創建可重復使用的代碼塊的便捷方法。

定義和調用 (Definition and Calling)

In Python use the def keyword to define a function.

在Python中,使用def關鍵字定義一個函數。

Give it a name and use parentheses to inform 0 or more arguments.

給它起一個名字,并用括號告知0個或多個參數。

In the line after the declaration starts, remember to indent the block of code.

在聲明開始后的行中,請記住縮進代碼塊。

Here is an example of a function called print_first_function() that only prints a phrase 'My first function!'.

這是一個名為print_first_function()的函數的示例,該函數僅輸出短語“我的第一個函數!”。

To call the function just use its name as defined.

要調用該函數,只需使用其定義的名稱即可。

def print_first_function():print('My first function!')print_first_function()
My first function!

return(return a value)

Use the return keyword to return a value from the function.

使用return關鍵字從函數返回值。

In this example the function second_function() returns the string 'My second function!'.

在此示例中,函數second_function()返回字符串“我的第二個函數!”。

Notice that print() is a built-in function and our function is called from inside it.

注意, print()是一個內置函數,我們的函數是從內部調用的。

The string returned by second_function() is passed as an argument to the print() function.

second_function()返回的字符串作為參數傳遞給print()函數。

def second_function():return 'My second function!'print(second_function())
My second function!

return多個值 (return multiple values)

Functions can also return multiple values at once.

函數也可以一次返回多個值。

return_numbers() returns two values simultaneously.

return_numbers()同時返回兩個值。

def return_numbers():return 10, 2print(return_numbers())
(10, 2)

爭論 (Arguments)

You can define parameters between the parentheses.

您可以在括號之間定義參數。

When calling a function with parameters you have to pass arguments according to the parameters defined.

使用參數調用函數時,必須根據定義的參數傳遞參數。

The past examples had no parameters, so there was no need for arguments. The parentheses remained empty when the functions were called.

過去的示例沒有參數,因此不需要參數。 調用函數時,括號保持空白。

一個論點 (One Argument)

To specify one parameter, just define it inside the parentheses.

要指定一個參數,只需在括號內定義它。

In this example, the function my_number expects one number as argument defined by the parameter num.

在此示例中,函數my_number期望一個數字作為參數num定義的參數。

The value of the argument is then accessible inside the function to be used.

然后可以在要使用的函數內部訪問參數的值。

def my_number(num):return 'My number is: ' + str(num)print(my_number(10))
My number is: 10

兩個或多個參數 (Two or more Arguments)

To define more parameters, just use a comma to separate them.

要定義更多參數,只需使用逗號將它們分開。

Here we have a function that adds two numbers called add. It expects two arguments defined by first_num and second_num.

在這里,我們有一個函數,將兩個數字相加,稱為add 。 它期望由first_numsecond_num定義的兩個參數。

The arguments are added by the + operator and the result is then returned by the return.

參數由+運算符添加,然后由return

def add(first_num, second_num):return first_num + second_numprint(add(10,2))
12

This example is very similar to the last one. The only difference is that we have 3 parameters instead of 2.

這個例子與上一個非常相似。 唯一的區別是我們有3個參數,而不是2個。

def add(first_num, second_num, third_num):return first_num + second_num + third_numprint(add(10,2,3))
15

This logic of defining parameters and passing arguments is the same for any number of parameters.

定義參數和傳遞參數的邏輯對于任意數量的參數都是相同的。

It is important to point out that the arguments have to be passed in the same order that the parameters are defined.

重要的是要指出,必須按照定義參數的順序傳遞參數。

默認值。 (Default value.)

You can set a default value for a parameter if no argument is given using the = operator and a value of choice.

如果未使用=運算符和選擇值給出參數,則可以為參數設置默認值。

In this function, if no argument is given, the number 30 is assumed as the expected value by default.

在此函數中,如果未提供任何參數,則默認情況下將數字30假定為期望值。

def my_number(my_number = 30):return 'My number is: ' + str(my_number)print(my_number(10))
print(my_number())
My number is: 10
My number is: 30

關鍵字或命名參數 (Keyword or Named Arguments)

When calling a function, the order of the arguments have to match the order of the parameters.

調用函數時,參數的順序必須與參數的順序匹配。

The alternative is if you use keyword or named arguments.

替代方法是使用關鍵字或命名參數。

Set the arguments to their respective parameters directly using the name of the parameters and the = operators.

直接使用參數名稱和=運算符將參數設置為其各自的參數。

This example flips the arguments, but the function works as expected because I tell it which value goes to which parameter by name.

此示例翻轉了參數,但是該函數按預期工作,因為我告訴它名稱將哪個值分配給了哪個參數。

def my_numbers(first_number, second_number):return 'The numbers are: ' + str(first_number) + ' and ' + str(second_number)print(my_numbers(second_number=30, first_number=10))
The numbers are: 10 and 30

任意數量的參數: *args (Any number of arguments: *args)

If you don't want to specify the number of parameters, just use the * before the parameter name. Then the function will take as many arguments as necessary.

如果不想指定參數數量,只需在參數名稱前使用* 。 然后,該函數將接受盡可能多的參數。

The parameter name could be anything like *numbers, but there is a convention in Python to use *args for this definition of a variable number of arguments.

參數名稱可以是*numbers類的東西,但是Python中有一個約定,可以使用*args來定義可變數量的參數。

def my_numbers(*args):for arg in args:print(number)my_numbers(10,2,3)
10
2
3

任意數量的關鍵字/命名參數: **kwargs (Any number of Keyword/Named arguments: **kwargs)

Similar to *args, we can use **kwargs to pass as many keyword arguments as we want, as long as we use **.

類似*args ,我們可以使用**kwargs傳遞盡可能多的關鍵字參數,因為我們希望,只要我們使用**

Again, the name could be anything like **numbers, but **kwargs is a convention.

Again, the name could be anything like **numbers , but **kwargs is a convention.

def my_numbers(**kwargs):for key, value in kwargs.items():print(key)print(value)my_numbers(first_number=30, second_number=10)
first_number
30
second_number
10

Other types as arguments (Other types as arguments)

The past examples used mainly numbers, but you can pass any type as argument and they will be treated as such inside the function.

The past examples used mainly numbers, but you can pass any type as argument and they will be treated as such inside the function.

This example takes strings as arguments.

This example takes strings as arguments.

def my_sport(sport):print('I like ' + sport)my_sport('football')
my_sport('swimming')
I like football
I like swimming

This function takes a list as argument.

This function takes a list as argument.

def my_numbers(numbers):for number in numbers:print(number)my_numbers([30, 10, 64, 92, 105])
30
10
64
92
105

范圍 (Scope)

The place where a variable is created defines its availability to be accessed and manipulated by the rest of the code. This is known as scope.

The place where a variable is created defines its availability to be accessed and manipulated by the rest of the code. This is known as scope .

There are two types of scope: local and global.

There are two types of scope: local and global.

Global Scope (Global Scope)

A global scope allows you to use the variable anywhere in your program.

A global scope allows you to use the variable anywhere in your program.

If your variable is outside a function, it has global scope by default.

If your variable is outside a function, it has global scope by default.

name = 'Bob'def print_name():print('My name is ' + name)print_name()
My name is Bob

Notice that the function could use the variable name and print My name is Bob.

Notice that the function could use the variable name and print My name is Bob .

Local Scope (Local Scope)

When you declare a variable inside a function, it only exists inside that function and can't be accessed from the outside.

When you declare a variable inside a function, it only exists inside that function and can't be accessed from the outside.

def print_name():name = "Bob"print('My name is ' + name)print_name()
My name is Bob

The variable name was declared inside the function, so the output is the same as before.

The variable name was declared inside the function, so the output is the same as before.

But this will throw an error:

But this will throw an error:

def print_name():name = 'Bob'print('My name is ' + name)print(name)

The output of the code above is:

The output of the code above is:

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

I tried to print the variable name from outside the function, but the scope of the variable was local and could not be found in a global scope.

I tried to print the variable name from outside the function, but the scope of the variable was local and could not be found in a global scope.

Mixing Scopes (Mixing Scopes)

If you use the same name for variables inside and outside a function, the function will use the one inside its scope.

If you use the same name for variables inside and outside a function, the function will use the one inside its scope.

So when you call print_name(), the name='Bob' is used to print the phrase.

So when you call print_name() , the name='Bob' is used to print the phrase.

On the other hand, when calling print() outside the function scope, name="Sarah" is used because of its global scope.

On the other hand, when calling print() outside the function scope, name="Sarah" is used because of its global scope.

name = "Sarah"def print_name():name = 'Bob'print('My name is ' + name)print_name()print(name)

The output of the code above is:

The output of the code above is:

My name is BobSarah

List Comprehensions (List Comprehensions)

Sometimes we want to perform some very simple operations over the items of a list.

Sometimes we want to perform some very simple operations over the items of a list.

List comprehensions give us a succinct way to work on lists as an alternative to other methods of iteration, such as for loops.

List comprehensions give us a succinct way to work on lists as an alternative to other methods of iteration, such as for loops.

Basic syntax (Basic syntax)

To use a list comprehension to replace a regular for loop, we can make:

To use a list comprehension to replace a regular for loop, we can make:

[expression for item in list]

Which is the same as doing:

Which is the same as doing:

for item in list:expression

If we want some conditional to apply the expression, we have:

If we want some conditional to apply the expression, we have:

[expression for item in list if conditional ]

Which is the same as doing:

Which is the same as doing:

for item in list:if conditional:expression

Example 1: calculating the cube of a number (Example 1: calculating the cube of a number)

Regular way

Regular way

numbers = [1, 2, 3, 4, 5]
new_list = []for n in numbers:new_list.append(n**3)print(new_list)
[1, 8, 27, 64, 125]

Using list comprehensions

Using list comprehensions

numbers = [1, 2, 3, 4, 5]
new_list = []new_list = [n**3 for n in numbers]print(new_list)
[1, 8, 27, 64, 125]

Example 2: calculating the cube of a number only if it is greater than 3 (Example 2: calculating the cube of a number only if it is greater than 3)

Using the conditional, we can filter only the values we want the expression to be applied to.

Using the conditional, we can filter only the values we want the expression to be applied to.

Regular way

Regular way

numbers = [1, 2, 3, 4, 5]
new_list = []for n in numbers:if(n > 3):new_list.append(n**3)print(new_list)
[64, 125]

Using list comprehensions

Using list comprehensions

numbers = [1, 2, 3, 4, 5]
new_list = []new_list = [n**3 for n in numbers if n > 3]print(new_list)
[64, 125]

Example 3: calling functions with list comprehensions (Example 3: calling functions with list comprehensions)

We can also call functions using the list comprehension syntax:

We can also call functions using the list comprehension syntax:

numbers = [1, 2, 3, 4, 5]
new_list = []def cube(number):return number**3new_list = [cube(n) for n in numbers if n > 3]print(new_list)
[64, 125]

Lambda Functions (Lambda Functions)

A Python lambda function can only have one expression and can't have multiple lines.

A Python lambda function can only have one expression and can't have multiple lines.

It is supposed to make it easier to create some small logic in one line instead of a whole function as is usually done.

It is supposed to make it easier to create some small logic in one line instead of a whole function as is usually done.

Lambda functions are also anonymous, which means there is no need to name them.

Lambda functions are also anonymous, which means there is no need to name them.

Basic Syntax (Basic Syntax)

The basic syntax is very simple: just use the lambda keyword, define the parameters needed, and use ":" to separate the parameters from the expression.

The basic syntax is very simple: just use the lambda keyword, define the parameters needed, and use ":" to separate the parameters from the expression.

The general forms is:

The general forms is:

lambda arguments : expression

One parameter example (One parameter example)

Look at this example using only one parameter

Look at this example using only one parameter

cubic = lambda number : number**3
print(cubic(2))
8

Multiple parameter example (Multiple parameter example)

If you want, you can also have multiple parameters.

If you want, you can also have multiple parameters.

exponential = lambda multiplier, number, exponent : multiplier * number**exponent
print(exponential(2, 2, 3))
16

Calling the Lambda Function directly (Calling the Lambda Function directly)

You don't need to use a variable as we did before. Instead you can make use of parenthesis around the lambda function and another pair of parenthesis around the arguments.

You don't need to use a variable as we did before. Instead you can make use of parenthesis around the lambda function and another pair of parenthesis around the arguments.

The declaration of the function and the execution will happen in the same line.

The declaration of the function and the execution will happen in the same line.

(lambda multiplier, number, exponent : multiplier * number**exponent)(2, 2, 3)
16

Examples using lambda functions with other built-in functions (Examples using lambda functions with other built-in functions)

地圖 (Map)

The Map function applies the expression to each item in a list.

The Map function applies the expression to each item in a list.

Let's calculate the cubic of each number in the list.

Let's calculate the cubic of each number in the list.

numbers = [2, 5, 10]
cubics = list(map(lambda number : number**3, numbers))
print(cubics)
[8, 125, 1000]

過濾 (Filter)

The Filter function will filter the list based on the expression.

The Filter function will filter the list based on the expression.

Let's filter to have only the numbers greater than 5.

Let's filter to have only the numbers greater than 5.

numbers = [2, 5, 10]
filtered_list = list(filter(lambda number : number > 5, numbers))
print(filtered_list)
[10]

模組 (Modules)

After some time your code starts to get more complex with lots of functions and variables.

After some time your code starts to get more complex with lots of functions and variables.

To make it easier to organize the code we use Modules.

To make it easier to organize the code we use Modules.

A well-designed Module also has the advantage of being reusable, so you write code once and reuse it everywhere.

A well-designed Module also has the advantage of being reusable, so you write code once and reuse it everywhere.

You can write a module with all the mathematical operations and other people can use it.

You can write a module with all the mathematical operations and other people can use it.

And, if you need, you can use someone else's modules to simplify your code, speeding up your project.

And, if you need, you can use someone else's modules to simplify your code, speeding up your project.

In other programming languages, these are also referred to as libraries.

In other programming languages, these are also referred to as libraries.

Using a Module (Using a Module)

To use a module we use the import keyword.

To use a module we use the import keyword.

As the name implies we have to tell our program what module to import.

As the name implies we have to tell our program what module to import.

After that, we can use any function available in that module.

After that, we can use any function available in that module.

Let's see an example using the math module.

Let's see an example using the math module.

First, let's see how to have access to a constant, Euler's number.

First, let's see how to have access to a constant, Euler's number.

import mathmath.e
2.718281828459045

In this second example, we are going to use a function that calculates the square root of a number.

In this second example, we are going to use a function that calculates the square root of a number.

It is also possible to use the as keyword to create an alias.

It is also possible to use the as keyword to create an alias.

import math as mm.sqrt(121)m.sqrt(729)
11
27

Finally, using the from keyword, we can specify exactly what to import instead of the whole module and use the function directly without the module's name.

Finally, using the from keyword, we can specify exactly what to import instead of the whole module and use the function directly without the module's name.

This example uses the floor() function that returns the largest integer less than or equal to a given number.

This example uses the floor() function that returns the largest integer less than or equal to a given number.

from math import floorfloor(9.8923)
9

Creating a Module (Creating a Module)

Now that we know how to use modules, let's see how to create one.

Now that we know how to use modules, let's see how to create one.

It is going to be a module with the basic math operations add, subtract, multiply, divide and it is gonna be called basic_operations.

It is going to be a module with the basic math operations add , subtract , multiply , divide and it is gonna be called basic_operations .

Create the basic_operations.py file with the four functions.

Create the basic_operations.py file with the four functions.

def add(first_num, second_num):return first_num + second_numdef subtract(first_num, second_num):return first_num - second_numdef multiply(first_num, second_num):return first_num * second_numdef divide(first_num, second_num):return first_num / second_num

Then, just import the basic_operations module and use the functions.

Then, just import the basic_operations module and use the functions.

import basic_operationsbasic_operations.add(10,2)
basic_operations.subtract(10,2)
basic_operations.multiply(10,2)
basic_operations.divide(10,2)
12
8
20
5.0

if __name__ == '__main__' (if __name__ == '__main__')

You are in the process of building a module with the basic math operations add, subtract, multiply, and divide called basic_operations saved in the basic_operations.py file.

You are in the process of building a module with the basic math operations add , subtract , multiply , and divide called basic_operations saved in the basic_operations.py file.

To guarantee everything is fine, you can run some tests.

To guarantee everything is fine, you can run some tests.

def add(first_num, second_num):return first_num + second_numdef subtract(first_num, second_num):return first_num - second_numdef multiply(first_num, second_num):return first_num * second_numdef divide(first_num, second_num):return first_num / second_numprint(add(10, 2)) 
print(subtract(10,2))
print(multiply(10,2))
print(divide(10,2))

After running the code:

After running the code:

renan@pro-home:~$ python3 basic_operations.py

The output is:

輸出為:

12
8
20
5.0

The output for those tests are what we expected.

The output for those tests are what we expected.

Our code is right and ready to share.

Our code is right and ready to share.

Let's import the new module run it in the Python console.

Let's import the new module run it in the Python console.

Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import basic_operations
12
8
20
5.0
>>>

When the module is imported our tests are displayed on the screen even though we didn't do anything besides importing basic_operations.

When the module is imported our tests are displayed on the screen even though we didn't do anything besides importing basic_operations .

To fix that we use if __name__ == '__main__' in the basic_operations.py file like this:

To fix that we use if __name__ == '__main__' in the basic_operations.py file like this:

def add(first_num, second_num):return first_num + second_numdef subtract(first_num, second_num):return first_num - second_numdef multiply(first_num, second_num):return first_num * second_numdef divide(first_num, second_num):return first_num / second_numif __name__ == '__main__':print(add(10, 2)) print(subtract(10,2))print(multiply(10,2))print(divide(10,2))

Running the code directly on the terminal will continue to display the tests. But when you import it like a module, the tests won't show and you can use the functions the way you intended.

Running the code directly on the terminal will continue to display the tests. But when you import it like a module, the tests won't show and you can use the functions the way you intended.

Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import basic_operations
>>> basic_operations.multiply(10,2)
20
>>>

Now that you know how to use the if __name__ == '__main__', let's understand how it works.

Now that you know how to use the if __name__ == '__main__' , let's understand how it works.

The condition tells when the interpreter is treating the code as a module or as a program itself being executed directly.

The condition tells when the interpreter is treating the code as a module or as a program itself being executed directly.

Python has this native variable called __name__.

Python has this native variable called __name__ .

This variable represents the name of the module which is the name of the .py file.

This variable represents the name of the module which is the name of the .py file.

Create a file my_program.py with the following and execute it.

Create a file my_program.py with the following and execute it.

print(__name__)

The output will be:

The output will be:

__main__

This tells us that when a program is executed directly, the variable __name__ is defined as __main__.

This tells us that when a program is executed directly, the variable __name__ is defined as __main__ .

But when it is imported as a module, the value of __name__ is the name of the module.

But when it is imported as a module, the value of __name__ is the name of the module.

Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import my_program
my_program
>>>

This is how the Python interpreter differentiates the behavior of an imported module and a program executed directly on the terminal.

This is how the Python interpreter differentiates the behavior of an imported module and a program executed directly on the terminal.

檔案 (Files)

Creating, deleting, reading, and many other functions applied to files are an integral part of many programs.

Creating, deleting, reading, and many other functions applied to files are an integral part of many programs.

As such, it is very important to know how to organize and deal with files directly from your code.

As such, it is very important to know how to organize and deal with files directly from your code.

Let's see how to handle files in Python.

Let's see how to handle files in Python.

File create (File create)

First things first, create!

First things first, create!

We are going to use the open() function.

We are going to use the open() function.

This function opens a file and returns its corresponding object.

This function opens a file and returns its corresponding object.

The first argument is the name of the file we are handling, the second refers to the operation we are using.

The first argument is the name of the file we are handling, the second refers to the operation we are using.

The code below creates the file "people.txt", the x argument is used when we just want to create the file. If a file with the same name already exists, it will throw an exception.

The code below creates the file "people.txt", the x argument is used when we just want to create the file. If a file with the same name already exists, it will throw an exception.

people_file = open("people.txt", "x")

You can also use the w mode to create a file. Unlike the x mode, it will not throw an exception since this mode indicates the writing mode. We are opening a file to write data into it and, if the file doesn't exist, it is created.

You can also use the w mode to create a file. Unlike the x mode, it will not throw an exception since this mode indicates the writing mode. We are opening a file to write data into it and, if the file doesn't exist, it is created.

people_file = open("people.txt", "w")

The last one is the a mode which stands for append. As the name implies, you can append more data to the file, while the w mode simply overwrites any existing data.

The last one is the a mode which stands for append . As the name implies, you can append more data to the file, while the w mode simply overwrites any existing data.

When appending, if the file doesn't exist, it also creates it.

When appending, if the file doesn't exist, it also creates it.

people_file = open("people.txt", "a")

File write (File write)

To write data into a file, you simply open a file with the w mode.

To write data into a file, you simply open a file with the w mode.

Then, to add data, you use the object return by the open() function. In this case, the object is called people_file. Then you call the write() function passing the data as argument.

Then, to add data, you use the object return by the open() function. In this case, the object is called people_file . Then you call the write() function passing the data as argument.

people_file = open("people.txt", "w")
people_file.write("Bob\n")
people_file.write("Mary\n")
people_file.write("Sarah\n")
people_file.close()

We use \n at the end to break the line, otherwise the content in the file will stay in the same line as "BobMarySarah".

We use \n at the end to break the line, otherwise the content in the file will stay in the same line as "BobMarySarah".

One more detail is to close() the file. This is not only a good practice, but also ensures that your changes were applied to the file.

One more detail is to close() the file. This is not only a good practice, but also ensures that your changes were applied to the file.

Remember that when using w mode, the data that already existed in the file will be overwritten by the new data. To add new data without losing what was already there, we have to use the append mode.

Remember that when using w mode, the data that already existed in the file will be overwritten by the new data. To add new data without losing what was already there, we have to use the append mode.

File append (File append)

The a mode appends new data to the file, keeping the existing one.

The a mode appends new data to the file, keeping the existing one.

In this example, after the first writing with w mode, we are using the a mode to append. The result is that each name will appear twice in the file "people.txt".

In this example, after the first writing with w mode, we are using the a mode to append. The result is that each name will appear twice in the file "people.txt".

#first write
people_file = open("people.txt", "w")
people_file.write("Bob\n")
people_file.write("Mary\n")
people_file.write("Sarah\n")
people_file.close()#appending more data
#keeping the existing data
people_file = open("people.txt", "a")
people_file.write("Bob\n")
people_file.write("Mary\n")
people_file.write("Sarah\n")
people_file.close()

File read (File read)

Reading the file is also very straightforward: just use the r mode like so.

Reading the file is also very straightforward: just use the r mode like so.

If you read the "people.txt" file created in the last example, you should see 6 names in your output.

If you read the "people.txt" file created in the last example, you should see 6 names in your output.

people_file = open("people.txt", "r")
print(people_file.read())
Bob
Mary
Sarah
Bob
Mary
Sarah

The read() function reads the whole file at once. If you use the readline() function, you can read the file line by line.

The read() function reads the whole file at once. If you use the readline() function, you can read the file line by line.

people_file = open("people.txt", "r")
print(people_file.readline())
print(people_file.readline())
print(people_file.readline())
Bob
Mary
Sarah

You can also loop to read the lines like the example below.

You can also loop to read the lines like the example below.

people_file = open("people.txt", "r")
for person in people_file:print(person)
Bob
Mary
Sarah
Bob
Mary
Sarah

Delete a File (Delete a File)

To delete a file, you also need the os module.

To delete a file, you also need the os module.

Use the remove() method.

Use the remove() method.

import osos.remove('my_file.txt')

Check if a File Exists (Check if a File Exists)

Use the os.path.exists() method to check the existence of a file.

Use the os.path.exists() method to check the existence of a file.

import osif os.path.exists('my_file.txt'):os.remove('my_file.txt')
else:print('There is no such file!')

Copy a File (Copy a File)

For this one, I like to use the copyfile() method from the shutil module.

For this one, I like to use the copyfile() method from the shutil module.

from shutil import copyfilecopyfile('my_file.txt','another_file.txt')

There are a few options to copy a file, but copyfile() is the fastest one.

There are a few options to copy a file, but copyfile() is the fastest one.

Rename and Move a File (Rename and Move a File)

If you need to move or rename a file you can use the move() method from the shutil module.

If you need to move or rename a file you can use the move() method from the shutil module.

from shutil import movemove('my_file.txt','another_file.txt')

Classes and Objects (Classes and Objects)

Classes and Objects are the fundamental concepts of Object-Oriented Programming.

Classes and Objects are the fundamental concepts of Object-Oriented Programming.

In Python, everything is an object!

In Python, everything is an object !

A variable (object) is just an instance of its type (class).

A variable (object) is just an instance of its type (class).

That's why when you check the type of a variable you can see the class keyword right next to its type (class).

That's why when you check the type of a variable you can see the class keyword right next to its type (class).

This code snippet shows that my_city is an object and it is an instance of the class str.

This code snippet shows that my_city is an object and it is an instance of the class str .

my_city = "New York"
print(type(my_city))
<class 'str'>

Differentiate Class x Object (Differentiate Class x Object)

The class gives you a standard way to create objects. A class is like a base project.

The class gives you a standard way to create objects. A class is like a base project.

Say you are an engineer working for Boeing.

Say you are an engineer working for Boeing.

Your new mission is to build the new product for the company, a new model called 747-Space. This aircraft flies higher altitudes than other commercial models.

Your new mission is to build the new product for the company, a new model called 747-Space. This aircraft flies higher altitudes than other commercial models.

Boeing needs to build dozens of those to sell to airlines all over the world, and the aircrafts have to be all the same.

Boeing needs to build dozens of those to sell to airlines all over the world, and the aircrafts have to be all the same.

To guarantee that the aircrafts (objects) follow the same standards, you need to have a project (class) that can be replicable.

To guarantee that the aircrafts (objects) follow the same standards, you need to have a project (class) that can be replicable.

The class is a project, a blueprint for an object.

The class is a project, a blueprint for an object.

This way you make the project once, and reuse it many times.

This way you make the project once, and reuse it many times.

In our code example before, consider that every string has the same behavior and the same attributes. So it only makes sense for strings to have a class str to define them.

In our code example before, consider that every string has the same behavior and the same attributes. So it only makes sense for strings to have a class str to define them.

Attributes and Methods (Attributes and Methods)

Objects have some behavior which is is given by attributes and methods.

Objects have some behavior which is is given by attributes and methods.

In simple terms, in the context of an object, attributes are variables and methods are functions attached to an object.

In simple terms, in the context of an object, attributes are variables and methods are functions attached to an object.

For example, a string has many built-in methods that we can use.

For example, a string has many built-in methods that we can use.

They work like functions, you just need to separate them from the objects using a ..

They work like functions, you just need to separate them from the objects using a .

In this code snippet, I'm calling the replace() method from the string variable my_city which is an object, and an instance of the class str.

In this code snippet, I'm calling the replace() method from the string variable my_city which is an object, and an instance of the class str .

The replace() method replaces a part of the string for another and returns a new string with the change. The original string remains the same.

The replace() method replaces a part of the string for another and returns a new string with the change. The original string remains the same.

Let's replace 'New' for 'Old' in 'New York'.

Let's replace 'New' for 'Old' in 'New York'.

my_city = 'New York'
print(my_city.replace('New', 'Old'))
print(my_city)
Old York
New York

Creating a Class (Creating a Class)

We have used many objects (instances of classes) like strings, integers, lists, and dictionaries. All of them are instances of predefined classes in Python.

We have used many objects (instances of classes) like strings, integers, lists, and dictionaries. All of them are instances of predefined classes in Python.

To create our own classes we use the class keyword.

To create our own classes we use the class keyword.

By convention, the name of the class matches the name of the .py file and the module by consequence. It is also a good practice to organize the code.

By convention, the name of the class matches the name of the .py file and the module by consequence. It is also a good practice to organize the code.

Create a file vehicle.py with the following class Vehicle.

Create a file vehicle.py with the following class Vehicle .

class Vehicle:def __init__(self, year, model, plate_number, current_speed = 0):self.year = yearself.model = modelself.plate_number = plate_numberself.current_speed = current_speeddef move(self):self.current_speed += 1def accelerate(self, value):self.current_speed += valuedef stop(self):self.current_speed = 0def vehicle_details(self):return self.model + ', ' + str(self.year) + ', ' + self.plate_number

Let's break down the class to explain it in parts.

Let's break down the class to explain it in parts.

The class keyword is used to specify the name of the class Vehicle.

The class keyword is used to specify the name of the class Vehicle .

The __init__ function is a built-in function that all classes have. It is called when an object is created and is often used to initialize the attributes, assigning values to them, similar to what is done to variables.

The __init__ function is a built-in function that all classes have. It is called when an object is created and is often used to initialize the attributes, assigning values to them, similar to what is done to variables.

The first parameter self in the __init__ function is a reference to the object (instance) itself. We call it self by convention and it has to be the first parameter in every instance method, as you can see in the other method definitions def move(self), def accelerate(self, value), def stop(self), and def vehicle_details(self).

The first parameter self in the __init__ function is a reference to the object (instance) itself. We call it self by convention and it has to be the first parameter in every instance method, as you can see in the other method definitions def move(self) , def accelerate(self, value) , def stop(self) , and def vehicle_details(self) .

Vehicle has 5 attributes (including self): year, model, plate_number, and current_speed.

Vehicle has 5 attributes (including self): year , model , plate_number , and current_speed .

Inside the __init__, each one of them is initialized with the parameters given when the object is instantiated.

Inside the __init__ , each one of them is initialized with the parameters given when the object is instantiated.

Notice that current_speed is initialized with 0 by default, meaning that if no value is given, current_speed will be equal to 0 when the object is first instantiated.

Notice that current_speed is initialized with 0 by default, meaning that if no value is given, current_speed will be equal to 0 when the object is first instantiated.

Finally, we have three methods to manipulate our vehicle regarding its speed: def move(self), def accelerate(self, value), and def stop(self).

Finally, we have three methods to manipulate our vehicle regarding its speed: def move(self) , def accelerate(self, value) , and def stop(self) .

And one method to give back information about the vehicle: def vehicle_details(self).

And one method to give back information about the vehicle: def vehicle_details(self) .

The implementation inside the methods work the same way as in functions. You can also have a return to give you back some value at the end of the method as demonstrated by def vehicle_details(self).

The implementation inside the methods work the same way as in functions. You can also have a return to give you back some value at the end of the method as demonstrated by def vehicle_details(self) .

Using the Class (Using the Class)

To use the class in your terminal, import the Vehicle class from the vehicle module.

To use the class in your terminal, import the Vehicle class from the vehicle module.

Create an instance called my_car, initializing year with 2009, model with 'F8', plate_number with 'ABC1234', and current_speed with 100.

Create an instance called my_car , initializing year with 2009, model with 'F8', plate_number with 'ABC1234', and current_speed with 100.

The self parameter is not taken into consideration when calling methods. The Python interpreter infers its value as being the current object/instance automatically, so we just have to pass the other arguments when instantiating and calling methods.

The self parameter is not taken into consideration when calling methods. The Python interpreter infers its value as being the current object/instance automatically, so we just have to pass the other arguments when instantiating and calling methods.

Now use the methods to move() the car which increases its current_speed by 1, accelerate(10) which increases its current_speed by the value given in the argument, and stop() which sets the current_speed to 0.

Now use the methods to move() the car which increases its current_speed by 1, accelerate(10) which increases its current_speed by the value given in the argument, and stop() which sets the current_speed to 0.

Remember to print the value of current_speed at every command to see the changes.

Remember to print the value of current_speed at every command to see the changes.

To finish the test, call vehicle_details() to print the information about our vehicle.

To finish the test, call vehicle_details() to print the information about our vehicle.

>>> from vehicle import Vehicle
>>>
>>> my_car = Vehicle(2009, 'F8', 'ABC1234', 100)
>>> print(my_car.current_speed)
100
>>> my_car.move()
>>> print(my_car.current_speed)
101
>>> my_car.accelerate(10)
>>> print(my_car.current_speed)
111
>>> my_car.stop()
>>> print(my_car.current_speed)
0
>>> print(my_car.vehicle_details())
F8, 2009, ABC1234

If we don't set the initial value for current_speed, it will be zero by default as stated before and demonstrated in the next example.

If we don't set the initial value for current_speed , it will be zero by default as stated before and demonstrated in the next example.

>>> from vehicle import Vehicle
>>>
>>> my_car = Vehicle(2009, 'F8', 'ABC1234')
>>> print(my_car.current_speed)
0
>>> my_car.move()
>>> print(my_car.current_speed)
1
>>> my_car.accelerate(10)
>>> print(my_car.current_speed)
11
>>> my_car.stop()
>>> print(my_car.current_speed)
0
>>> print(my_car.vehicle_details())
F8, 2009, ABC1234

遺產 (Inheritance)

Let's define a generic Vehicle class and save it inside the vehicle.py file.

Let's define a generic Vehicle class and save it inside the vehicle.py file.

class Vehicle:def __init__(self, year, model, plate_number, current_speed):self.year = yearself.model = modelself.plate_number = plate_numberself.current_speed = current_speeddef move(self):self.current_speed += 1def accelerate(self, value):self.current_speed += valuedef stop(self):self.current_speed = 0def vehicle_details(self):return self.model + ', ' + str(self.year) + ', ' + self.plate_number

A vehicle has attributes year, model, plate_number, and current_speed.

A vehicle has attributes year , model , plate_number , and current_speed .

The definition of vehicle in the Vehicle is very generic and might not be suitable for trucks, for instance, because it should include a cargo attribute.

The definition of vehicle in the Vehicle is very generic and might not be suitable for trucks, for instance, because it should include a cargo attribute.

On the other hand, a cargo attribute does not make much sense for small vehicles like motorcycles.

On the other hand, a cargo attribute does not make much sense for small vehicles like motorcycles.

To solve this we can use inheritance.

To solve this we can use inheritance .

When a class (child) inherits another class (parent), all the attributes and methods from the parent class are inherited by the child class.

When a class (child) inherits another class (parent), all the attributes and methods from the parent class are inherited by the child class.

Parent and Child (Parent and Child)

In our case, we want a new Truck class to inherit everything from the Vehicle class. Then we want it to add its own specific attribute current_cargo to control the addition and removal of cargo from the truck.

In our case, we want a new Truck class to inherit everything from the Vehicle class. Then we want it to add its own specific attribute current_cargo to control the addition and removal of cargo from the truck.

The Truck class is called a child class that inherits from its parent class Vehicle.

The Truck class is called a child class that inherits from its parent class Vehicle .

A parent class is also called a superclass while a child class is also known as a subclass.

A parent class is also called a superclass while a child class is also known as a subclass .

Create the class Truck and save it inside the truck.py file.

Create the class Truck and save it inside the truck.py file.

from vehicle import Vehicleclass Truck(Vehicle):def __init__(self, year, model, plate_number, current_speed, current_cargo):super().__init__(year, model, plate_number, current_speed)self.current_cargo = current_cargodef add_cargo(self, cargo):self.current_cargo += cargodef remove_cargo(self, cargo):self.current_cargo -= cargo

Let's break down the class to explain it in parts.

Let's break down the class to explain it in parts.

The class Vehicle inside the parentheses when defining the class Truck indicates that the parent Vehicle is being inherited by its child Truck.

The class Vehicle inside the parentheses when defining the class Truck indicates that the parent Vehicle is being inherited by its child Truck .

The __init__ method has self as its first parameter, as usual.

The __init__ method has self as its first parameter, as usual.

The parameters year, model, plate_number, and current_speed are there to match the ones in the Vehicle class.

The parameters year , model , plate_number , and current_speed are there to match the ones in the Vehicle class.

We added a new parameter current_cargo suited for the Truck class.

We added a new parameter current_cargo suited for the Truck class.

In the first line of the __init__ method of the Truck class we have to call the __init__ method of the Vehicle class.

In the first line of the __init__ method of the Truck class we have to call the __init__ method of the Vehicle class.

To do that we use super() to make a reference to the supperclass Vehicle, so when super().__init__(year, model, plate_number, current_speed) is called we avoid repetition of our code.

To do that we use super() to make a reference to the supperclass Vehicle , so when super().__init__(year, model, plate_number, current_speed) is called we avoid repetition of our code.

After that, we can assign the value of current_cargo normally.

After that, we can assign the value of current_cargo normally.

Finally, we have two methods to deal with the current_cargo: def add_cargo(self, cargo):, and def remove_cargo(self, cargo):.

Finally, we have two methods to deal with the current_cargo : def add_cargo(self, cargo): , and def remove_cargo(self, cargo): .

Remember that Truck inherits attributes and methods from Vehicle, so we also have an implicit access to the methods that manipulate the speed: def move(self), def accelerate(self, value), and def stop(self).

Remember that Truck inherits attributes and methods from Vehicle , so we also have an implicit access to the methods that manipulate the speed: def move(self) , def accelerate(self, value) , and def stop(self) .

Using the Truck class (Using the Truck class)

To use the class in your terminal, import the Truck class from the truck module.

To use the class in your terminal, import the Truck class from the truck module.

Create an instance called my_truck, initializing year with 2015, model with 'V8', plate_number with 'XYZ1234', current_speed with 0, and current_cargo with 0.

Create an instance called my_truck , initializing year with 2015, model with 'V8', plate_number with 'XYZ1234', current_speed with 0, and current_cargo with 0.

Use add_cargo(10) to increase current_cargo by 10, remove_cargo(4), to decrease current_cargo by 4.

Use add_cargo(10) to increase current_cargo by 10, remove_cargo(4) , to decrease current_cargo by 4.

Remember to print the value of current_cargo at every command to see the changes.

Remember to print the value of current_cargo at every command to see the changes.

By inheritance, we can use the methods from the Vehicle class to move() the truck which increases its current_speed by 1, accelerate(10) which increases its current_speed by the value given in the argument, and stop() which sets the current_speed to 0.

By inheritance, we can use the methods from the Vehicle class to move() the truck which increases its current_speed by 1, accelerate(10) which increases its current_speed by the value given in the argument, and stop() which sets the current_speed to 0.

Remember to print the value of current_speed at every interaction to see the changes.

Remember to print the value of current_speed at every interaction to see the changes.

To finish the test, call vehicle_details() inherited from the Vehicle class to print the information about our truck.

To finish the test, call vehicle_details() inherited from the Vehicle class to print the information about our truck.

>>> from truck import Truck
>>> 
>>> my_truck = Truck(2015, 'V8', 'XYZ1234', 0, 0)
>>> print(my_truck.current_cargo)
0
>>> my_truck.add_cargo(10)
>>> print(my_truck.current_cargo)
10
>>> my_truck.remove_cargo(4)
>>> print(my_truck.current_cargo)
6
>>> print(my_truck.current_speed)
0
>>> my_truck.accelerate(10)
>>> print(my_truck.current_speed)
10
>>> my_truck.stop()
>>> print(my_truck.current_speed)
0
>>> print(my_truck.vehicle_details())
V8, 2015, XYZ1234

例外情況 (Exceptions)

Errors are a part of every programmer's life, and knowing how to deal with them is a skill on its own.

Errors are a part of every programmer's life, and knowing how to deal with them is a skill on its own.

The way Python deals with errors is called 'Exception Handling'.

The way Python deals with errors is called 'Exception Handling'.

If some piece of code runs into an error, the Python interpreter will raise an exception.

If some piece of code runs into an error, the Python interpreter will raise an exception.

Types of Exceptions (Types of Exceptions)

Let's try to raise some exceptions on purpose and see the errors they produce.

Let's try to raise some exceptions on purpose and see the errors they produce.

  • TypeError

    TypeError

First, try to add a string and an integer

First, try to add a string and an integer

'I am a string' + 32
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: must be str, not int
  • IndexError

    IndexError

Now, try to access an index that doesn't exist in a list.

Now, try to access an index that doesn't exist in a list.

A common mistake is to forget that sequences are 0-indexed, meaning the first item has index 0, not 1.

A common mistake is to forget that sequences are 0-indexed, meaning the first item has index 0, not 1.

In this example, the list car_brands ends at index 2.

In this example, the list car_brands ends at index 2.

car_brands = ['ford', 'ferrari', 'bmw']
print(car_brands[3])
Traceback (most recent call last):File "<stdin>", line 1, in <module>
IndexError: list index out of range
  • NameError

    NameError

If we try to print a variable that doesn't exist:

If we try to print a variable that doesn't exist:

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

    ZeroDivisionError

Math doesn't allow division by zero, so trying to do so will raise an error, as expected.

Math doesn't allow division by zero, so trying to do so will raise an error, as expected.

32/0
Traceback (most recent call last):File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

This was just a sample of the kinds of exceptions you might see during your daily routine and what can cause each of them.

This was just a sample of the kinds of exceptions you might see during your daily routine and what can cause each of them.

Exception Handling (Exception Handling)

Now we know how to cause errors that will crash our code and show us some message saying something is wrong.

Now we know how to cause errors that will crash our code and show us some message saying something is wrong.

To handle these exceptions just make use of the try/except statement.

To handle these exceptions just make use of the try/except statement.

try:32/0
except:print('Dividing by zero!')
Dividing by zero!

The example above shows the use of the try statement.

The example above shows the use of the try statement.

Put the block of code that may cause an exception inside the try scope. If everything runs alright, the except block is not invoked. But if an exception is raised, the block of code inside the except is executed.

Put the block of code that may cause an exception inside the try scope. If everything runs alright, the except block is not invoked. But if an exception is raised, the block of code inside the except is executed.

This way the program doesn't crash and if you have some code after the exception, it will keep running if you want it to.

This way the program doesn't crash and if you have some code after the exception, it will keep running if you want it to.

Specific Exception Handling (Specific Exception Handling)

In the last example the except block was generic, meaning it was catching anything.

In the last example the except block was generic, meaning it was catching anything.

Good practice it to specify the type of exception we are trying to catch, which helps a lot when debugging the code later.

Good practice it to specify the type of exception we are trying to catch, which helps a lot when debugging the code later.

If you know a block of code can throw an IndexError, specify it in the except:

If you know a block of code can throw an IndexError , specify it in the except :

try:car_brands = ['ford', 'ferrari', 'bmw']print(car_brands[3])
except IndexError:print('There is no such index!')
There is no such index!

You can use a tuple to specify as many exception types as you want in a single except:

You can use a tuple to specify as many exception types as you want in a single except :

try:print('My code!')
except(IndexError, ZeroDivisionError, TypeError):print('My Excepetion!')

else (else)

It is possible to add an else command at the end of the try/except. It runs only if there are no exceptions.

It is possible to add an else command at the end of the try/except . It runs only if there are no exceptions.

my_variable = 'My variable'
try:print(my_variable)
except NameError:print('NameError caught!')
else:print('No NameError')
My variable
No NameError

Raising Exceptions (Raising Exceptions)

The raise command allows you to manually raise an exception.

The raise command allows you to manually raise an exception.

This is particularly useful if you want to catch an exception and do something with it -- like logging the error in some personalized way like redirecting it to a log aggregator, or ending the execution of the code since the error should not allow the progress of the program.

This is particularly useful if you want to catch an exception and do something with it -- like logging the error in some personalized way like redirecting it to a log aggregator, or ending the execution of the code since the error should not allow the progress of the program.

try:raise IndexError('This index is not allowed')
except:print('Doing something with the exception!')raise
Doing something with the exception!
Traceback (most recent call last):File "<stdin>", line 2, in <module>
IndexError: This index is not allowed

finally (finally)

The finally block is executed independently of exceptions being raised or not.

The finally block is executed independently of exceptions being raised or not.

They are usually there to allow the program to clean up resources like files, memory, network connections, etc.

They are usually there to allow the program to clean up resources like files, memory, network connections, etc.

try:print(my_variable)
except NameError:print('Except block')
finally:print('Finally block')
Except block
Finally block

結論 (Conclusion)

That's it!

而已!

Congratulations on reaching the end.

Congratulations on reaching the end.

I want to thank you for reading this article.

I want to thank you for reading this article.

If you want to learn more, checkout my blog renanmf.com.

If you want to learn more, checkout my blog renanmf.com .

Remember to download a PDF version of this Python Guide for Beginners.

Remember to download a PDF version of this Python Guide for Beginners .

You can also find me on Twitter: @renanmouraf.

You can also find me on Twitter: @renanmouraf .

翻譯自: https://www.freecodecamp.org/news/the-python-guide-for-beginners/

python初學者

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/390381.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390381.shtml
英文地址,請注明出處:http://en.pswp.cn/news/390381.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

z-index

z-index 這個東西非常簡單&#xff0c;它有四大特性&#xff0c;每個特性你記住了&#xff0c;頁面布局就不會出現找不到盒子的情況。 z-index 值表示誰壓著誰&#xff0c;數值大的壓蓋住數值小的&#xff0c;只有定位了的元素&#xff0c;才能有z-index,也就是說&#xff0c;不…

大型運輸行業實戰_day12_1_權限管理實現

1.業務分析 權限說的是不同的用戶對同一個系統有不同訪問權限,其設計的本質是:給先給用戶分配好URL,然后在訪問的時候判斷該用戶是否有當前訪問的URL. 2.實現 2.1數據庫設計標準5表權限結構 2.2.sql語句實現,根據用戶id查詢該用戶所有的資源 sql語句: SELECT ur.user_id, r.u…

aws python庫_如何使用Python,AWS和IEX Cloud創建自動更新股市數據的Excel電子表格

aws python庫Many Python developers in the financial world are tasked with creating Excel documents for analysis by non-technical users.金融界的許多Python開發人員的任務是創建Excel文檔&#xff0c;以供非技術用戶進行分析。 This is actually a lot harder than i…

37)智能指針(就是自動delete空間)

1&#xff09;問題引入&#xff1a; 在java或者在C中&#xff0c;一旦你new一個東西&#xff0c;那么必然有一個delete與之對應&#xff0c;比如&#xff1a; 1 int main&#xff08;&#xff09;2 {3 int* p new int&#xff08;&#xff09;&#xff1b;4 5 *…

linux 安裝maven

2019獨角獸企業重金招聘Python工程師標準>>> 目錄:/usr/local/maven 1.下載 wget http://mirrors.hust.edu.cn/apache/maven/maven-3/3.5.3/binaries/apache-maven-3.5.3-bin.tar.gz 2.解壓 tar -zxvf apache-maven-3.5.3-bin.tar.gz 3.配置 vi /etc/profile #講下面…

自由開發者怎么生存_如何作為自由開發者生存

自由開發者怎么生存It’s been 8 weeks since we started experiencing the dramatic impact of the COVID-19 pandemic. In that time, we’ve all borne witness to how this virus can impact our families, our communities, and our livelihood. 自我們開始體驗COVID-19大…

UUID生成字符串

在向數據庫插入新數據時&#xff0c;可能需要插入字符串形式的ID&#xff0c;這時使用UUID可以生成隨機字符串&#xff1a; String str UUID.randomUUID().toString(); 轉載于:https://www.cnblogs.com/suhfj-825/p/8260861.html

如何在React Native中使用react-navigation 5處理導航

React-navigation is the navigation library that comes to my mind when we talk about navigation in React Native. 當我們談論React Native中的導航時&#xff0c;React-navigation是我想到的導航庫。 Im a big fan of this library and its always the first solution I…

flask內置session原理

內置session原理 請求到來 當請求進來之后&#xff0c;先執行Flask對象的 __call__ 方法 def wsgi_app(self, environ, start_response):# 獲取請求相關數據&#xff0c;并進行封裝和加工ctx self.request_context(environ)# 將請求消息推送到堆棧中&#xff0c;并執行 open_s…

指針3

#include <stdio.h>/* 2018-05-28 如何通過被調函數修改主調函數普通變量的值1&#xff0c;實參必須為該普通變量的地址2,形參必須為指針變量3&#xff0c;在背調函數中通過*形參名 。。。。。的方式就可以修改主調函數相關變量的值*/f(int *i,int *j) {*i 4;*j 5;ret…

面試系統設計_系統設計面試問題–您應該知道的概念

面試系統設計You may have heard the terms "Architecture" or "System Design." These come up a lot during developer job interviews – especially at big tech companies.您可能已經聽說過“架構”或“系統設計”這兩個術語。 在開發人員工作面試中&…

8597 石子劃分問題 dpdp,只考慮第一次即可

8597 石子劃分問題 時間限制:500MS 內存限制:1000K提交次數:155 通過次數:53 題型: 編程題 語言: G;GCC;VC Description 給定n個石子&#xff0c;其重量分別為a1,a2,a3,...,an。 要求將其劃分為m份&#xff0c;每一份的劃分費用定義為這份石子中最大重量與最小重量差的平方。…

文章中嵌入代碼塊_如何在您的文章中嵌入多項選擇測驗問題

文章中嵌入代碼塊In my experience, supplementing study with practical exercises greatly improves my understanding of a topic. This is especially true when I can test my knowledge as I go and receive instant feedback for each question.以我的經驗&#xff0c;通…

mysql免安裝版配置

1.官網下載https://dev.mysql.com/downloads/mysql/ 2.將下載好的壓縮包mysql-5.7.20-winx64.zip解壓。 3.mysql解壓后&#xff0c;設置.ini文件&#xff0c;在加壓后的路徑中加一個my.ini文件 配置如下內容&#xff1a; # 設置mysql客戶端默認字符集 default-character-setutf…

各種IE(IE6-IE10)兼容問題一行代碼搞定

x-ua-compatible 用來指定IE瀏覽器解析編譯頁面的model x-ua-compatible 頭標簽大小寫不敏感&#xff0c;必須用在 head 中&#xff0c;必須在除 title 外的其他 meta 之前使用。 1、使用一行代碼來指定瀏覽器使用特定的文檔模式。 <meta http-equiv"x-ua-compatible&q…

802. 找到最終的安全狀態

在有向圖中&#xff0c;以某個節點為起始節點&#xff0c;從該點出發&#xff0c;每一步沿著圖中的一條有向邊行走。如果到達的節點是終點&#xff08;即它沒有連出的有向邊&#xff09;&#xff0c;則停止。 對于一個起始節點&#xff0c;如果從該節點出發&#xff0c;無論每…

元類型與類型的區別

元類型是指所有類型的類型。 元類型只能類型出現在類型標示位&#xff1b; 類型即能作為類型存在&#xff0c;出現在類型標示位&#xff1b; 也能作為變量存在&#xff0c;出現在元類型的變量位。 http://www.swift51.com/swift2.0/chapter3/03_Types.html#type_inheritance_cl…

css 動畫使用_如何在CSS中使用動畫

css 動畫使用使用CSS動畫 (Using CSS Animations) CSS animations add beauty to the webpages and make transitions from one CSS style to the other beautiful.CSS動畫可以使網頁更加美觀&#xff0c;并可以從一種CSS樣式過渡到另一種CSS樣式。 To create a CSS animation…

第01章—快速構建

spring boot 系列學習記錄&#xff1a;http://www.cnblogs.com/jinxiaohang/p/8111057.html 碼云源碼地址&#xff1a;https://gitee.com/jinxiaohang/springboot 一、Spring Initializr 使用教程 &#xff08;IntelliJ IDEA&#xff09; 具體步驟&#xff1a; 1、打開IDEA &am…

看板和scrum_看板VS Scrum-如何變得敏捷

看板和scrumScrum and Kanban are the two most popular project management techniques today in business. As a developer, I think its important to understand these processes as you will likely be heavily involved in them if you are part of a team. By understan…