python初學者_初學者使用Python的完整介紹

python初學者

A magical art of teaching a computer to perform a task is called computer programming. Programming is one of the most valuable skills to have in this competitive world of computers. We, as modern humans, are living with lots of gadgets such as smartphone, computers and much more digital inventions. One must agree that gadgets are nothing without programming.

教導計算機執行任務的神奇藝術稱為計算機編程。 在這個競爭激烈的計算機世界中,編程是最有價值的技能之一。 作為現代人類,我們生活在許多小工具中,例如智能手機,計算機和更多數字發明。 必須同意,如果沒有編程,則小工具一無是處。

Even though the programming languages started to evolve only before half a century ago, the rate of growth was very huge compared to any other man-made things. In this article, I will teach you my favorite language Python and how to learn a language.

即使編程語言僅在半個世紀之前才開始發展,但與任何其他人造事物相比,其增長速度還是非常巨大的。 在本文中,我將教您我最喜歡的語言Python以及如何學習語言。

Image for post
Photo by Austin Chan on Unsplash
由Austin Chan 攝于Unsplash

先做這個... (Do this first…)

Why do you want to learn to program?

為什么要學習編程?

Think deeply before reading further. I asked the same question to my students on the first day of a programming class. Most of the answers were the same as the following statements.

在進一步閱讀之前,請深思。 在編程課程的第一天,我向我的學生問了同樣的問題。 大多數答案與以下陳述相同。

“ I want a good job in a well-reputed software company so I need to learn a programming language ”

“我想在一個聲譽良好的軟件公司中找到一份好工作,所以我需要學習一種編程語言”

“ Learning a programming language will make me able to learn some advanced technologies like artificial intelligence and machine learning ”

“學習編程語言將使我能夠學習一些先進技術,例如人工智能和機器學習”

The major reason to learn a programming language is to get a job with a good salary or to learn more about some advanced technologies. If you are familiar with some tutorial websites and online courses, then you may know that they start the tutorial by writing the applications of the language.

學習編程語言的主要原因是獲得一份高薪的工作或更多地了解一些先進技術。 如果您熟悉某些教程網站和在線課程,那么您可能知道他們通過編寫該語言的應用程序來開始教程。

Learning with a purpose is not the right way. This is not going to be the right approach as that is followed by everyone. If you need to learn something do it with passion. While doing something, if it fills your heart with enthusiasm then you are in the right path.

有目的的學習不是正確的方法。 這不是每個人都遵循的正確方法。 如果您需要學習一些東西,那就去做吧。 在做某事時,如果它充滿熱情,那么您就走對了。

“Programming is not a subject. It is a basic ability of human brain.”

“編程不是主題。 這是人腦的基本能力。”

If you are a complete beginner to this language, try to learn it with your whole heart. This article is not going to make you a great developer. Only thing I can swear you that you will learn programming is a language of nature.

如果您是該語言的完整入門者,請嘗試全心學習。 本文不會使您成為一名出色的開發人員。 我只能向你發誓,你將學習編程是自然的語言。

為什么要使用Python? (Why Python among others?)

In this world, there are more than seven hundred programming languages available. But not everything gets noticed by all. I have started to learn programming in 2015. I just started with the language C. I still have respect on the C language. But, when I started learning python in 2019 I loved the language very much. The love is still alive. I don’t know the reason for that. It may be a clean syntax. It may be the high readability of code. But something attracted me to stick with that language. I promise you that you will love the language and how it responds to the problems.

在這個世界上,有超過七百種編程語言可用。 但是并不是所有人都注意到所有事情。 我從2015年開始學習編程。我剛開始使用C語言。我仍然對C語言敬重。 但是,當我在2019年開始學習python時,我非常喜歡這種語言。 愛情仍然存在。 我不知道原因。 這可能是一種干凈的語法。 這可能是代碼的高可讀性。 但是某種吸引我的地方是那種語言。 我向您保證,您會喜歡這種語言及其對問題的回應。

Look at the quote by its Inventor Guido van Rossum.

查看其發明人Guido van Rossum的報價。

“The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code — not in reams of trivial code that bores the reader to death.”

“編寫Python的樂趣應該在于看到簡短,簡潔,易讀的類,這些類以少量清晰的代碼表達很多動作,而不是讓大量瑣碎的代碼使讀者無聊而死。”

Image for post
Photo by Hitesh Choudhary on Unsplash
Hitesh Choudhary 攝于Unsplash

Among all other languages, Python is worth considering due to its simplicity and readability of code. We, as humans, use many languages to convey some information to others. Programming is language to speak with computers. If you are looking for a computer language that is same as a human language then Python is the first choice.

在所有其他語言中,Python因其簡單性和代碼可讀性而值得考慮。 作為人類,我們使用多種語言向他人傳達某些信息。 編程是與計算機交談的語言。 如果您正在尋找與人類語言相同的計算機語言,那么Python是首選。

When you are speaking with someone, you don’t need to mention what type of information you are speaking about. The person who is hearing your talk can understand that without any external aid. Python works in the same way. Not like other popular languages, It works great without declaring the data type.

與某人交談時,無需提及您要談論的信息類型。 聽到您講話的人可以理解,而無需任何外部幫助。 Python的工作方式相同。 與其他流行語言不同,它無需聲明數據類型就可以很好地工作。

The following topics will be covered in this article. This will help you to know most of the basic things in programming.

本文將介紹以下主題。 這將幫助您了解編程中的大多數基本知識。

💥 How to Print something in Python?

如何在Python中打印內容?

💥 Concept of using Variable name

Variable使用變量名的概念

💥 Data Types in Python

Python Python中的數據類型

💥 Comments in Python

Python Python中的注釋

💥 Operators and Their functions

💥運算符及其功能

💥 Decision Making and Repetition

💥決策與重復

💥 Looping statements

💥循環語句

💥 Strings in Python

Python Python中的字符串

💥 List in Python

Python Python清單

💥 Tuple in Python

Python Python中的元組

💥 Set in Python

in用Python設置

💥 Dictionary in Python

💥Python中的字典

💥 Functions in Python

Python Python中的函數

💥 Object Oriented Programming

Or面向對象編程

💥 File System in Python

Python Python中的文件系統

如何在Python中打印內容? (How to Print something in Python?)

A program should able to tell something to the user after compiling the code. The computer will give some data after getting some set of instruction from the user. The data given by the computer is called output. The instructions are written using programing language. A computer processor will process the information and gives the output in human understandable form.

程序在編譯代碼后應該能夠告訴用戶一些信息。 在從用戶那里獲得一些指令集之后,計算機將提供一些數據。 計算機提供的數據稱為輸出。 這些指令是使用編程語言編寫的。 計算機處理器將處理該信息,并以人類可以理解的形式給出輸出。

Python follows a technique called interpretation to do this. There are many opensource and commercial IDEs are available. You can use some online interpreters such as repl.it. Click the following link to practice the code examples.

Python遵循一種稱為解釋的技術來執行此操作。 有許多開源和商業IDE。 您可以使用一些在線解釋器,例如repl.it。 單擊以下鏈接練習代碼示例。

Image for post
Repl.it Python復制Python

https://repl.it/languages/python

https://repl.it/languages/python

Imagine, computer as your friend. Look at the imaginary conversation between two friends meeting each other in a park.

想象一下,計算機是您的朋友。 看看兩個朋友在公園里見面時的假想對話。

Person 1 : Hello. {Statement - Information}

人1: 你好。 {聲明-信息}

Person 1 : Do you remember me? {Question}

第一個人: 你還記得我嗎? {題}

Person 2 : Sorry. I don’t remember you. {Statement - Reply}

第二個人: 對不起。 我不記得你了 {聲明-回復}

Person 2: May I know your name, please ? {Question}

第二個人: 請問您叫什么名字? {題}

Person 1: I am Felix. {Statement - Reply}

人1: 我是費利克斯。 {聲明-回復}

Person 1: We studied in high school together. {Statement - Information}.

人1: 我們一起在高中學習。 {聲明-信息}。

This is a simple conversation between two persons. If you can understand the definitions given at the end of each dialogue , then you can understand how a program works. A computer program may have a input and gives us at least one output from that.

這是兩個人之間的簡單對話。 如果您可以理解每次對話末尾給出的定義,那么您可以了解程序的工作方式。 一個計算機程序可能有一個輸入,并從中提供至少一個輸出。

The output screen in the development environment is called a console. We can able to print something in the console using two different methods. They are print() and input().

開發環境中的輸出屏幕稱為控制臺。 我們可以使用兩種不同的方法在控制臺中打印內容。 它們是print()input()

Take the first line of the conversation. That is a simple information. The sentence does not requires anything from the another node. We can use the keyword print() for this kind of purpose.

進行對話的第一行。 那是一個簡單的信息。 該句子不需要其他節點的任何內容。 為此,我們可以使用關鍵字print()

The second line is question that requires a response from the another one. This kind of information can be printed using input() method. When we use the input method the user must enter some values in the output console.

第二行是需要另一個回答的問題。 可以使用input()方法打印此類信息。 當我們使用輸入法時,用戶必須在輸出控制臺中輸入一些值。

In practice, print is used for printing some information and the input is used for getting input from the user.

在實踐中, print用于打印某些信息, input用于獲取用戶的輸入。

Always remember one thing. You have to put something after the execution of input statements. Let us re-design the conversation into a program in python.

永遠記住一件事。 您必須在輸入語句執行后放一些東西。 讓我們將對話重新設計為python程序。

print("Hello.")

Output

輸出量

Hello.

This program is used to print the statement without any requirement from the second person or the user. The print function just prints whatever the information passed inside the quotes. We can the print function in different ways. Look at the following code.

該程序用于打印對帳單,而無需第二人稱或用戶的任何要求。 打印功能僅打印引號內傳遞的所有信息。 我們可以用不同的方式打印功能。 看下面的代碼。

print("First Line")print("Second Line")print('''This
is Multi Line''')

Output

輸出量

First Line
Second Line
This
is Multi Line

Before doing something with input() function we have understand the concept of variable.

在使用input()函數進行操作之前,我們已經了解了變量的概念。

使用變量名的概念 (Concept of using Variable Name)

Look at the second line of the conversation. The first person asking a question to the second one. Now, think about your brain. Human brain contains a large collection of memories. When someone asking about your best friend, you will get your friends image in your mind. Right?.

查看對話的第二行。 第一個人向第二個人問一個問題。 現在,考慮一下您的大腦。 人腦包含大量回憶。 當有人問起你最好的朋友時,你會在腦海中浮現出你的朋友形象。 對?。

The brain contains a image of many people. While thinking about your friend you get the correct imagination as your brain stored the memories with some name. In programming the name that addresses a data stored in memory location is called variable.

大腦包含許多人的形象。 在思考您的朋友時,您會得到正確的想象力,因為您的大腦以一些名字存儲了回憶。 在編程時,尋址存儲在存儲器中的數據的名稱稱為變量。

In the above conversation. The second person gives some response which must be stored in the first persons brain. In computer science, this can be done by using input keyword. The syntax for using a variable name is given below.

在上面的對話中。 第二個人給出一些必須存儲在第一個人大腦中的響應。 在計算機科學中,這可以通過使用input關鍵字來完成。 下面給出了使用變量名的語法。

variable_name = value

variable_name = value

or

要么

variable_name = input("Statement")

variable_name = input("Statement")

I hope you understood the importance of input(), print() and Variable name in Python.

我希望您了解Python中input()print()和Variable name的重要性。

The complete conversation is converted as python program here.

完整的對話在此處轉換為python程序。

print("Hello.")
answer_1 = input("Do you remember me? ")
answer_2 = input("May I know your name, please? ")
print("We studied in high school together.")

Output

輸出量

Hello.
Do you remember me? Sorry. I don't Re remm ember you.
May I know your name, please? I am Felix
We studied in high school together.

Practice the code by your own to know the program get executed by step by step. The darken letters in the output column are typed by the user.

自己練習代碼,以逐步了解該程序。 用戶在輸出列中輸入較暗的字母。

變量命名規則 (Rules for naming a variable)

In python there are set of rules to be followed while creating a variable name.

在python中,創建變量名稱時要遵循一組規則。

? A variable name can have alphabets (A-z), Numbers(0–9) and Underscore( _ ).

variable變量名可以包含字母(Az),數字(0–9)和下劃線(_)。

? A variable name should not start with any number.

?變量名不能以任何數字開頭。

? A variable name cannot have any special characters in it.

variable變量名稱中不能包含任何特殊字符。

? The variable name could not be a keyword in Python.

?變量名稱不能是Python中的關鍵字。

Python中的數據類型 (Data Types in Python)

Let me ask you three questions. What is your name? What is your age? Are you interested in learning Python? After answering these questions, look at the answers. Each answer is in different type. The first is a type of text-based data. The second one is numerical data. The third one is categorical data.

讓我問你三個問題。 你叫什么名字? 你幾歲? 您對學習Python感興趣嗎? 回答這些問題后,請查看答案。 每個答案的類型不同。 第一種是基于文本的數據。 第二個是數值數據。 第三個是分類數據。

Image for post
Photo by Jason Leung on Unsplash
照片由Jason Leung在Unsplash上拍攝

So the basic classification of data types is texts, numbers and yes or no type. The reason for classifying the data is each type behaves differently. From your age, we can calculate the age after two years. But I can’t do the same operation with text-based data. In programming, the text-based data is called a string.

因此,數據類型的基本分類是文本,數字以及是或否類型。 對數據進行分類的原因是每種類型的行為都不同。 根據您的年齡,我們可以計算出兩年后的年齡。 但是我不能對基于文本的數據執行相同的操作。 在編程中,基于文本的數據稱為字符串。

The numerical data can be classified into two types. One is int and another one is float. An int is a whole number whereas the float type is used for numbers with decimal places. The third type is called a boolean data type which contains only two values “True” and “False”.

數值數據可以分為兩種類型。 一個是int ,另一個是float。 int是整數,而float類型用于帶小數位的數字。 第三種類型稱為布爾數據類型,它僅包含兩個值“ True ”和“ False ”。

We have already seen how to get a string from the user and how to print it to the console. Getting a numerical value is also same. But the input value is always in the form of string.

我們已經看到了如何從用戶那里獲取字符串以及如何將其打印到控制臺。 獲取數值也相同。 但是輸入值始終為字符串形式。

Now age is a numerical data. To ask a numerical data, the input command should be passed through the int() . If someone asks for your age, you will say like 25 or 30. The answer is same as the answer for any other questions. But after hearing that answer, your brain will recognize it is a numerical data. This is how our brain works. int() does the same thing in programming.

現在年齡是一個數值數據。 要詢問數值數據,輸入命令應通過int()傳遞。 如果有人問您的年齡,您會說25或30歲。答案與其他任何問題的答案相同。 但是,在聽到這個答案之后,您的大腦就會意識到這是一個數字數據。 這就是我們大腦的工作方式。 int()在編程中做同樣的事情。

age = int(input(what is your age?))
print("Your age is",age)

Output…

輸出…

what is your age? 26
Your age is 26

Try the same for float value with the help of float() .

float()的幫助下,對float值嘗試相同的操作。

type() keyword

type()關鍵字

type() is used to find the data type of a variable. Consider the following code.

type()用于查找變量的數據類型。 考慮下面的代碼。

name = "Felix"
age = 23
print(type(name))
print(type(age))

Output will be

輸出將是

'str'
'int'

Python注釋 (Comments in Python)

Comments are some statements which are not considered as instruction to the computer. The comments can be used to write developer information or code usage or anything apart from the actual code.

注釋是一些陳述,不被視為對計算機的說明。 注釋可用于編寫開發人員信息或代碼用法或除實際代碼外的任何內容。

The comment will be of two types. Single line comments and multiple line comments.

評論將分為兩種類型。 單行注釋和多行注釋。

Single line comments are created using # .

使用#創建單行注釋。

Multi Line comments are created using ''' Your Comment Here ''' .

多行注釋是使用''' Your Comment Here '''

#Single Line comment
'''This is
a multi line
comment'''

運算符及其功能 (Operators and Their Functions)

Just storing and retrieving data is not enough in programming. Let us look at an example. You are going to a shop to get some chocolates. Now the price of chocolate is 4.99 $. You need ten chocolates in total. After collecting the chocolates you have to pay the bill. Now, how will you calculate the amount?.

在編程中僅存儲和檢索數據是不夠的。 讓我們來看一個例子。 你要去商店買些巧克力。 現在,巧克力的價格為4.99美元。 您總共需要十塊巧克力。 收集完巧克力后,您必須支付賬單。 現在,您將如何計算金額?

Image for post
Photo by Chris Liverani on Unsplash
Chris Liverani在Unsplash上拍攝的照片

In this scenario, we can store the price of the chocolate in a float variable. But we have to multiply the cost into total chocolates to get the total price. This is simple elementary mathematics. But, how can a computer do this?. The use of operators takes place here. There are many operations like multiplication is available in mathematics. To perform those calculations in programming we are using some symbols called operators. A operator usually operates on two different operands.

在這種情況下,我們可以將巧克力的價格存儲在float變量中。 但是我們必須將成本乘以總巧克力才能得出總價。 這是簡單的基礎數學。 但是,計算機如何做到這一點? 在這里使用運算符。 數學中有很多運算,例如乘法。 為了在編程中執行這些計算,我們使用了一些稱為運算符的符號。 一個運算符通常對兩個不同的操作數進行運算。

Let us look at the algorithm for above situation.

讓我們看一下上述情況的算法。

PRICE = 4.99
COUNT = 10
TOTAL = PRICE * COUNT

Here operator is *.

這里的運算符是*。

Major classification of operators in python is listed below.

下面列出了python中運算符的主要分類。

🔹 Arithmetic Operators

🔹算術運算符

🔹 Assignment Operators

🔹賦值運算符

🔹 Comparison Operators

🔹比較運算符

🔹 Logical Operators

🔹邏輯運算符

🔹 Bit Wise Operators

🔹位明智算子

ARITHMETIC OPERATORS

算術運算符

Arithmetic operators are used for basic mathematical operations like addition subtraction, multiplication and division.

算術運算符用于基本的數學運算,例如加減法,乘法和除法。

Let a=30 and b=4.

設a = 30和b = 4。

Image for post
Arithmetic Operators
算術運算符

Python Program for above calculation.

用于上述計算的Python程序。

a = 30
b = 4
print(a + b)
print(a - b)
print(a * b)
print(a / b)
floor = a // b
print(floor)
mod = a % b
power = a ** b
print(mod)
print(power)

Output :

輸出:

34
26
120
7.5
7
2
810000

ASSIGNMENT OPERATORS

轉讓經營者

Assignment operators are used to assign a value to a variable. The main assignment operator is = .

賦值運算符用于為變量賦值。 主要的賦值運算符是=。

In price = 50 , the value 50 is assigned to the price variable.

price = 50 ,將值50分配給price變量。

a = 50
b = 40
a = 60
print(a)
print(b)

Output:

輸出:

60
40

A variable will always have the value that assigned lastly. In the above program the last assignment for the variable ‘a’ is 60.

變量將始終具有最后分配的值。 在上面的程序中,變量“ a”的最后賦值為60。

Apart from the equal to (=) operator there are some assignment operators called short hand operator. These operators are used to store a value returned from a operation on a particular variable to the variable itself.

除了等于(=)運算符外,還有一些賦值運算符稱為簡寫運算符。 這些運算符用于將從對特定變量的操作返回的值存儲到變量本身。

+= is an example for short hand operator. If we use it in programming the syntax will be a+=b. The actual syntax for this expression is a = a + b. After adding the values of ‘a’ and ‘b’ the result is stored in ‘a’ itself.

+ =是速記員的示例。 如果我們在編程中使用它,語法將為a + = b。 該表達式的實際語法為a = a + b。 將“ a”和“ b”的值相加后,結果將存儲在“ a”本身中。

a = 40 
b = 60
a += b
print(a)

Output:

輸出:

100

Try this type of program with other short hand operators like -=, *=, /=, **= //= , %=. Almost all the arithmetic operators supports short hand operation.

與其他速記運算符(例如-=,* =,/ =,** = // =和%=)一起嘗試這種類型的程序。 幾乎所有的算術運算符都支持短手運算。

COMPARISON OPERATORS

比較運算符

Comparison operators are used to compare two variables. All comparison operators will return two things. ‘True’ and ‘False’.

比較運算符用于比較兩個變量。 所有比較運算符將返回兩件事。 '真假'。

Syntax: Operand1 Operator Operand2

語法: Operand1 運算符 Operand2

  • == is equality operator. If both values are equal it will return True otherwise it returns False.

    ==是相等運算符。 如果兩個值相等,它將返回True,否則返回False。
a = 10
b = 10
c = 20
print(a==b)
print(a==c)

Output:

輸出:

True
False
  • != is not equal operator. It acts opposite to the equality operator. This will return True only if the both values are different.

    !=不等于運算符。 它的作用與相等運算符相反。 僅當兩個值都不同時,才返回True。
a = 10
b = 10
c = 20
print(a!=b)
print(a!=c)

Output:

輸出:

False
True
  • > is greater than symbol. If operand1 is greater than operand2, it will return True otherwise zero.

    >大于符號。 如果操作數1大于操作數2,它將返回True,否則返回零。
a = 10
b = 10
c = 20
print(a > b)
print(c > a)
print(a > c)

Output:

輸出:

False
True
False
  • < is lesser than symbol. If operand1 is lesser than operand2, it will return True otherwise zero.

    <小于符號。 如果操作數1小于操作數2,則它將返回True,否則返回零。
a = 10
b = 10
c = 20
print(a < b)
print(c < a)
print(a < c)

Output:

輸出:

False
False
True
  • >= and <= are Greater than or equal to and less than or equal to operators respectively. These operators combines both the operations on > and equality operators. First one returns True if the value 1 is greater or equal to the second value.

    > =和<=分別大于或等于和小于或等于運算符。 這些運算符將>運算符和相等運算符組合在一起。 如果值1大于或等于第二個值,則第一個返回True。
a = 10
b = 10
c = 20
print(a >= b)
print(c >= a)
print(a >= c)

Output:

輸出:

True
True
False

Another example

另一個例子

a = 10
b = 10
c = 20
print(a <= b)
print(c <= a)
print(a <= c)

Output:

輸出:

True
False
True

LOGICAL OPERATORS

邏輯運算符

Logical operators are often used with the conditional statements. There are three logical operators in python. They are and, or and not.

邏輯運算符通常與條件語句一起使用。 python中有三個邏輯運算符。 它們是andor and not

It used between two boolean values.

它在兩個布爾值之間使用。

  • and returns True when both the conditions are same.

    并在兩個條件相同時返回True。

True and True returns True

True True返回True

True and False returns False

正確 錯誤返回False

False and True returns False

False True返回False

False and False returns True

False False返回True

a = 10
b = 10
c = 20
print(a==b and c>a) #(True and True)

Output:

輸出:

True
  • or returns True if any one of the value is True.

    或如果任何一個值為True,則返回True。

True and True returns True

True True返回True

True and False returns True

返回真

False and True returns True

False True返回True

False and False returns False

錯誤 錯誤返回錯誤

a = 10
b = 10
c = 20
print(a==b or a>b) #(True and False)print(a>b or c<b) #(False and False)

Output:

輸出:

True
False
  • not returns opposite of anything.

    返回任何東西相反。

Syntax: not expression

語法:不表達

not True returns False

不正確返回錯誤

not False returns True

不是False返回True

Write your own program for this…. 😉

為此編寫您自己的程序。 😉

決策與重復 (Decision Making and Repetition)

Decision making is an important skill in everyone life. In this part we are going to teach the computers to make decision. Let us imagine a situation. You are driving a car. Suddenly you are noticing that the red light is turned on in the signal. Now, what will you do?. You will apply the brake. Now, you are executing something called driving a car. During the execution, the car must be stopped only if you see the red color. This is an example of decision making. The exact thing can be achieved by decision control statements in Python. The decision control statements are given below.

決策是每個人生活中的一項重要技能。 在這一部分中,我們將教計算機進行決策。 讓我們想象一個情況。 您正在開車。 突然您注意到信號中的紅色指示燈已打開。 現在,你會怎么做? 您將剎車。 現在,您正在執行稱為駕駛汽車的操作。 在執行過程中,只有在看到紅色時才必須停止汽車。 這是決策的一個例子。 確切的事情可以通過Python中的決策控制語句來實現。 決策控制語句如下。

Image for post
Photo by Javier Allegue Barros on Unsplash
Javier Allegue Barros在Unsplash上拍攝的照片
  1. if

    如果
  2. if…else

    如果別的
  3. if…elif…else

    如果……否則……否則
  • if Statement:

    如果聲明:

if statement will check for a condition. If the condition return True then the statements given in the statements will be executed. Otherwise it do nothing.

if語句將檢查條件。 如果條件返回True,則將執行語句中給出的語句。 否則它什么也不做。

Syntax: if condition:

語法: if條件:

States: if True or if False. These are the two states in if condition. We have studied about various operators and expressions. After passing the expressions it will return True or False. If the returned value is True then the statements in that condition will be executed.

狀態:如果為True或False。 這是if條件下的兩個狀態。 我們研究了各種運算符和表達式。 傳遞表達式后,它將返回True或False。 如果返回值為True,則將執行該條件下的語句。

Example: Let a =10 and b = 20.

示例:令a = 10且b = 20。

Here if a<b: means if True: so that the statements in the if block is executed.

這里,如果a <b:表示是否為True:則執行if塊中的語句。

a = 10
b = 5
if a>b:
print("if condition satisfied")
print("Hello")

Output:

輸出:

if condition satisfied
Hello
  • if … else

    如果別的

In the previous one if the expression becomes if False: Then nothing will be executed. The else keyword makes it possible. If the condition in the ‘if’ is False then the statements in else part will be executed.

在上一個表達式中,如果表達式變為False:則不執行任何操作。 else關鍵字使之成為可能。 如果“ if”中的條件為False,則將執行else部分中的語句。

a = 10
b = 5
if a>b:
print("If is executed")
else:
print("else is executed")

Output:

輸出:

If is executed
  • if … elif … else

    如果... elif ...否則

If you have more than one conditions in your program, then this type of nested condition is used.

如果程序中有多個條件,則使用這種嵌套條件。

a = 1
b = 2
c = 3
if a>b and a>c:
print("a is greater")
elif b>a and b>c:
print("b is greater")
else:
print("c is greater")

After using : in if, elif and else expressions the statements must be given after 4 spaces in the next line. This is called indentation.

在if,elif和else表達式中使用:之后,必須在下一行的4個空格后給出語句。 這稱為縮進。

循環報表 (LOOPING STATEMENTS)

Looping or repeating the same type of operations again and again is important thing in programming. This kind of approach is called looping.

在編程中一次又一次地循環或重復相同類型的操作是很重要的。 這種方法稱為循環。

Image for post
Tine Ivani? on TineIvani?攝于UnsplashUnsplash

There are two types of keyword available in python. One is while and another on is for.

python中有兩種可用的關鍵字。 一個是一會兒,另一個是為。

  • while:

    而:

Syntax: while expression:

語法: while表達式:

The statements in the while block will be executed until the expression returns True each time.

while塊中的語句將一直執行,直到每次表達式返回True為止。

a = 5
while a>0:
print(a)
a = a-1
print("while loop executed")

Output:

輸出:

5
4
3
2
1
while loop executed

Each time the value returned from the expression is changing. Here at on point a will become 0. Now a>0 is False. When the while loop becomes False the execution will be stopped.

每次從表達式返回的值都會改變。 在這里,a將變為0。現在a> 0為False。 當while循環變為False時,將停止執行。

  • for loop

    for循環

Syntax: for variable in sequence:

語法:對于順序 變量

There are many sequence types available in python. But for now let us create a sequence with range() keyword.

python中有許多可用的序列類型。 但是現在讓我們創建一個帶有range()關鍵字的序列。

for x in range(5):

對于范圍x中的x(5):

In this expression, the range(5) will create a sequence from 0 to 4. Each time the consecutive numbers are assigned to the variable x.

在此表達式中,range(5)將創建一個從0到4的序列。每次將連續數字分配給變量x。

a = 5
for x in range(a):
print(x)
print("for loop executed")

Output:

輸出:

0
1
2
3
4
for loop executed

字符串的結構 (Structure of String)

In Python, string is a collection of uni-code characters arranged in a sequence. Each character of a string is placed in continuous positions called index. We can access the characters with the help of the index. The following diagram illustrates how the string “Happy Coding” is arranged using indexes.

在Python中,字符串是按順序排列的Unicode字符的集合。 字符串的每個字符都放置在稱為index連續位置中。 我們可以在索引的幫助下訪問字符。 下圖說明了如何使用索引來排列字符串“ Happy Coding”。

Image for post

Python allows both positive and negative indexing for the string. The index always starts with 0 in positive indexing.

Python允許對字符串進行正向和負向索引。 在正索引中,索引始終以0開頭。

The first Character can be accessed with the indexes 0 and -12 in this string.

可以使用該字符串中的索引0和-12訪問第一個字符。

如何創建一個字符串變量? (How to Create a String Variable?)

Creating a string variable is very simple. You can just assign a string to a variable name directly or by getting input from user. We know that a string can be printed directly in the console without any variable names in the following methods.

創建字符串變量非常簡單。 您可以直接將字符串分配給變量名,也可以從用戶那里獲取輸入。 我們知道,在以下方法中,無需任何變量名即可直接在控制臺中打印字符串。

print("I am a String")
or
print('I am a String')
or
print("""I am also a String""")
orprint('''Me too....''')

A string variable created by the following syntax.

通過以下語法創建的字符串變量。

variable_name = “String”

variable_name = “String”

Image for post
Syntax for String Creation
創建字符串的語法

To print the string, you don’t need to use any quotes. print(variable_name) is enough. Here is an example for creating string variable and printing it using Python.

要打印字符串,您不需要使用任何引號。 print(variable_name)就足夠了。 這是創建字符串變量并使用Python打印它的示例。

name = "Felix Antony"
print(name)

Output:

輸出:

Felix Antony

訪問字符串中的字符 (Accessing a Character in String)

I already stated that a character in a string can be accessed using index of a character in the string. Now, I create a string variable called statement which stores the string “Happy Coding” in it.

我已經說過,可以使用字符串中字符的索引來訪問字符串中的字符。 現在,我創建一個名為statement的字符串變量,該變量在其中存儲字符串“ Happy Coding”。

statement = "Happy Coding"

To access a character in a particular index, we have to put the index number inside square brackets [] at the end of variable name.

要訪問特定索引中的字符,我們必須將索引號放在變量名末尾的方括號[]中。

Image for post
Syntax for accessing a character
訪問字符的語法

Look at the following example which prints the characters in particular index.

請看下面的示例,該示例顯示特定索引中的字符。

statement = "Happy Coding"
print(statement[0])
print(statement[-12])
print(statement[3])
print(statement[-5])

Output:

輸出:

H
H
p
o

如果指數超過…怎么辦? (What if the index exceeds…)

What will happen, if you put an index that is not available. In the above example the maximum index is 11. So let us check what will happen while trying to access 13th index.

如果您放置一個不可用的索引,將會發生什么。 在上面的示例中,最大索引為11。因此,讓我們檢查在嘗試訪問第13個索引時會發生什么。

statement = "Happy Coding"
print(statement[13])

Output

輸出量

IndexError: string index out of range

This will create an error. So the Python Interpreter will through an exception on it.

這將產生一個錯誤。 因此,Python解釋器將通過其上的異常。

Python中的字符串方法 (String Methods in Python)

Methods are functions that associated with Objects in Python. In python everything is an object. String is also an object in Python. The string object supports some methods which returns some values after applying the methods on strings.

方法是與Python中的對象相關聯的函數。 在python中,一切都是對象。 字符串也是Python中的對象。 字符串對象支持某些方法,這些方法將方法應用于字符串后會返回一些值。

To simplify the concept, I classified the string methods available in python into four different types.

為了簡化概念,我將python中可用的字符串方法分為四種不同的類型。

💥 Character Conversion methods

💥字符轉換方法

💥 Type Checking Methods

💥類型檢查方法

💥 Sub String Methods

💥子字符串方法

💥 Alignment Methods

💥對準方法

字符轉換方法 (Character Conversion Methods)

Character conversion methods are used to convert the characters in string into different forms. The available character conversion methods for strings in python are given below.

字符轉換方法用于將字符串中的字符轉換為不同形式。 下面給出了python中字符串可用的字符轉換方法。

🎲 capitalize()

🎲capitalize()

🎲 casefold()

🎲casefold()

🎲 swapcase()

🎲swapcase()

🎲 upper()

🎲upper()

🎲 lower()

🎲lower()

🎲 title()

🎲title()

🔖 capitalize() Method

ize capitalize()方法

capitalize() Method converts the first character of a string to upper case. It doesn’t make any change if the first character is already in capitalized.

capitalize()方法將字符串的第一個字符轉換為大寫。 如果第一個字符已經大寫,則不會進行任何更改。

Image for post
Syntax for capitalize( ) method
大寫()方法的語法
string = "i love Python"
print(string.capitalize())orstring = "i love Python"
string = string.capitalize()
print(string)

Both program will give same outputs

兩個程序將給出相同的輸出

I love Python

🔖 casefold() Method

🔖casefold()方法

casefold() method is used to convert all the uppercase characters in a string into lower case characters.

casefold()方法用于將字符串中的所有大寫字符轉換為小寫字符。

Image for post
Syntax for casefold( ) method
casefold()方法的語法
string = "hApPy CoDinG"
print(string.casefold())

Output

輸出量

happy coding

🔖 swapcase() Method

case swapcase()方法

swapcase() method is used to convert the uppercase letters into lower case letters and lower case letters into uppercase letters.

swapcase()方法用于將大寫字母轉換為小寫字母,并將小寫字母轉換為大寫字母。

Image for post
Syntax for swapcase( ) method
swapcase()方法的語法
string = "hAPPY cODING"
print(string.swapcase())

Output

輸出量

Happy Coding

🔖upper() Method

🔖upper()方法

upper() is a string method which is used to capitalize all the characters in a string.

upper()是一個字符串方法,用于大寫字符串中的所有字符。

Image for post
Syntax for upper( ) method
upper()方法的語法
string = "Hello Python"
print(string.upper())

Output:

輸出:

HELLO PYTHON

🔖lower() Method

🔖lower()方法

lower() is also a string method which is used to convert the entire string into lowercase letters.

lower()也是一個字符串方法,用于將整個字符串轉換為小寫字母。

Image for post
Syntax for lower( ) method
lower()方法的語法
string = "Hello Python"
print(string.lower())

Output

輸出量

hello python

🔖title() Method

🔖title()方法

title() method converts the first characters of all the words in String.

title()方法轉換String中所有單詞的首字符。

Image for post
Syntax for title( ) method
title()方法的語法
string = "hello python"
print(string.title())

Output

輸出量

Hello Python

類型檢查方法 (Type Checking Methods)

The string method used for checking the type of character in python is known as type checking methods. The type checking methods are listed below.

用于檢查python中字符類型的字符串方法稱為類型檢查方法。 類型檢查方法如下所示。

🎲 isalpha()

🎲isalpha()

🎲 isnumeric()

🎲isnumeric()

🎲 isalnum()

🎲isalnum()

🎲 isupper()

🎲isupper()

🎲 islower()

low islower()

🎲 isidentifier()

🎲isidentifier()

🎲 istitle()

🎲istitle()

🎲 isspace()

🎲isspace()

🔖isalpha() Method

🔖isalpha()方法

isalpha() method is used to check all the characters in a string are alphabets. This method return True when all the characters are alphabets.

isalpha()方法用于檢查字符串中的所有字符是否都是字母。 當所有字符均為字母時,此方法返回True。

Image for post
Syntax for isalpha( ) method
isalpha()方法的語法
string = "hello"
print(string.isalpha())

Output

輸出量

True

🔖isnumeric() Method

🔖isnumeric()方法

isnumeric() method returns True if all the characters in the string are numbers.

如果字符串中的所有字符均為數字,則isnumeric()方法返回True。

Image for post
Sytax for isnumeric( ) method
isnumeric()方法的語法
string = "1234"
print(string.isnumeric())

Output

輸出量

True

🔖isalnum() Method

🔖isalnum()方法

isalnum() metthod returns True if the characters in a string are alphabets or numbers or combination of both.

如果字符串中的字符是字母,數字或兩者的組合,則isalnum()方法返回True。

Image for post
Syntax for isalnum( ) method
isalnum()方法的語法
string = "str123"
print(string.isalnum())

Output

輸出量

True

🔖isupper() and islower() Methods

upisupper()和islower()方法

isupper() method returns True if all the characters in a string are uppercase letters whereas islower() will return True if all the characters are lowercase letters.

如果字符串中的所有字符均為大寫字母,則isupper()方法返回True;而如果所有字符均為小寫字母,則islower()將返回True。

Image for post
Syntax for isupper( ) method
isupper()方法的語法
Image for post
Image for post
Syntax for islower( ) method
islower()方法的語法
string1 = "HELLO"
string2 = "python"
print(string1.isupper())
print(string2.islower())

Output

輸出量

True
True

🔖isidentifier() Method

identisidentifier()方法

isidentifier() Method is used to check whether a string can be an identifier or not. We have already seen the conditions to follow while creating a variable name in our previous article. This method return True if the string can be a identifier.

isidentifier()方法用于檢查字符串是否可以是標識符。 在上一篇文章中,我們已經看到了在創建變量名時要遵循的條件。 如果字符串可以是標識符,則此方法返回True。

Image for post
Syntax for isidentifier( ) method
isidentifier()方法的語法
string1 = "var_1"
string2 = "2var"
print(string1.isidentifier())
print(string2.isidentifier())

Output

輸出量

True
False

🔖isspace() Method

spaceisspace()方法

If all the characters in a string are white spaces, then isspace() method will return True.

如果字符串中的所有字符都是空格,則isspace()方法將返回True。

Image for post
Syntax for isspace( ) method
isspace()方法的語法
string = "    "
print(string.isspace())

Output

輸出量

True

🔖istitle()

🔖istitle()

istitle() is used to check whether a string is a title or not.

istitle()用于檢查字符串是否為標題。

Image for post
Syntax for istitle( ) method
istitle()方法的語法
string = "Hello Python"
print(string.istitle())

Output

輸出量

True

基于子字符串的方法 (Sub String Based Methods)

A part of string is called sub string. Consider the string ‘cat’. The sub strings of this string are, ‘c’, ‘a’, ‘t’, ‘ca’, ‘at’, ‘cat’. There are some methods are available based on the sub string processing in Python.

字符串的一部分稱為子字符串。 考慮字符串“ cat”。 該字符串的子字符串為“ c”,“ a”,“ t”,“ ca”,“ at”,“ cat”。 有一些基于Python中子字符串處理的方法。

🎲 count()

🎲count()

🎲 startswith()

🎲startswith()

🎲 endswith()

with endswith()

🎲 find()

🎲find()

🎲 rfind()

🎲rfind()

🎲 index()

🎲index()

🎲 rindex()

🎲rindex()

🎲 replace()

🎲replace()

🔖 count() Method

🔖count()方法

count() method is used to count the number of time a sub string occurs in a string.

count()方法用于計算子字符串在字符串中出現的時間。

Image for post
Syntax for count( ) method
count()方法的語法
string = "I am learning Python"
print(string.count("a"))

Output

輸出量

2

🔖 startswith() Method

🔖startswith()方法

startswith() method is used to check whether a string is starting with the given sub string or not.

startswith()方法用于檢查字符串是否以給定的子字符串開頭。

Image for post
Syntax for startswith( ) method
startswith()方法的語法
string = "Happy Coding"
print(string.startswith("Hap"))

Output

輸出量

True

🔖 endswith() Method

🔖endswith()方法

endswith() method returns True if the string ends with the given sub string.

如果字符串以給定的子字符串結尾,則endswith()方法返回True。

Image for post
Syntax for endswith( ) method
endswith()方法的語法
string = "Happy COding"
print(string.endswith("ing"))

Output

輸出量

True

🔖 index() and find() Methods

🔖index()和find()方法

index() and find() methods are used to find the index of the sub string where it occurs for the first time. The only difference between the both is find() will return -1 if the sub string is not available in the string whereas the index() method creates an exception.

index()和find()方法用于查找第一次出現的子字符串的索引。 兩者之間的唯一區別是,如果子字符串在字符串中不可用,則find()將返回-1,而index()方法將創建一個異常。

Image for post
Syntax for index( ) method
index()方法的語法
Image for post
Image for post
Syntax for find( ) method
find()方法的語法
string = "I love Python"
print(string.index("o"))
print(string.find("o"))

Output

輸出量

3
3

Another Example

另一個例子

string = "I love Python"
print(string.index("q"))
print(string.find("q"))

Output

輸出量

ValueError: substring not found
-1

🔖 rindex() and rfind()

🔖rindex()和rfind()

These methods works as same as index() and find() methods. But It returns the index at which a sub string occurs for the last time in the string.

這些方法與index()和find()方法相同。 但是,它返回字符串中最后一次出現子字符串的索引。

Image for post
Syntax for rindex( ) method
rindex()方法的語法
Image for post
Image for post
Syntax for rfind( ) method
rfind()方法的語法
string = "I love Python"
print(string.rindex("o"))
print(string.rfind("o"))

Output

輸出量

11
11

🔖 replace() Method

🔖replace()方法

Image for post
Syntax for replace( ) method
replace()方法的語法
string = "I love Java"
print(string.replace("Java","Python"))

Output

輸出量

I love Python

對準方法 (Alignment Methods)

Alignment methods in python are used for positioning the text in particular place. The alignment methods used in python are given below.

python中的對齊方法用于將文本放置在特定位置。 python中使用的對齊方法如下。

🎲 center()

🎲center()

🎲 ljust()

just ljust()

🎲 rjust()

🎲rjust()

🎲 expandtabs()

🎲expandtabs()

🔖 center() Method

🔖center()方法

center() method is used to place the string in center to the width passed through it.

center()方法用于將字符串放置在通過它的寬度中心。

Image for post
Syntax for center( ) method
center()方法的語法
string = "python"
print(string.center(20))

Output

輸出量

python
####################20 Spaces allocated in console(This line will not be printed)

🔖 ljust() and rjust() Methods

just ljust()和rjust()方法

ljust() and rjust() methods are used to justify the string in a particular width to left and right ends respectively.

ljust()和rjust()方法用于將字符串以特定寬度對齊到左右兩端。

Image for post
Syntax for ljust( ) method
ljust()方法的語法
Image for post
Image for post
Syntax for rjust( ) method
rjust()方法的語法
string = "Python"
print(string.ljust(10))
print(string.rjust(10))

Output

輸出量

Python
Python

🔖 expandtabs() Method

🔖expandtabs()方法

/t is a format specifier used to print a tab of space in string. This method expandtabs() helps to customise the length of tabs in a string.

/ t是一種格式說明符,用于打印字符串中的空格標簽。 此方法expandtabs()有助于自定義字符串中選項卡的長度。

Image for post
Syntax for expandtabs( ) method
expandtabs()方法的語法
string = "Python\tProgramming"
print(string)
print(string.expandtabs(5))

Output

輸出量

Python  Programming
Python Programming

在Python中列出 (List in Python)

In many situation we should collect more than one similar data. For example, if you need to create list of names of five persons, you have to create five variable names. When the count increases, that is very hard to find variable name for each entry. The list data type solves the problem. In a list you can store more than one data in which each entry can be accessed by single variable name. In this section we will discuss about the list data type and the methods used in list.

在許多情況下,我們應該收集多個類似的數據。 例如,如果需要創建五個人的姓名列表,則必須創建五個變量名。 當計數增加時,很難為每個條目找到變量名。 列表數據類型解決了該問題。 在一個列表中,您可以存儲多個數據,其中每個條目都可以通過單個變量名進行訪問。 在本節中,我們將討論列表數據類型和列表中使用的方法。

清單結構 (Structure of List)

In a list all elements are separated by commas. A list can be created by inserting all elements inside square brackets. The elements inside a list can be of many types.

在列表中,所有元素都用逗號分隔。 可以通過將所有元素插入方括號內來創建列表。 列表中的元素可以有多種類型。

Image for post
Structure of List
清單結構

用Python創建列表 (Creating List in Python)

Let us create a list contains the following numbers as its elements.

讓我們創建一個包含以下數字作為其元素的列表。

148
201
958
20199
22036

The list in Python,

Python中的列表,

my_list = [ 148, 201, 958, 20199, 22036]
print(my_list)

Output

輸出量

[148, 201, 958, 20199, 22036]

在列表中建立索引 (Indexing in List)

All elements in python are indexed as same as the string data type. Each element can be accessed by both positive and negative integers.

python中所有元素的索引都與字符串數據類型相同。 每個元素都可以使用正整數和負整數進行訪問。

Image for post
Indexing in List
在列表中建立索引

訪問列表中的值 (Accessing Values in List)

The index can be used to get the value from a list. Both positive and negative indexing can be used.

索引可用于從列表中獲取值。 正索引和負索引都可以使用。

my_list = [ 148, 201, 958, 20199, 22036]
print(my_list[0])
print(my_list[-5])
print(my_list[2])
print(my_list[-3])
print(my_list[3])

Output

輸出量

148
148
958
958
20199

將值分配給列表元素 (Assigning Value to List Element)

The value can be assigned to a list element using assignment operator (=).

可以使用賦值運算符(=)將值賦給列表元素。

列表中的方法 (Methods in List)

We will discuss the following methods used to process a list object in python.

我們將討論以下用于處理python中的列表對象的方法。

🎲 append()

🎲append()

🎲 clear()

🎲clear()

🎲 copy()

🎲copy()

🎲 count()

🎲count()

🎲 extend()

🎲extend()

🎲 index()

🎲index()

🎲 insert()

🎲insert()

🎲 pop()

🎲pop()

🎲 remove()

🎲remove()

🎲 reverse()

🎲reverse()

🎲 sort()

🎲sort()

🔖 append( ) Method

🔖append()方法

append( ) Method is used to add item at the end of the list. We can add many items to the list continuously.

append()方法用于在列表的末尾添加項目。 我們可以將許多項目連續添加到列表中。

Image for post
Syntax for append( ) method
append()方法的語法
my_list = [1,2,3,4,5]
my_list.append(6)
print(my_list)

Output

輸出量

[1, 2, 3, 4, 5, 6]

🔖 clear( ) Method

🔖clear()方法

clear( ) method clears all the entry in a list. It will return an empty list after deleting all the elements.

clear()方法清除列表中的所有條目。 刪除所有元素后,它將返回一個空列表。

Image for post
Syntax for clear( ) method
clear()方法的語法
my_list = [1,2,3,4,5]
my_list.clear()
print(my_list)

Output

輸出量

[]

🔖 copy( ) Method

🔖copy()方法

copy( ) method is used to make a copy of existing list and store the list in another list variable.

copy()方法用于復制現有列表并將該列表存儲在另一個列表變量中。

Image for post
Syntax for copy( ) method
copy()方法的語法
my_list = [1,2,3,4,5]
new_list = my_list.copy()
print(new_list)

Output

輸出量

[1, 2, 3, 4, 5]

🔖 count( ) Method

🔖count()方法

count( ) method is used to count number of times a value get repeated in a list.

count()方法用于計算一個值在列表中重復的次數。

Image for post
Syntax for count( ) method
count()方法的語法
my_list = [1,5,1,2,3,1]
print(my_list.count(1))

Output

輸出量

3

🔖 extend( ) Method

🔖extend()方法

extend( ) is used to add a collection item like list to an another list variable. The passed list is appended at the end of the previous list.

extend()用于將諸如列表的收集項添加到另一個列表變量。 傳遞的列表將附加在上一個列表的末尾。

Image for post
Syntax for extend( ) method
extend()方法的語法
first_list = [1,2,3]
second_list = ["Alex","Carter"]
first_list.extend(second_list)
print(first_list)

Output

輸出量

[1, 2, 3, 'Alex', 'Carter']

🔖 index( ) Method

🔖index()方法

index( ) method is used to get the index of a particular element. If you pass a element that is not present then python will through an exception.

index()方法用于獲取特定元素的索引。 如果您傳遞的元素不存在,則python將通過異常。

Image for post
Syntax for index( ) method
index()方法的語法
my_list = [3,4,2,1,5,4]
print(my_list.index(4))

Output

輸出量

1

🔖 insert( ) Method

🔖insert()方法

insert( ) method is used to add an element at a particular index in a list.

insert()方法用于在列表中的特定索引處添加元素。

Image for post
Syntax for insert( ) method
insert()方法的語法
my_list = [1,2,4,5]
my_list.insert(2,3)
print(my_list)

Output

輸出量

[1, 2, 3, 4, 5]

🔖 pop( ) Method

🔖pop()方法

pop( ) method is used to delete an element in a particular index.

pop()方法用于刪除特定索引中的元素。

Image for post
Syntax for pop( ) method
pop()方法的語法
my_list = [1,2,3,4,5]
my_list.pop(2)
print(my_list)

Output

輸出量

[1, 2, 4, 5]

🔖 remove( ) Method

🔖remove()方法

remove( ) is just like the pop( ) method but in this method the element is passed instead of index.

remove()類似于pop()方法,但是在此方法中,元素是通過傳遞的,而不是索引。

Image for post
Syntax for remove( ) method
remove()方法的語法
my_list = [1,2,3,5,4]
my_list.remove(3)
print(my_list)

Output

輸出量

[1, 2, 4, 5]

🔖 reverse( ) Method

🔖reverse()方法

reverse( ) is used to reverse all the elements in a list. It doesn’t take any argument.

reverse()用于反轉列表中的所有元素。 不需要任何爭論。

Image for post
Syntax for reverse( ) method
reverse()方法的語法
my_list = [1,2,3,4,5]
my_list.reverse()
print(my_list)

Output

輸出量

[5, 4, 3, 2, 1]

🔖 sort( ) Method

🔖sort()方法

sort() Method is used to sort all the elements in a list in ascending order.

sort()方法用于按升序對列表中的所有元素進行排序。

Image for post
Syntax for sort( ) method
sort()方法的語法
my_list = [3,8,2,5,1]
my_list.sort()
print(my_list)

Output

輸出量

[1, 2, 3, 5, 8]

Python中的元組 (Tuple in Python)

Tuple is a collection elements like list but which is immutable object. In tuple you cannot change the value. So item assignment is not possible in tuple. This section of article will help you to know the basics about tuple and their methods.

元組是一個像list這樣的集合元素,但它是不可變的對象。 在元組中,您無法更改值。 因此,在元組中不可能進行項目分配。 本文的這一部分將幫助您了解有關元組及其方法的基礎知識。

元組的結構 (The Structure of a Tuple)

The tuple is created by separating each element by commas. The tuple elements are enclosed with parenthesis (). The items in the tuple can be in many kinds.

通過用逗號分隔每個元素來創建元組。 元組元素用括號()括起來。 元組中的項可以有多種。

Image for post
Structure of Tuple
元組的結構

用Python創建元組 (Creating Tuple in Python)

Let us create a tuple which contains the following data in a sequence.

讓我們創建一個元組,它按順序包含以下數據。

1
Felix
[97,95,99,100,94]
(1,2,3)

The tuple can have multiple data type in one collection.

元組可以在一個集合中具有多種數據類型。

my_tuple = [1,"Felix",[97,95,99,100,94],(1,2,3)]
print(my_tuple)

Output

輸出量

[1, 'Felix', [97, 95, 99, 100, 94], (1, 2, 3)]

元組索引 (Indexing in Tuple)

Each element in the tuple are indexed with integers. Any item in a tuple can be accessed by positive or negative index.

元組中的每個元素都用整數索引。 元組中的任何項都可以通過正或負索引訪問。

Image for post
Indexing of Tuple elements
元組元素的索引

訪問元組中的值 (Accessing Values in Tuple)

The tuple items can be accessed with help of the index of the item.

可以在項目索引的幫助下訪問元組項目。

my_tuple = [1,"Felix",[97,95,99,100,94],(1,2,3)]print(2)

Output

輸出量

[97,95,99,100,94]

元組中的方法 (Methods in Tuple)

There are two major methods available in tuple.

元組中有兩種主要方法。

🎲 count()

🎲count()

🎲 index()

🎲index()

🔖 count( ) Method

🔖count()方法

count() method is used to count how many times a particular item occurred in a tuple().

count()方法用于計算特定項目在tuple()中發生了多少次。

Image for post
Syntax for count( ) method
count()方法的語法
my_tuple = (1,2,3,1,5,6,1)
print(my_tuple.count(1))

Output

輸出量

3

🔖 index( ) Method

🔖index()方法

index( ) method is used to get the index of a item at which it occurs for first time.

index()方法用于獲取第一次出現的項目的索引。

Image for post
Syntax for index( ) method
index()方法的語法
my_tuple = (2,3,4,1,8,3)
print(my_tuple.index(3))

Output

輸出量

1

在Python中設置 (Set in Python)

Set is a unordered collection of unique elements in Python. It is also a basic data type in Python. It gives us the flexibility to work with the mathematical concepts like set theory.

Set是Python中唯一元素的無序集合。 它也是Python中的基本數據類型。 它使我們可以靈活地處理諸如集合論之類的數學概念。

集的結構 (Structure of Set)

Set is a collection of elements separated by commas. The set elements are enclosed with curly braces. All elements in the set are unique values.

Set是由逗號分隔的元素的集合。 set元素用花括號括起來。 集合中的所有元素都是唯一值。

Image for post
Set

創作集 (Creation of Set)

A set can be created using assignment operator. It is same as the creation of list in Python.

可以使用賦值運算符來創建集合。 它與在Python中創建列表相同。

my_set = {6,7,3,2,1,8,9,1}
print(my_set)

Output

輸出量

{1, 2, 3, 6, 7, 8, 9}

1 is printed only one time. This show that all values must be unique.

1只打印一次。 這表明所有值都必須是唯一的。

集合中的方法 (Methods in Set)

Here is the list of methods used mostly in set.

這是主要用于set中的方法列表。

🎲 add()

🎲add()

🎲 clear()

🎲clear()

🎲 difference()

🎲差異()

🎲 discard()

🎲丟棄()

🎲 intersection()

🎲交集()

🎲 pop()

🎲pop()

🎲 remove()

🎲remove()

🎲 symmetric_difference()

🎲symmetric_difference()

🔖 add() Method

🔖add()方法

add() method is used to add elements to set.

add()方法用于添加要設置的元素。

Image for post
Syntax for add( ) method
add()方法的語法
my_set = {1,2,3,4}
my_set.add(5)
print(my_set)

Output

輸出量

{1, 2, 3, 4, 5}

🔖 clear() Method

🔖clear()方法

This method clears all the elements present in a set.

此方法清除集中存在的所有元素。

Image for post
Syntax for clear( ) method
clear()方法的語法
my_set = {1,2,3,4}
my_set.clear()
print(my_set)

Output

輸出量

set()

🔖 difference() Method

🔖difference()方法

This method returns a new set contains the elements that present in a set but not in the other.

此方法返回一個新集合,其中包含存在于一個集合中但不存在于另一個集合中的元素。

Image for post
Syntax for difference( ) method
Difference()方法的語法
my_set = {1,2,3,4}
new_set= {1,6,7,3,9}
diff_set=my_set.difference(new_set)
print(diff_set)

Output

輸出量

{2, 4}

🔖 discard() Method

🔖throws()方法

discard() method is used to remove an item from the set.

reject()方法用于從集合中刪除一個項目。

Image for post
Syntax for discard( ) method
throws()方法的語法
my_set = {1,2,3,4}
my_set.discard(3)
print(my_set)

Output

輸出量

{1, 2, 4}

🔖 intersection() Method

🔖交集()方法

intersection() method is used to create a new set with common elements in all sets.

交集()方法用于創建一個在所有集合中具有共同元素的新集合。

Image for post
Syntax for intersection( ) method
相交()方法的語法
my_set = {1,2,3,4}
new_set = {1,5,2,7}
inter_set=my_set.intersection(new_set)
print(inter_set)

Output

輸出量

{1, 2}

🔖 pop() and remove() methods

🔖pop()和remove()方法

pop() and remove() methods are used to remove an element from the set. pop() removes an arbitrary element whereas remove() removes the specified element.

pop()和remove()方法用于從集合中刪除元素。 pop()刪除任意元素,而remove()刪除指定元素。

Image for post
Syntax for pop( ) method
pop()方法的語法
Image for post
Image for post
Syntax for remove( ) method
remove()方法的語法
my_set = {1,2,3,4}
my_set.pop()
print(my_set)

Output

輸出量

{2, 3, 4}

Program for remove method

刪除方法程序

my_set = {1,2,3,4}
my_set.remove(2)
print(my_set)

Output

輸出量

{1, 3, 4}

Python字典 (Dictionary in Python)

Welcome to my favorite data type in Python. Dictionary is a most interesting and useful data type in Python. To understand the concept of Dictionary, we may consider the contact list in our phone. Each contact is stored using a pair of name and contact number.

歡迎使用Python中我最喜歡的數據類型。 字典是Python中最有趣,最有用的數據類型。 要了解字典的概念,我們可以考慮手機中的聯系人列表。 每個聯系人都使用一對姓名和聯系號碼進行存儲。

The reason for using this method is the hardness of remembering lot of numbers in your brain. But, you can remember the names easily. When you need to make a call you can refer the contact list with help of the name in the list and it will be enough to access the phone number too. The Dictionary data type works in the same way.

使用這種方法的原因是很難記住大腦中的許多數字。 但是,您可以輕松記住這些名稱。 當您需要撥打電話時,可以借助列表中的姓名參考聯系人列表,這也足以訪問電話號碼。 詞典數據類型以相同的方式工作。

Image for post
Photo by Waldemar Brandt on Unsplash
Waldemar Brandt在Unsplash上拍攝的照片

Dictionary contains two set of value associated with each other. One is called key and another one is called value. The both combined together is called key-value pair or dictionary.

字典包含兩組彼此關聯的值。 一個叫做鍵,另一個叫做值。 兩者結合在一起稱為鍵值對或字典。

Each element in dictionary will be in the following form.

字典中的每個元素將采用以下形式。

Image for post
Key Value Pair
關鍵值對

字典的結構 (The Structure of a Dictionary)

A Dictionary will have one or more key value pairs separated by commas. The dictionary is created using the curly braces {} . The key and value in each element of dictionary is separated by colon : . Each key in a dictionary must be unique one.

詞典將具有一個或多個用逗號分隔的鍵值對。 使用花括號{}創建字典。 字典中每個元素的鍵和值用冒號分隔:。 詞典中的每個鍵都必須是唯一的。

Image for post
Dictionary Structure
字典結構

用Python創建字典 (Creating Dictionary in Python)

Let use create a dictionary contains a contact list of three persons. The contact list given here.

讓我們使用創建包含三個人的聯系人列表的字典。 此處給出的聯系人列表。

Alex - 783 456 2763
Clan - 462 355 3728
Olivia - 688 323 2237

The equivalent form of dictionary for this data set is created in Python below.

下面在Python中創建了與此數據集對應的字典形式。

contact = {"Alex":"7834562763", "Clan":"4623553728",  "Olivia":"6883232237"}

字典無序 (Dictionary is Unordered)

Dictionary is not like list, we can’t access the key value pair using any index. If two dictionaries have same contents in different order, then both are same dictionaries.

字典與列表不同,我們無法使用任何索引訪問鍵值對。 如果兩個字典的內容以不同的順序排列,則它們都是相同的字典。

Let us create another dictionary for the same contact list.

讓我們為相同的聯系人列表創建另一個詞典。

contact2 = {"Clan":"4623553728", Olivia:"6883232237", Alex:"7834562763"}

We can check whether two dictionaries are same or not using if statement.

我們可以使用if語句檢查兩個字典是否相同。

if(contact==contact2):
print("Same Dictionary")
else:
print("Not Same Dictionary")

Output

輸出量

Same Dictionary

So order of the key-value pair is not important in dictionary. Because all the values are accessed using the key of the dictionary.

So order of the key-value pair is not important in dictionary. Because all the values are accessed using the key of the dictionary.

Accessing a Value in Dictionary (Accessing a Value in Dictionary)

As I mentioned earlier, a value in a dictionary can be accessed with the help of key value.

As I mentioned earlier, a value in a dictionary can be accessed with the help of key value.

Syntax for accessing a value is,

Syntax for accessing a value is,

Image for post

Let us try to access a contact number of Alex in the contact list created in previous program.

Let us try to access a contact number of Alex in the contact list created in previous program.

contact = {"Alex":"7834562763", "Clan":"4623553728",  "Olivia":"6883232237"}
print(contact["Alex"])

Output

輸出量

7834562763

Assigning Value to Key (Assigning Value to Key)

The value can be assigned to a key using assignment operator (=). It works in two different cases. Let us take a look at the syntax for assigning value to the key in dictionary.

The value can be assigned to a key using assignment operator (=). It works in two different cases. Let us take a look at the syntax for assigning value to the key in dictionary.

Image for post

Case 1:

情況1:

When you try to assign a value for a key that already exists in dictionary, the value will get updated. For example, I will try to change the phone number of Alex in the contact list.

When you try to assign a value for a key that already exists in dictionary, the value will get updated. For example, I will try to change the phone number of Alex in the contact list.

contact = {"Alex":"7834562763", "Clan":"4623553728",  "Olivia":"6883232237"}contact["Alex"] = "1234567890"print(contact["Alex"])

Output

輸出量

1234567890

It shows that the previous value get updated.

It shows that the previous value get updated.

Case 2:

情況2:

If you try to assign a value to a key which is not present in the dictionary already, then a new key-value pair will be added to the dictionary. In the following code I am going to assign a phone number value to key name called “Ella”.

If you try to assign a value to a key which is not present in the dictionary already, then a new key-value pair will be added to the dictionary. In the following code I am going to assign a phone number value to key name called “Ella”.

contact = {"Alex":"7834562763", "Clan":"4623553728",  "Olivia":"6883232237"}contact["Ella"]="4531323768"
print(contact)

Output

輸出量

{'Alex': '7834562763', 'Olivia': '6883232237', 'Ella': '4531323768', 'Clan': '4623553728'}

New key value pair is added to the contact dictionary.

New key value pair is added to the contact dictionary.

Methods in Dictionary (Methods in Dictionary)

The methods used for processing the dictionary data type is given below.

The methods used for processing the dictionary data type is given below.

🎲 get()

🎲 get()

🎲 keys()

🎲 keys()

🎲 values()

🎲 values()

🎲 update()

🎲 update()

🎲 pop()

🎲 pop()

🎲 popitem()

🎲 popitem()

🎲 clear()

🎲 clear()

🎲 items()

🎲 items()

🎲 del()

🎲 del()

Let us discuss each methods in dictionary using some examples.

Let us discuss each methods in dictionary using some examples.

🔖 get( ) Method

🔖 get( ) Method

get( ) method is an another way to access the value associated with a key in dictionary. It take the key value as its argument.

get( ) method is an another way to access the value associated with a key in dictionary. It take the key value as its argument.

Image for post
Syntax for get( ) Method
Syntax for get( ) Method
contact = {"Alex":"7834562763", "Clan":"4623553728",  "Olivia":"6883232237"}print(contact.get("Alex"))

Output

輸出量

7834562763

If you try to access a key which is not present in the dictionary, then it will return None. So there will not be an exception for this.

If you try to access a key which is not present in the dictionary, then it will return None. So there will not be an exception for this.

contact = {"Alex":"7834562763", "Clan":"4623553728",  "Olivia":"6883232237"}print(contact.get("Carter"))

Output

輸出量

None

🔖 keys( ) Method and values( ) Method

🔖 keys( ) Method and values( ) Method

keys( ) method is used to list out all the keys present in a dictionary and values( ) method is used to list the values present in the dictionary.

keys( ) method is used to list out all the keys present in a dictionary and values( ) method is used to list the values present in the dictionary.

Image for post
Syntax for keys( ) method
Syntax for keys( ) method
Image for post
Image for post
Syntax for values( ) method
Syntax for values( ) method
contact = {"Alex":"7834562763", "Clan":"4623553728",  "Olivia":"6883232237"}print(contact.keys())
print(contact.values())

Output

輸出量

dict_keys(['Alex', 'Olivia', 'Clan'])
dict_values(['7834562763', '6883232237', '4623553728'])

🔖 update( ) Method

🔖 update( ) Method

update( ) method works as cases explained in value assignment section in dictionary. Here, a dictionary is given as an argument then each key value will be checked. If any key is already present in the dictionary then the value will get updated. If not new key value pair is added to the dictionary.

update( ) method works as cases explained in value assignment section in dictionary. Here, a dictionary is given as an argument then each key value will be checked. If any key is already present in the dictionary then the value will get updated. If not new key value pair is added to the dictionary.

Image for post
Syntax for update( ) method
Syntax for update( ) method
contact = {"Alex":"7834562763", "Clan":"4623553728",  "Olivia":"6883232237"}contact2 = {"Alex":"1234567890","Carter":"6583426552"}contact.update(contact2)print(contact)

Output

輸出量

{'Olivia': '6883232237', 'Clan': '4623553728', 'Carter': '6583426552', 'Alex': '1234567890'}

🔖 pop( ) Method

🔖 pop( ) Method

pop( ) method is used for deleting a key value pair by passing the key to it. If the passed key is not present in the dictionary then it will raise an keyerror exception.

pop( ) method is used for deleting a key value pair by passing the key to it. If the passed key is not present in the dictionary then it will raise an keyerror exception.

Image for post
Syntax for pop( ) method
Syntax for pop( ) method
contact = {"Alex":"7834562763", "Clan":"4623553728",  "Olivia":"6883232237"}contact.pop("Alex")print(contact)

Output

輸出量

{'Clan': '4623553728', 'Olivia': '6883232237'}

🔖 popitem( ) Method

🔖 popitem( ) Method

popitem() removes the key value pair that added lastly to the dictionary. This popitem() method does not take any argument.

popitem() removes the key value pair that added lastly to the dictionary. This popitem() method does not take any argument.

Image for post
Syntax for popitem( ) method
Syntax for popitem( ) method
contact = {"Alex":"7834562763", "Clan":"4623553728",  "Olivia":"6883232237"}contact.popitem()print(contact)

Output

輸出量

{'Olivia': '6883232237', 'Clan': '4623553728'}

🔖 clear( ) Method

🔖 clear( ) Method

clear() method removes all the key value pairs in a dictionary and returns an empty dictionary.

clear() method removes all the key value pairs in a dictionary and returns an empty dictionary.

Image for post
Syntax for clear( ) method
Syntax for clear( ) method
contact = {"Alex":"7834562763", "Clan":"4623553728",  "Olivia":"6883232237"}contact.clear()print(contact)

Output

輸出量

{}

🔖 items( ) Method

🔖 items( ) Method

items( ) method returns all the key value pairs as a tuple inside a list.

items( ) method returns all the key value pairs as a tuple inside a list.

Image for post
Syntax for items( ) method
Syntax for items( ) method
contact = {"Alex":"7834562763", "Clan":"4623553728",  "Olivia":"6883232237"}print(contact.items())

Output

輸出量

dict_items([('Clan', '4623553728'), ('Olivia', '6883232237'), ('Alex', '7834562763')])

🔖 del ( ) Method

🔖 del ( ) Method

del( ) method deletes the entire dictionary. It you try to access a deleted dictionary you will end up with some errors. clear( ) method is like deleting all contacts in your app whereas del( ) is uninstalling the contact app from your mobile phone.

del( ) method deletes the entire dictionary. It you try to access a deleted dictionary you will end up with some errors. clear( ) method is like deleting all contacts in your app whereas del( ) is uninstalling the contact app from your mobile phone.

Image for post
Syntax for del( ) Method
Syntax for del( ) Method
contact = {"Alex":"7834562763", "Clan":"4623553728",  "Olivia":"6883232237"}del(contact)print(contact)

Output

輸出量

NameError: name 'contact' is not defined

Python中的函數 (Functions in Python)

Breaking down your program into multiple parts gives us great flexibility over the code. The concept of functional programming enables a programmer to write better programs with higher simplicity. Even though python is object-oriented in nature the implementation of function concepts in python is very simple. This article will help you to understand the basics of function creation and some advanced functional programming concepts.

Breaking down your program into multiple parts gives us great flexibility over the code. The concept of functional programming enables a programmer to write better programs with higher simplicity. Even though python is object-oriented in nature the implementation of function concepts in python is very simple. This article will help you to understand the basics of function creation and some advanced functional programming concepts.

什么是功能? (What is a function?)

A function is a small piece of code that does something in the program with or without getting input parameters. Function usually prints the output or returns a value to the place from where the function is called. Still confusing? Let me try to simplify the concept of functions using a scenario. Imagine you are going to buy a birthday cake for your friend. Who will you approach to make a cake? A doctor or a baker? That will be a baker. Because a baker is someone who can prepare a cake for you. It doesn’t mean a doctor cannot bake a cake. Instead of one person doing all kinds of work, we can categorize people into multiple professions. Here each professional has its unique type of services by getting unique types of requirements from the consumer.

A function is a small piece of code that does something in the program with or without getting input parameters. Function usually prints the output or returns a value to the place from where the function is called. Still confusing? Let me try to simplify the concept of functions using a scenario. Imagine you are going to buy a birthday cake for your friend. Who will you approach to make a cake? A doctor or a baker? That will be a baker. Because a baker is someone who can prepare a cake for you. It doesn't mean a doctor cannot bake a cake. Instead of one person doing all kinds of work, we can categorize people into multiple professions. Here each professional has its unique type of services by getting unique types of requirements from the consumer.

The function works in the same manner. A function is a unique code snippet created by the developer to use wherever he needs the same kind of operations. Look at the following code sample without any function definition.

The function works in the same manner. A function is a unique code snippet created by the developer to use wherever he needs the same kind of operations. Look at the following code sample without any function definition.

name_1 = input("Your Name Here:")
year_of_birth_1 = int(input())name_2 = input("Your Name Here:")
year_of_birth_2 = int(input())name_3 = input("Your Name Here:")
year_of_birth_3 = int(input())print("Check",name_1,"'s YOB is Leap or Not:")
if(year_of_birth_1%4==0):
if(year_of_birth_1%100==0):
if(year_of_birth_1%400==0):
print("Leap Year")
else:
print("Not Leap Year")
else:
print("Leap Year")
else:
print("Not Leap Year")print("Check",name_2,"'s YOB is Leap or Not:")
if(year_of_birth_2%4==0):
if(year_of_birth_2%100==0):
if(year_of_birth_2%400==0):
print("Leap Year")
else:
print("Not Leap Year")
else:
print("Leap Year")
else:
print("Not Leap Year")print("Check",name_3,"'s YOB is Leap or Not:")
if(year_of_birth_3%4==0):
if(year_of_birth_3%100==0):
if(year_of_birth_3%400==0):
print("Leap Year")
else:
print("Not Leap Year")
else:
print("Leap Year")
else:
print("Not Leap Year")

The output of the above program is given below.

The output of the above program is given below.

Your Name Here:Felix
2000
Your Name Here:Antony
1998
Your Name Here:Alex
2004
Check Felix 's YOB is Leap or Not:
Leap Year
Check Antony 's YOB is Leap or Not:
Not Leap Year
Check Alex 's YOB is Leap or Not:
Leap Year

In the above program, the same operations are performed in three different places. Imagine this kind of program in which the same kind of operations is conducted many times. The final code will be a complex one. Now take a look at the following program in which a function called check_leap is created used wherever required.

In the above program, the same operations are performed in three different places. Imagine this kind of program in which the same kind of operations is conducted many times. The final code will be a complex one. Now take a look at the following program in which a function called check_leap is created used wherever required.

def check_leap(YOB):
if(year_of_birth_3%4==0):
if(year_of_birth_3%100==0):
if(year_of_birth_3%400==0):
print("Leap Year")
else:
print("Not Leap Year")
else:
print("Leap Year")
else:
print("Not Leap Year")name_1 = input("Your Name Here:")
year_of_birth_1 = int(input())name_2 = input("Your Name Here:")
year_of_birth_2 = int(input())name_3 = input("Your Name Here:")
year_of_birth_3 = int(input())print("Check",name_1,"'s YOB is Leap or Not:")
check_leap(year_of_birth_1)print("Check",name_2,"'s YOB is Leap or Not:")
check_leap(year_of_birth_2)print("Check",name_3,"'s YOB is Leap or Not:")
check_leap(year_of_birth_3)

It gives the same output as the previous program but it is really easy to understand. The statements required for checking leap year is written only one time in the program. That is why functional programming gives us easy debugging chances.

It gives the same output as the previous program but it is really easy to understand. The statements required for checking leap year is written only one time in the program. That is why functional programming gives us easy debugging chances.

Your Name Here:Felix
2000
Your Name Here:Antony
1998
Your Name Here:Alex
2004
Check Felix 's YOB is Leap or Not:
Leap Year
Check Antony 's YOB is Leap or Not:
Not Leap Year
Check Alex 's YOB is Leap or Not:
Leap Year

Classification of Functions (Classification of Functions)

I hope you have understood the basic need for functions in programming. In python, we can further classify the functions into two different types. They are user-defined functions and in built functions. The in built functions are functions that are readily available to be called in the program. In the definition before the first program, I have mentioned that I am going to write a program without function definition not without function. Yes! We have already used some functions in that program too. The functions inputand printare some examples of in built functions. These in built functions are created by the developers of the language with some inner engineering like the check_leapfunction. This check_leap is an example of user-defined functions that are created by the programmer as per the requirement.

I hope you have understood the basic need for functions in programming. In python, we can further classify the functions into two different types. They are user-defined functions and in built functions. The in built functions are functions that are readily available to be called in the program. In the definition before the first program, I have mentioned that I am going to write a program without function definition not without function. 是! We have already used some functions in that program too. The functions input and print are some examples of in built functions. These in built functions are created by the developers of the language with some inner engineering like the check_leap function. This check_leap is an example of user-defined functions that are created by the programmer as per the requirement.

Definition and Call of a function (Definition and Call of a function)

The instructions written under the check_leap function are called function definition. This defined instructions will be executed whenever a function is called from a particular place.

The instructions written under the check_leap function are called function definition. This defined instructions will be executed whenever a function is called from a particular place.

The check_leap function with a value passed through it is called a function call. The function can be called with or without any value. The value passed through the function is called parameter or arguments. Based on the arguments passed and return value the user-defined function can be classified into four groups.

The check_leap function with a value passed through it is called a function call. The function can be called with or without any value. The value passed through the function is called parameter or arguments. Based on the arguments passed and return value the user-defined function can be classified into four groups.

  • Function without Argument and without Return Value

    Function without Argument and without Return Value

  • Function without Argument and with Return Value

    Function without Argument and with Return Value

  • Function with Argument and without Return Value

    Function with Argument and without Return Value

  • Function with Argument and with Return Value

    Function with Argument and with Return Value

Function without argument and without return value (Function without argument and without return value)

The value returned by the function is called the return value. We can return a value from a user-defined function by using a keyword called return. Some functions don’t require any arguments to be passed and return nothing. These kinds of functions fall under this category. The following program is an example of a function without argument and the return value.

The value returned by the function is called the return value. We can return a value from a user-defined function by using a keyword called return . Some functions don't require any arguments to be passed and return nothing. These kinds of functions fall under this category. The following program is an example of a function without argument and the return value.

def eligible():
print("You are Eligible to take the Exam")def not_eligible():
print("You are not Eligible to take the Exam")age = int(input("Enter Your Age:"))if(age<20):
not_eligible()
elif(age>=20 and age<35):
eligible()
else:
not_eligible()

Output

輸出量

Enter Your Age:24
You are Eligible to take the Exam

In the above program, there are two user-defined functions are created. In the function definition, you can see that there is no argument is defined inside the function. So we don’t need any parameters to call these functions.

In the above program, there are two user-defined functions are created. In the function definition, you can see that there is no argument is defined inside the function. So we don't need any parameters to call these functions.

Function without argument and with return value (Function without argument and with return value)

In some cases, a function will return a value without taking any argument or parameter. These types of functions are the functions without argument and with a return value. Look at the following example program for understanding the concept better.

In some cases, a function will return a value without taking any argument or parameter. These types of functions are the functions without argument and with a return value. Look at the following example program for understanding the concept better.

def low_dosage():
return 75
def med_dosage():
return 100
def high_dosage():
return 150age = int(input("Patient's Age:"))
temp = float(input("Body Temperature:"))if(age<10 and temp>98 and temp<99):
print("The medicine with ",low_dosage(),"mgs is enough.")
elif(age<10 and temp>99):
print("The medicine with",med_dosage(),"mgs is enough.")
elif(age>10 and temp>98 and temp<99):
print("The medicine with",med_dosage(),"mgs is enough.")
elif(age>10 and temp>99):
print("The medicine with",high_dosage(),"mgs is enough.")

Output

輸出量

Patient's Age:35
Body Temperature:100
The medicine with 150 mgs is enough.

The called functions are highlighted in the program. Whenever a function returns a value using the keyword return the value can be stored in a variable or formatted using the print function.

The called functions are highlighted in the program. Whenever a function returns a value using the keyword return the value can be stored in a variable or formatted using the print function.

Function with arguments and without return value (Function with arguments and without return value)

Some functions will take some parameters to it and does not return any value back. The following code will help you to understand the concept.

Some functions will take some parameters to it and does not return any value back. The following code will help you to understand the concept.

def low(amount,year):
rate = 6.5
interest = amount * year * rate/100
if(year<5):
print("Your interest will be",interest * 1.2)
else:
print("Your interest will be",interest * 1.4)
def high(amount,year):
rate = 8.5
interest = amount * year * rate/100
if(year<5):
print("Your interest will be",interest * 1.2)
else:
print("Your interest will be",interest * 1.4)amount = int(input("Investment Amount:"))
year = int(input("No of Years:"))if(amount<100000):
low(amount,year)
else:
high(amount,year)

Output

輸出量

Investment Amount:120000
No of Years:6
Your interest will be 85680.0

The two functions low and high both functions getting two values as their arguments and it returns nothing. Simply we can say that the output is formatted in the function itself. But that is not true always. We can create a function for doing nothing.

The two functions low and high both functions getting two values as their arguments and it returns nothing. Simply we can say that the output is formatted in the function itself. But that is not true always. We can create a function for doing nothing.

Function with arguments and with return value (Function with arguments and with return value)

This type of user-defined function is the majorly used in many situations. It takes some arguments into it and returns some values to the function call. Let us try to rewrite the previous program for this type of user-defined function.

This type of user-defined function is the majorly used in many situations. It takes some arguments into it and returns some values to the function call. Let us try to rewrite the previous program for this type of user-defined function.

def low(amount,year):
rate = 6.5
interest = amount * year * rate/100
if(year<5):
return interest*1.2
else:
return interest*1.4
def high(amount,year):
rate = 8.5
interest = amount * year * rate/100
if(year<5):
return interest*1.2
else:
return interest*1.4amount = int(input("Investment Amount:"))
year = int(input("No of Years:"))if(amount<100000):
print("Your Interest will be",low(amount,year))
else:
print("Your Interest will be",high(amount,year))

Output

輸出量

Investment Amount:98000
No of Years:4
Your Interest will be 30576.0

Instead of printing the value inside the function, the return keyword returns the interest value to the place from which the value is called. The function call is highlighted with bold letters.

Instead of printing the value inside the function, the return keyword returns the interest value to the place from which the value is called. The function call is highlighted with bold letters.

Here I have written a program which contains all the four types of functions in it. Try to understand each type and usage of that in a particular place.

Here I have written a program which contains all the four types of functions in it. Try to understand each type and usage of that in a particular place.

def question():
print("Your Name:")
def type():
print("Type of Account")
def savings():
return 1.8
def fixed():
return 2.3
def interest_calc(amount,year,rate):
interest_amt=amount * year * rate/100
return interest_amt
def total_calc(amount,interest):
return amount+interest
def info(name,total,year):
print(name,"'s Total amount after",year,"is",total)question()
name = input()
type()
t=int(input("Savings(1)/Fixed(2)"))
if(t==1):
rate = savings()
elif(t==2):
rate = fixed()
amount = int(input("Amount:"))
year = int(input("Year:"))
interest = interest_calc(amount,year,rate)
total = total_calc(amount,interest)
info(name,total,year)

Output

輸出量

Your Name:
Felix
Type of Account
Savings(1)/Fixed(2)1
Amount:18000
Year:5
Felix 's Total amount after 5 is 19620.0

Scope of Variable (Scope of Variable)

Every variable defined in the program has its own scope. That is there will be a range in which we can access the value with a particular variable name. Usually, a variable can accessible within the function only. Let me demonstrate the scope of a variable using the following program.

Every variable defined in the program has its own scope. That is there will be a range in which we can access the value with a particular variable name. Usually, a variable can accessible within the function only. Let me demonstrate the scope of a variable using the following program.

def info():
value = 5
print("The value is",value)
def test():
print("The value is",value)info()
test()

Output

輸出量

The value is 5
Traceback (most recent call last):
File "main.py", line 7, in <module>
test()
File "main.py", line 5, in test
print("The value is",value)
NameError: name 'value' is not defined

You get some exceptions over the program. This is because the scope of the variable value is constrained between the range of function info(). So that it cannot be accessible by other functions.

You get some exceptions over the program. This is because the scope of the variable value is constrained between the range of function info() . So that it cannot be accessible by other functions.

Global Variables in Python (Global Variables in Python)

Global variables are variables that can be accessed anywhere in the program. Usually, the variables defined in the main function are global variables. We don’t need any extra syntax to make global variables. But if we need to create a global variable inside any function we can use the keyword called global.

Global variables are variables that can be accessed anywhere in the program. Usually, the variables defined in the main function are global variables. We don't need any extra syntax to make global variables. But if we need to create a global variable inside any function we can use the keyword called global .

Syntax: global variable_name

Syntax: global variable_name

Here I modified the previous program with the keyword global .

Here I modified the previous program with the keyword global .

def info():
global value
value = 5
print("The value is",value)
def test():
print("The value is",value)info()
test()

*args and **kwargs in Python (*args and **kwargs in Python)

In previous programs, we exactly know how many parameters are going into a function. But what if we don’t know the number of arguments in advance. Here is how the list arguments and keyword arguments come to play. These are some methods to pass a collection of values with only one name. Look at the following example for *args method.

In previous programs, we exactly know how many parameters are going into a function. But what if we don't know the number of arguments in advance. Here is how the list arguments and keyword arguments come to play. These are some methods to pass a collection of values with only one name. Look at the following example for *args method.

def function(*args):
for x in args:
print(x)function("Felix","Antony")

Output

輸出量

Felix
Antony

The function takes more than one value at a time in the format of a tuple. The tuple can be accessed by the index with args as tuple name. Here is another example that contains more than one argument.

The function takes more than one value at a time in the format of a tuple. The tuple can be accessed by the index with args as tuple name. Here is another example that contains more than one argument.

def function(name ,*args):
print(name)
for x in args:
print(x)function("Felix Antony", "Medium", "Writer")

Output

輸出量

Felix Antony
Medium
Writer

Here the first preference is given to the single arguments. Usually, we have to keep *args and **kwargs in the last place in the arguments list.

Here the first preference is given to the single arguments. Usually, we have to keep *args and **kwargs in the last place in the arguments list.

The **kwargs also working same as the previous one. But instead of a tuple, we are using dictionary data type here. The dictionary value can be accessed by its key values. That is why it is called as keyword arguments.

The **kwargs also working same as the previous one. But instead of a tuple, we are using dictionary data type here. The dictionary value can be accessed by its key values. That is why it is called as keyword arguments.

def myfunction(**kwargs):
for x,y in kwargs.items():
print(y)myfunction(First_name = "Felix", Last_name = "Antony")

Output

輸出量

Antony
Felix

*args and **kwargs are the common convention. We can choose our own name for implementing these arguments. But keeping the common name will be a better option.

*args and **kwargs are the common convention. We can choose our own name for implementing these arguments. But keeping the common name will be a better option.

Lambda表達式 (Lambda Expressions)

Lambda is a pure anonymous function in python which allows us to write a function in a single line of code. It reduces the effort of programmer in writing multiple lines of code to create user-defined functions. Before going to write the actual code we must understand the concept behind the lambda function. Look at the explanation about lambda in Wikipedia.

Lambda is a pure anonymous function in python which allows us to write a function in a single line of code. It reduces the effort of programmer in writing multiple lines of code to create user-defined functions. Before going to write the actual code we must understand the concept behind the lambda function. Look at the explanation about lambda in Wikipedia .

Lambda calculus (also written as λ-calculus) is a formal system in mathematical logic for expressing computation based on function abstraction and application using variable binding and substitution. It is a universal model of computation that can be used to simulate any Turing machine.

Lambda calculus (also written as λ- calculus ) is a formal system in mathematical logic for expressing computation based on function abstraction and application using variable binding and substitution. It is a universal model of computation that can be used to simulate any Turing machine.

Image for post

Lambda Function Symbol

Lambda Function Symbol

Lambda calculus was introduced by the mathematician Alonzo Church to investigate the foundational mathematical calculus. This calculus helps the mathematicians to understand the mechanism between basic arithmetic and logical operations. The symbolic representation of the lambda is λ Greek alphabet.

Lambda calculus was introduced by the mathematician Alonzo Church to investigate the foundational mathematical calculus. This calculus helps the mathematicians to understand the mechanism between basic arithmetic and logical operations. The symbolic representation of the lambda is λ Greek alphabet.

In python, the function is denoted with the keyword lambda . Look at the syntax of the lambda function.

In python, the function is denoted with the keyword lambda . Look at the syntax of the lambda function.

Syntax: lambda arguments : expression

Syntax: lambda arguments : expression

Let us create a function to calculate the volume of given cube.

Let us create a function to calculate the volume of given cube.

def volume(side):
return side*side*sideside = int(input("Enter Side of Cube"))
Volume_of_cube = volume(side)
print( Volume_of_cube )

Look at the following code which contains lambda expression to create the function.

Look at the following code which contains lambda expression to create the function.

side = int(input("Enter Side of Cube"))
Volume_of_cube = lambda side : side * side * sideprint( Volume_of_cube (side) )

Both codes give the same output for similar kind of inputs as follows.

Both codes give the same output for similar kind of inputs as follows.

Enter Side of Cube6
216

Why Anonymous? (Why Anonymous?)

In the previous program, we have called the lambda function with the help of the name Volume_of_cube . But actually this name is not a function name. The previous program is just one of the ways to use a lambda function. In python the function created using the lambda does not have any function name. In the program, the variable name itself acted as function name. To understand clearly you can replace the entire lambda expression instead of the variable name.

In the previous program, we have called the lambda function with the help of the name Volume_of_cube . But actually this name is not a function name. The previous program is just one of the ways to use a lambda function. In python the function created using the lambda does not have any function name. In the program, the variable name itself acted as function name. To understand clearly you can replace the entire lambda expression instead of the variable name.

side = int(input("Enter Side of Cube")) 
print( (lambda side : side * side * side) (side) )

I hope you can understand the concept. That is why the lambda expression is called as an anonymous function. There are certain conditions in creating a lambda function in Python. More than one argument can be passed in the lambda expression but only one expression can be created in it. Some more examples are given below using lambda functions.

I hope you can understand the concept. That is why the lambda expression is called as an anonymous function. There are certain conditions in creating a lambda function in Python. More than one argument can be passed in the lambda expression but only one expression can be created in it. Some more examples are given below using lambda functions.

add = lambda a,b,c : a + b + c
print( add(5,4,6) )multiply = lambda x,y : x * y
print( multiply(3,7) )power = lambda m,n : m ** n
print( power(6,2) )

Output

輸出量

15
21
36

Map function in Python (Map function in Python)

Map is a function used to trace the sequencing objects. The map function reduces great effort of applying some functions for each elements of collections such as list and dictionaries. Let us try to get a list of interest amount of each employee for an particular sum of money using normal way.

Map is a function used to trace the sequencing objects. The map function reduces great effort of applying some functions for each elements of collections such as list and dictionaries. Let us try to get a list of interest amount of each employee for an particular sum of money using normal way.

Image for post

Photo by Honey Yanibel Minaya Cruz on Unsplash

Photo by Honey Yanibel Minaya Cruz on Unsplash

Syntax: map[]

Syntax: map[]

def interest(amount, rate, year):
return amount * rate * year / 100amount = [10000, 12000, 15000]
rate = 5
year = 3for x in amount:
y = interest(x, rate, year)
print(y)

Output

輸出量

1500.0
1800.0
2250.0

The same can be done easily with the help of map function in Python. The following code is created using the map function.

The same can be done easily with the help of map function in Python. The following code is created using the map function.

def interest(amount):
rate = 5
year = 3
return amount * rate * year / 100amount = [10000, 12000, 15000]interest_list = map(interest,amount)
print( interest_list )

Output

輸出量

<map object at 0x7fd6e45d90b8>

Get confused with the output? The map function always return a map object. We have type cast the object using list keyword.

Get confused with the output? The map function always return a map object. We have type cast the object using list keyword.

def interest(amount):
rate = 5
year = 3
return amount * rate * year / 100amount = [10000, 12000, 15000]interest_list = list( map(interest,amount) )
print( interest_list )

Output

輸出量

[1500.0, 1800.0, 2250.0]

Map function is not only take the user defined function. We can use the built in function also.

Map function is not only take the user defined function. We can use the built in function also.

name = ["alex", "felix", "antony"]
cap = list( map(str.capitalize, name))
print(cap)

Output

輸出量

['Alex', 'Felix', 'Antony']

Filter Function in Python (Filter Function in Python)

In some times you have to filter some elements in a list based on some conditions. Let us consider a list of ages of ten persons. We have to filter the persons based on their age. If a person’s age is greater than or equal to 24 then they can be eligible to be in the list. In a normal way, we can use something like the following.

In some times you have to filter some elements in a list based on some conditions. Let us consider a list of ages of ten persons. We have to filter the persons based on their age. If a person's age is greater than or equal to 24 then they can be eligible to be in the list. In a normal way, we can use something like the following.

list_of_age = [10, 24, 27, 33, 30, 18, 17, 21, 26, 25]filtered_list = []for x in list_of_age:
if(x>=24):
filtered_list.append(x)print( filtered_list )

Using filter function this can be very easy. The filter function returns an object that contains the elements that are true for certain conditions.

Using filter function this can be very easy. The filter function returns an object that contains the elements that are true for certain conditions.

Syntax: filter(function, iterables)

Syntax: filter(function, iterables)

def eligibility(age):
if(age>=24):
return True
list_of_age = [10, 24, 27, 33, 30, 18, 17, 21, 26, 25]age = filter(eligibility, list_of_age)print(list(age))

The output for the previous programs are given below.

The output for the previous programs are given below.

[24, 27, 33, 30, 26, 25]

Reduce function in Python (Reduce function in Python)

Reduce is a built in function in a module called functools. It reduces the size of iterable objects by applying function in each step. The syntax of reduce() function is given below.

Reduce is a built in function in a module called functools. It reduces the size of iterable objects by applying function in each step. The syntax of reduce() function is given below.

Syntax: reduce(function, iterables, start)

Syntax: reduce(function, iterables, start)

Let us consider a list of five numbers [1, 2, 3, 4, 5] from which you need to find the sum of the numbers. The reduce function first takes the numbers (1,2) then pass them through the defined function. Then the return value from the first one and the third value will be passed through the function. Let the name of the function be add() then the steps involved in finding the sum will be the following.

Let us consider a list of five numbers [1, 2, 3, 4, 5] from which you need to find the sum of the numbers. The reduce function first takes the numbers (1,2) then pass them through the defined function. Then the return value from the first one and the third value will be passed through the function. Let the name of the function be add() then the steps involved in finding the sum will be the following.

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

The actual code for the previous explanation is given below.

The actual code for the previous explanation is given below.

from functools import reduce
def add(a,b):
return a+b
my_list = [1, 2, 3, 4, 5]
sum = reduce(add, my_list)
print(sum)

Output

輸出量

15

Combining Lambda with Map, Filter and Reduce (Combining Lambda with Map, Filter and Reduce)

The higher order functions can replace the function object with the lambda expressions. The usage of lambda expression helps us to implement the discussed concept easily with a couple of lines of code.

The higher order functions can replace the function object with the lambda expressions. The usage of lambda expression helps us to implement the discussed concept easily with a couple of lines of code.

Lambda with Map (Lambda with Map)

The following code will help you to know how to implement the map function with lambda. Let us try to create a list of power of a list.

The following code will help you to know how to implement the map function with lambda. Let us try to create a list of power of a list.

list_of_numbers = [10, 6, 5, 17, 15]
order = 2
power = map(lambda x : x ** order, list_of_numbers)
print(list(power))

Output

輸出量

[100, 36, 25, 289, 225]

Lambda with Filter (Lambda with Filter)

The conditional statements can be used with lambda expressions. Using the return value from the lambda function we can use filter the list.

The conditional statements can be used with lambda expressions. Using the return value from the lambda function we can use filter the list.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even = list(filter(lambda x: x%2==0, numbers))
print(even)

Output

輸出量

[2, 4, 6, 8, 10]

面向對象編程 (Object Oriented Programming)

This world is made up of various objects. It may be a living thing or a non living thing, simply it can be called an Object. Objects can be categorized with the help of its behavior. Try to find the object from the instruction given here.

This world is made up of various objects. It may be a living thing or a non living thing, simply it can be called an Object. Objects can be categorized with the help of its behavior. Try to find the object from the instruction given here.

  • The object has four wheels.

    The object has four wheels.
  • It contains an Engine.

    It contains an Engine.
  • It takes fuel to run.

    It takes fuel to run.

Most of you could able to understand what I am describing about. It is a car. Here we have millions of cars in our world. Each of the cars are different objects. But all the cars can be classified into a group with the help of its behavior. In object oriented programming, each car is an object whereas the common blueprint that contains the behaviors of the object is called class.

Most of you could able to understand what I am describing about. It is a car. Here we have millions of cars in our world. Each of the cars are different objects. But all the cars can be classified into a group with the help of its behavior. In object oriented programming, each car is an object whereas the common blueprint that contains the behaviors of the object is called class.

Once a class with some properties is created, then any number of objects can be created under the class. The creation of an object under a class is called instantiation. To construct a class we should understand the behavior of objects clearly.

Once a class with some properties is created, then any number of objects can be created under the class. The creation of an object under a class is called instantiation. To construct a class we should understand the behavior of objects clearly.

The object-oriented model makes it easy to build up programs by accretion. What this often means, in practice, is that it provides a structured way to write spaghetti code.

The object-oriented model makes it easy to build up programs by accretion. What this often means, in practice, is that it provides a structured way to write spaghetti code.

Image for post
insung yoon on insung yoon on UnsplashUnsplash

Creating a Class in Python (Creating a Class in Python)

A class in python is created using the keyword called class. The class name must follow the rules for creating identifiers in Python. Let us try to create a class with a name called car.

A class in python is created using the keyword called class . The class name must follow the rules for creating identifiers in Python. Let us try to create a class with a name called car .

Syntax: class name:

Syntax: class name:

To create an empty class in Python we can use the pass keyword. The following is the example of an empty class in python.

To create an empty class in Python we can use the pass keyword. The following is the example of an empty class in python.

class Car:
pass

Now the class Car is created. But there is no description of the car is given to the class. It simply creates the Car class. Still we can create an object under the Car class.

Now the class Car is created. But there is no description of the car is given to the class. It simply creates the Car class. Still we can create an object under the Car class.

How to Create an Object Under a Class (How to Create an Object Under a Class)

Creating an object under a class is very simple. Let us try to create three cars under the Car class created in the previous code. Before that, we have to collect some information about the car. The following table describes the properties of each car.

Creating an object under a class is very simple. Let us try to create three cars under the Car class created in the previous code. Before that, we have to collect some information about the car. The following table describes the properties of each car.

Object  Company  Speed   Color   Year
Car1 XYZ 125 RED 2019
Car2 ABC 150 BLUE 2020
Car3 LMN 200 YELLOW 2020

Now we have to classify each information into different categories. The Car1, Car2 and Car3 are objects under the Car class. Company, Speed, Color, and Year are properties of the Cars. These properties will help us to create a blueprint for the Car objects.

Now we have to classify each information into different categories. The Car1, Car2 and Car3 are objects under the Car class. Company, Speed, Color, and Year are properties of the Cars. These properties will help us to create a blueprint for the Car objects.

Syntax: object_name = Class_name()

Syntax: object_name = Class_name()

class Car:
pass
Car1 = Car()
Car2 = Car()
Car3 = Car()

Now all three cars are created as the objects under the class named Car. Now we can able to assign each property to the car objects.

Now all three cars are created as the objects under the class named Car. Now we can able to assign each property to the car objects.

class Car:
pass
Car1 = Car()
Car2 = Car()
Car3 = Car()Car1.company = "ABC"
Car2.company = "XYZ"
Car3.company = "LMN"

The company name for each car object is assigned to the object using dot operator. We can assign all other values also.

The company name for each car object is assigned to the object using dot operator. We can assign all other values also.

class Car:
pass
Car1 = Car()
Car2 = Car()
Car3 = Car()Car1.company = "ABC"
Car2.company = "XYZ"
Car3.company = "LMN"Car1.speed = 125
Car2.speed = 150
Car3.speed = 200Car1.color = "RED"
Car2.color = "BLUE"
Car3.color = "YELLOW"Car1.year = 2019
Car2.year = 2020
Car3.year = 2020

But this code doesn’t make any difference from the procedural programming. This is also like a normal value assignment for different variable names. Let us try to solve this using a method called constructor method in the following section.

But this code doesn't make any difference from the procedural programming. This is also like a normal value assignment for different variable names. Let us try to solve this using a method called constructor method in the following section.

Image for post
Photo by Nick Fewings on Unsplash
Nick Fewings在Unsplash上拍攝的照片

Concept of Constructor Method (Concept of Constructor Method)

The method __init__() is known as the constructor method in python. It helps us to create the blue print for the object. While using this constructor method the object instantiation will induce this method. That means, whenever you create a new object the __ini__ method will be called and whatever written in the method will be executed. Look at the following example in which we are trying to create an class with constructor instead of empty class.

The method __init__() is known as the constructor method in python. It helps us to create the blue print for the object. While using this constructor method the object instantiation will induce this method. That means, whenever you create a new object the __ini__ method will be called and whatever written in the method will be executed. Look at the following example in which we are trying to create an class with constructor instead of empty class.

class Car:
def __init__(self):
print("You created a new object")
Car1 = Car()
Car2 = Car()
Car3 = Car()

Output

輸出量

You created a new object
You created a new object
You created a new object

We can use this ability of the constructor method to assign the value for each variable. In the above example, the constructor method defined with an argument called self . But while creating an object there is no argument is passed. Simply the argument passed during the instantiation will be n-1 where n is no of arguments described in the constructor method. Self takes the objects as the argument itself.

We can use this ability of the constructor method to assign the value for each variable. In the above example, the constructor method defined with an argument called self . But while creating an object there is no argument is passed. Simply the argument passed during the instantiation will be n-1 where n is no of arguments described in the constructor method. Self takes the objects as the argument itself.

class Car:
def __init__(self,company,speed,color,year):
self.company = company
self.speed = speed
self.color = color
self.year = yearCar1 = Car("ABC",125,"RED",2019)
Car2 = Car("XYZ",150,"BLUE",2020)
Car3 = Car("LMN",200,"YELLOW",2020)

This code is the same as the previous value assignment code. The actual parameters passed through the constructor method are Car1,"ABC",125, "RED",2019. Let me break down what happened while creating the object called Car1 .

This code is the same as the previous value assignment code. The actual parameters passed through the constructor method are Car1,"ABC",125, "RED",2019. Let me break down what happened while creating the object called Car1 .

When the object Car1 is created the __init__ () method inside the Car class will be called. It replaces the all self keyword into the object name. For example the self.company will be Car1.company , then the value is assigned to Car1.company . This is how the constructor method plays a vital role in object oriented programming with Python.

When the object Car1 is created the __init__ () method inside the Car class will be called. It replaces the all self keyword into the object name. For example the self.company will be Car1.company , then the value is assigned to Car1.company . This is how the constructor method plays a vital role in object oriented programming with Python.

Image for post
Dane Deaner on Dane Deaner on UnsplashUnsplash

Creating Methods for Objects (Creating Methods for Objects)

A class can have not only the constructor method but also we can create our own method. In the previous code, we created a class with Cars. Let us try to create a method to get the values from the objects.

A class can have not only the constructor method but also we can create our own method. In the previous code, we created a class with Cars. Let us try to create a method to get the values from the objects.

class Car:
def __init__(self,company,speed,color,year):
self.company = company
self.speed = speed
self.color = color
self.year = year
def get_speed(self):
print(self.speed)
def get_company(self):
print(self.company)
def get_color(self):
print(self.color)
def get_year(self):
print(self.year)Car1 = Car("ABC",125,"RED",2019)
Car2 = Car("XYZ",150,"BLUE",2020)
Car3 = Car("LMN",200,"YELLOW",2020)Car1.get_company()
Car2.get_speed()
Car3.get_color()

Output

輸出量

XYZ
150
YELLOW

Make Your Attribute Private using Encapsulation (Make Your Attribute Private using Encapsulation)

Let us try to change the value of the speed of Car2 using normal value assignment. In the above code, the following statement will change the speed easily.

Let us try to change the value of the speed of Car2 using normal value assignment. In the above code, the following statement will change the speed easily.

Car2.speed = 250

This clearly shows that there is no proper security over the information. Unfortunately, python doesn’t have any classification like public or private data. We can protect information by using a double underscore before the variable name.

This clearly shows that there is no proper security over the information. Unfortunately, python doesn't have any classification like public or private data. We can protect information by using a double underscore before the variable name.

class Car:
def __init__(self,company,speed,color,year):
self.__company = company
self.__speed = speed
self.__color = color
self.__year = year
def get_speed(self):
print(self.__speed)
def get_company(self):
print(self.__company)
def get_color(self):
print(self.__color)
def get_year(self):
print(self.__year)Car1 = Car("ABC",125,"RED",2019)
Car2 = Car("XYZ",150,"BLUE",2020)
Car3 = Car("LMN",200,"YELLOW",2020)Car2.__speed = 250
Car2.get_speed()

Output

輸出量

200

In the above code, the double __ protected the data so that the value of speed of the second car is still 200. This is called data protection or encapsulation in object oriented programming.

In the above code, the double __ protected the data so that the value of speed of the second car is still 200. This is called data protection or encapsulation in object oriented programming.

遺產 (Inheritance)

Inheritance is the concept of creating relationship between a parent class and a child class which enables the code reusability. In inheritance, we just inherit the properties from parent class to child class. In inheritance, an object from a class can access a method defined in a different class.

Inheritance is the concept of creating relationship between a parent class and a child class which enables the code reusability. In inheritance, we just inherit the properties from parent class to child class. In inheritance, an object from a class can access a method defined in a different class.

Syntax: class name(parent):

Syntax: class name(parent):

Look at the following code in which we just added a class called Trike as a child for the Car class. Let us try to get the speed of trike1 from the method defined in the car class.

Look at the following code in which we just added a class called Trike as a child for the Car class. Let us try to get the speed of trike1 from the method defined in the car class.

class Car:
def __init__(self,company,speed,color,year):
self.company = company
self.speed = speed
self.color = color
self.year = year
def get_speed(self):
print(self.speed)
def get_company(self):
print(self.company)
def get_color(self):
print(self.color)
def get_year(self):
print(self.year)class Trike(Car):
def __init__(self,company,speed,color,year):
self.company = company
self.speed = speed
self.color = color
self.year = yearCar1 = Car("ABC",125,"RED",2019)
Car2 = Car("XYZ",150,"BLUE",2020)
Car3 = Car("LMN",200,"YELLOW",2020)Trike1 = Trike("GHJ",90,"Grey",2020)
Trike2 = Trike("DFG",80,"Violet",2019)Trike1.get_speed()

Output

輸出量

90

In the above code Trike1 is an object created under the class name Trike. As the Trike class is created as a child of Car class, it can access the method get_speed which is defined in Car class.

In the above code Trike1 is an object created under the class name Trike. As the Trike class is created as a child of Car class, it can access the method get_speed which is defined in Car class.

Types of Inheritance (Types of Inheritance)

Let us discuss four important types of Inheritance using code examples in the following sections. The types covered in this article are listed below.

Let us discuss four important types of Inheritance using code examples in the following sections. The types covered in this article are listed below.

  • Single Inheritance

    單繼承
  • Multiple Inheritance

    多重繼承
  • Multilevel Inheritance

    Multilevel Inheritance
  • Hierarchical Inheritance

    層次繼承

單繼承 (Single Inheritance)

When a child class in a program has only one parent class then the type of inheritance is called single inheritance. The following code is an example of single inheritance.

When a child class in a program has only one parent class then the type of inheritance is called single inheritance. The following code is an example of single inheritance.

class Car:
def __init__(self,company,speed,color,year):
self.company = company
self.speed = speed
self.color = color
self.year = year
def get_speed(self):
print(self.speed)
def get_company(self):
print(self.company)
def get_color(self):
print(self.color)
def get_year(self):
print(self.year)class Trike(Car):
def __init__(self,company,speed,color,year):
self.company = company
self.speed = speed
self.color = color
self.year = yearCar1 = Car("ABC",125,"RED",2019)
Car2 = Car("XYZ",150,"BLUE",2020)
Car3 = Car("LMN",200,"YELLOW",2020)Trike1 = Trike("GHJ",90,"Grey",2020)
Trike2 = Trike("DFG",80,"Violet",2019)Trike1.get_speed()
Trike1.get_company()
Trike2.get_color()
Trike2.get_year()

Output

輸出量

90
GHJ
Violet
2019

多重繼承 (Multiple Inheritance)

In multiple inheritance, a child class will have more than one parent class. The objects created by the child class can access the methods defined in all the parent classes. In the above code, let us add one more class called Cycle. Here the get methods get_company and get_speed will be defined in the Car class and the methods get_color and get_year methods will be defined in Trike Class.

In multiple inheritance, a child class will have more than one parent class. The objects created by the child class can access the methods defined in all the parent classes. In the above code, let us add one more class called Cycle. Here the get methods get_company and get_speed will be defined in the Car class and the methods get_color and get_year methods will be defined in Trike Class.

class Car:
def __init__(self,company,speed,color,year):
self.company = company
self.speed = speed
self.color = color
self.year = year
def get_speed(self):
print(self.speed)
def get_company(self):
print(self.company)class Trike():
def __init__(self,company,speed,color,year):
self.company = company
self.speed = speed
self.color = color
self.year = year
def get_color(self):
print(self.color)
def get_year(self):
print(self.year)class Cycle(Car,Trike):
def __init__(self,company,speed,color,year):
self.company = company
self.speed = speed
self.color = color
self.year = yearCar1 = Car("ABC",125,"RED",2019)
Car2 = Car("XYZ",150,"BLUE",2020)
Car3 = Car("LMN",200,"YELLOW",2020)Trike1 = Trike("GHJ",90,"Grey",2020)
Trike2 = Trike("DFG",80,"Violet",2019)Cycle1 = Cycle("WER",30,"RED",2020)Cycle1.get_company()
Cycle1.get_color()

Output

輸出量

WER
RED

多級繼承 (Multi Level Inheritance)

Multilevel inheritance is a type of inheritance in which the child class is used as a parent of another child class. The child class can access the methods of the parent of its parent class.

Multilevel inheritance is a type of inheritance in which the child class is used as a parent of another child class. The child class can access the methods of the parent of its parent class.

class Car:
def __init__(self,company,speed,color,year):
self.company = company
self.speed = speed
self.color = color
self.year = year
def get_speed(self):
print(self.speed)
def get_company(self):
print(self.company)
def get_color(self):
print(self.color)
def get_year(self):
print(self.year)class Trike(Car):
def __init__(self,company,speed,color,year):
self.company = company
self.speed = speed
self.color = color
self.year = yearclass Cycle(Trike):
def __init__(self,company,speed,color,year):
self.company = company
self.speed = speed
self.color = color
self.year = yearCar1 = Car("ABC",125,"RED",2019)
Car2 = Car("XYZ",150,"BLUE",2020)
Car3 = Car("LMN",200,"YELLOW",2020)Trike1 = Trike("GHJ",90,"Grey",2020)
Trike2 = Trike("DFG",80,"Violet",2019)Cycle1 = Cycle("WER",30,"RED",2020)Cycle1.get_company()
Cycle1.get_color()

Output

輸出量

WER
RED

層次繼承 (Hierarchical Inheritance)

If more than one child having the same parent, then the type of inheritance is called hierarchical inheritance. All the children created using the same parent can inherit from the class.

If more than one child having the same parent, then the type of inheritance is called hierarchical inheritance. All the children created using the same parent can inherit from the class.

class Car:
def __init__(self,company,speed,color,year):
self.company = company
self.speed = speed
self.color = color
self.year = year
def get_speed(self):
print(self.speed)
def get_company(self):
print(self.company)
def get_color(self):
print(self.color)
def get_year(self):
print(self.year)class Trike(Car):
def __init__(self,company,speed,color,year):
self.company = company
self.speed = speed
self.color = color
self.year = yearclass Cycle(Car):
def __init__(self,company,speed,color,year):
self.company = company
self.speed = speed
self.color = color
self.year = yearCar1 = Car("ABC",125,"RED",2019)
Car2 = Car("XYZ",150,"BLUE",2020)
Car3 = Car("LMN",200,"YELLOW",2020)Trike1 = Trike("GHJ",90,"Grey",2020)
Trike2 = Trike("DFG",80,"Violet",2019)Cycle1 = Cycle("WER",30,"RED",2020)Trike1.get_company()
Cycle1.get_color()

Output

輸出量

GHJ
RED

Hybrid Inheritance (Hybrid Inheritance)

Hybrid Inheritance contains a mixture of various types of inheritance in one program. Try to build a program with hybrid inheritance yourself.

Hybrid Inheritance contains a mixture of various types of inheritance in one program. Try to build a program with hybrid inheritance yourself.

The usage of a file system is an important thing in the field of computer science. It is the most common method used to store required information in various formats. Usually, every programmer will use standard input output methods to test a logical concept. But, In the real time computing systems the standard input output operations is not only enough. When we use standard IO method in a program, the output will remain until the execution ends. File system is the best solution to store the information permanently in a memory device of a computer. This article will help you to understand the basics of file handling and advanced functions in file handling in python.

The usage of a file system is an important thing in the field of computer science. It is the most common method used to store required information in various formats. Usually, every programmer will use standard input output methods to test a logical concept. But, In the real time computing systems the standard input output operations is not only enough. When we use standard IO method in a program, the output will remain until the execution ends. File system is the best solution to store the information permanently in a memory device of a computer. This article will help you to understand the basics of file handling and advanced functions in file handling in python.

A Computer File (A Computer File)

A computer file is a virtual environment that acts as a container for various types of information. Consider the real world, we have a lot of stuffs such as papers and books to store information. The computer needs a system same as that. The file system combines various files in a memory device with the help of directory. Directory of a file is a string that denotes where the file is stored in the memory disc.

A computer file is a virtual environment that acts as a container for various types of information. Consider the real world, we have a lot of stuffs such as papers and books to store information. The computer needs a system same as that. The file system combines various files in a memory device with the help of directory. Directory of a file is a string that denotes where the file is stored in the memory disc.

The directory can be considered as the address of the file. A file can be stored in different folders in a drive. Each folder is separated by a back slash (\). A file name will contain two parts. They are file name and extension. File name is a unique string used to name the file. The extension is the suffix used after the file name to denote the type of file. The structure of a file directory is given below.

The directory can be considered as the address of the file. A file can be stored in different folders in a drive. Each folder is separated by a back slash (\). A file name will contain two parts. They are file name and extension. File name is a unique string used to name the file. The extension is the suffix used after the file name to denote the type of file. The structure of a file directory is given below.

Image for post
Structure of File Directory
Structure of File Directory

The file name and the extension must be separated by a dot. The file name should not contain any special character in it. The example extensions are .mp4, .mp3.

The file name and the extension must be separated by a dot. The file name should not contain any special character in it. The example extensions are .mp4, .mp3.

Files in Python (Files in Python)

Even though we have various file formats in our computer, the in-built methods in python can handle two major types of files. The types are text files and binary files. The text and binary files has .txt and .bin as their extensions respectively. We have to understand both types of files. Text files are used to store human readable information whereas the binary files contains computer readable information that are written using binary digits 0s and 1s.

Even though we have various file formats in our computer, the in-built methods in python can handle two major types of files. The types are text files and binary files. The text and binary files has .txt and .bin as their extensions respectively. We have to understand both types of files. Text files are used to store human readable information whereas the binary files contains computer readable information that are written using binary digits 0s and 1s.

Image for post
Classification of Files in Python
Classification of Files in Python

The file processing in python is done by two different types of approaches. One is processing the content in the file. Another one is processing the directory. The first one can be done by the built in functions. The second one will be processed by the os module methods. In this article we will concentrate only on the file content manipulation.

The file processing in python is done by two different types of approaches. One is processing the content in the file. Another one is processing the directory. The first one can be done by the built in functions. The second one will be processed by the os module methods. In this article we will concentrate only on the file content manipulation.

Operations on File (Operations on File)

The operations performed on a file is called the file operation. Following is the list of operations can be applied on a file in python.

The operations performed on a file is called the file operation. Following is the list of operations can be applied on a file in python.

  1. Opening or Creating a File

    Opening or Creating a File
  2. Writing a File

    Writing a File
  3. Reading a File

    Reading a File
  4. Closing a File

    Closing a File
  5. Renaming a File

    Renaming a File
  6. Deleting a File

    Deleting a File

Opening or Creating a New File in Python (Opening or Creating a New File in Python)

The very first thing to do in file handling is the creation of file. The method open() is used to open an existing file or creating a new file. If the complete directory is not given then the file will be created in the directory in which the python file is stored. The syntax for using open() method is given below.

The very first thing to do in file handling is the creation of file. The method open() is used to open an existing file or creating a new file. If the complete directory is not given then the file will be created in the directory in which the python file is stored. The syntax for using open() method is given below.

Syntax: file_object = open( file_name, “Access Mode”, Buffering )

Syntax: file_object = open ( file_name, “Access Mode”, Buffering )

File name is a unique name in a directory. The open() function will create the file with the specified name if it is not already exists otherwise it will open the already existing file. The open method returns file object which can be stored in the name file_object.

File name is a unique name in a directory. The open() function will create the file with the specified name if it is not already exists otherwise it will open the already existing file. The open method returns file object which can be stored in the name file_object .

The access mode is the string which tells in what mode the file should be opened for operations. There are three different access modes are available in python.

The access mode is the string which tells in what mode the file should be opened for operations. There are three different access modes are available in python.

Reading: Reading mode is crated only for reading the file. The pointer will be at the beginning of the file.

R eading: Reading mode is crated only for reading the file. The pointer will be at the beginning of the file.

Writing: Writing mode is used for overwriting the information on existing file.

Writing: Writing mode is used for overwriting the information on existing file.

Append: Append mode is same as the writing mode. Instead of over writing the information this mode append the information at the end.

Append: Append mode is same as the writing mode. Instead of over writing the information this mode append the information at the end.

Below is the list of representation of various access modes in python.

Below is the list of representation of various access modes in python.

Reading ModeR   - Opens a text file for Reading
Rb - Opens a binary file for Reading
r+ - Opens a text file for Reading and Writing
rb+ - Opens a binary file for Reading and WritingWriting ModeW - Opens a text file for Writing
Wb - Opens a binary file for Writing
w+ - Opens a text file for Reading and Writing
wb+ - Opens a binary file for Reading and WritingAppend ModeA - Opens a text file for appending
Ab - Opens a binary file for appending
a+ - Opens a text file for appending and reading
ab+ - Opens a binary file for appending and reading

What is Buffering ? (What is Buffering ?)

Buffering is the process of storing a chunk of a file in a temporary memory until the file loads completely. In python there are different values can be given. If the buffering is set to 0 , then the buffering is off. The buffering will be set to 1 when we need to buffer the file.

Buffering is the process of storing a chunk of a file in a temporary memory until the file loads completely. In python there are different values can be given. If the buffering is set to 0 , then the buffering is off. The buffering will be set to 1 when we need to buffer the file.

Creating our first file (Creating our first file)

We have discussed lot of theoretical part in the article. Let us try to create a file object in python. Before creating a file object we have to decide proper attributes to be applied. The major three things in file object creation are file name, access mode and buffering. Let the file name be my_file_name . We are going to create a new file in the text format. We have to write something on the file. So choosing the mode for reading and writing will be perfect one. As I am going to create text based file, I can choose the mode w+ for the file. Buffering can be used for text type file. So we can enable the buffering.

We have discussed lot of theoretical part in the article. Let us try to create a file object in python. Before creating a file object we have to decide proper attributes to be applied. The major three things in file object creation are file name, access mode and buffering. Let the file name be my_file_name . We are going to create a new file in the text format. We have to write something on the file. So choosing the mode for reading and writing will be perfect one. As I am going to create text based file, I can choose the mode w+ for the file. Buffering can be used for text type file. So we can enable the buffering.

my_file = open(my_file_name.txt,"w+",1)

Now a text file with the name my_file_name is created successfully. We can able to apply various methods on the file object. Here is the list of useful methods used on file object.

Now a text file with the name my_file_name is created successfully. We can able to apply various methods on the file object. Here is the list of useful methods used on file object.

file.name   - Returns the name of file
file.mode - Returns the access mode of the file
file.closed - Returns true if the file is closed

Let us apply all the methods on our file object my_file .

Let us apply all the methods on our file object my_file .

my_file = open("my_file_name.txt", "w+", 1)
print(my_file.name)
print(my_file.mode)
print(my_file.closed)

Output

輸出量

my_file_name.txt
w+
False

Let us try the same with the r+ access mode instead of w+ .

Let us try the same with the r+ access mode instead of w+ .

my_file = open("my_file_name.txt", "r+", 1)
print(my_file.name)
print(my_file.mode)
print(my_file.closed)

Output

輸出量

Traceback (most recent call last):
File "main.py", line 1, in <module>
my_file = open("my_file_name.txt", "r+", 1)
FileNotFoundError: [Errno 2] No such file or directory: 'my_file_name.txt'

If you need to use r+ the file must present already in the directory. Otherwise it will give some error. As we created a new file there is no information available in the text file. You can check manually by opening the file in the directory.

If you need to use r+ the file must present already in the directory. Otherwise it will give some error. As we created a new file there is no information available in the text file. You can check manually by opening the file in the directory.

Writing Information in the File (Writing Information in the File)

In the previous step we have created a file for reading and writing modes. In this part we will write something in the text document. The write() method is used for writing a string inside a file. The syntax for using write function is given below.

In the previous step we have created a file for reading and writing modes. In this part we will write something in the text document. The write() method is used for writing a string inside a file. The syntax for using write function is given below.

Syntax: file_object.write(“String”)

Syntax: file_object .write(“String”)

string = "This is a String in Python"
my_file = open(my_file_name.txt,"w+",1)my_file.write(string)

Now the information will be written in the text file. This information will be saved once we close the file.

Now the information will be written in the text file. This information will be saved once we close the file.

Reading Information in the File (Reading Information in the File)

The text information in the text file can be extracted with the help of read() function. The syntax for reading is given below.

The text information in the text file can be extracted with the help of read() function. The syntax for reading is given below.

Syntax: var_name = file_object.read(index)

Syntax: var_name = file_object .read(index)

string = "This is a String in Python"
my_file = open(my_file_name.txt,"r+",1)
my_file.write(string)my_string = my_file.read()
print(my_string)

Output

輸出量

This is a String in Python

The index argument passed inside the read() method determines how many characters to be printed from the file.

The index argument passed inside the read() method determines how many characters to be printed from the file.

Closing a File in Python (Closing a File in Python)

The previous programs are not suggested for real time. After processing the content in a file, the file must be saved and closed. To do this we can use another method close() for closing the file. This is an important method to be remembered while handling files in python.

The previous programs are not suggested for real time. After processing the content in a file, the file must be saved and closed. To do this we can use another method close() for closing the file. This is an important method to be remembered while handling files in python.

Syntax: file_object.close()

Syntax: file_object .close()

string = "This is a String in Python"
my_file = open(my_file_name.txt,"w+",1)
my_file.write(string)
my_file.close()
print(my_file.closed)

Output

輸出量

True

The method file.closed returns True as the file is closed.

The method file.closed returns True as the file is closed.

Renaming a File (Renaming a File)

The file name can be changed by a method rename() . The rename() method is available in the os module. Before calling the rename function we have to import the os module into our program. The syntax is given below.

The file name can be changed by a method rename() . The rename() method is available in the os module. Before calling the rename function we have to import the os module into our program. The syntax is given below.

Syntax: os.rename(old_name, new_name)

Syntax: os .rename(old_name, new_name)

import os
string = "This is a String in Python"
my_file = open("my_file_name.txt", "w+", 1)
my_file.write(string)
os.rename("my_file_name.txt", "renamed.txt")

Now the file will be renamed into the new name.

Now the file will be renamed into the new name.

Deleting a File (Deleting a File)

Another method from the same os module, remove() is used to delete an existing file in a directory. The following is the syntax for using delete operation.

Another method from the same os module, remove() is used to delete an existing file in a directory. The following is the syntax for using delete operation.

Syntax: os.remove(file_name)

Syntax: os .remove(file_name)

import os
string = "This is a String in Python"
my_file = open("my_file_name.txt", "w+", 1)
my_file.write(string)
os.remove("my_file_name.txt")

Thank you all for spending your precious time on my writing. This very long tutorial comprises of my previous articles written by me. Most of the readers asked me to give all things at one place. Here It is. Thank you again for the love and support. ??????

Thank you all for spending your precious time on my writing. This very long tutorial comprises of my previous articles written by me. Most of the readers asked me to give all things at one place. Here It is. Thank you again for the love and support. ??????

If you need any guidance for learning python, just connect me with the email id provided. mydigitalwallets@gmail.com.

If you need any guidance for learning python, just connect me with the email id provided. mydigitalwallets@gmail.com .

Follow me on Medium

跟我來

翻譯自: https://towardsdatascience.com/a-complete-walk-through-in-python-for-beginners-bf59a1f04296

python初學者

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/388033.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/388033.shtml
英文地址,請注明出處:http://en.pswp.cn/news/388033.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

c# nat udp轉發

UdpClient myClient;Thread recvThread;//打開udp端口開始接收private void startRecv(int port){myClient new UdpClient(port);recvThread new Thread(new ThreadStart(receive));recvThread.Start();}//停止接收private void stopRecv(){recvThread.Abort();}private void…

【Code-Snippet】TextView

1. TextView文字過長&#xff0c;顯示省略號 【參考】 必須要同時設置XML和JAVA&#xff0c;而且&#xff0c;java中設置文字必須是在最后。 android:ellipsize"start|end|middle" //省略號的位置 android:singleLine"true" android:lines"2"…

Object 的靜態方法之 defineProperties 以及數據劫持效果

再提一下什么是靜態方法&#xff1a; 靜態方法&#xff1a;在類身上的方法&#xff0c;  動態方法:在實例身上的方法 Object.defineProperties(obj, props)obj&#xff1a;被添加屬性的對象props&#xff1a;添加或更新的屬性對象給對象定義屬性&#xff0c;如果存在該屬性&a…

Spring實現AOP的4種方式

Spring實現AOP的4種方式 先了解AOP的相關術語: 1.通知(Advice): 通知定義了切面是什么以及何時使用。描述了切面要完成的工作和何時需要執行這個工作。 2.連接點(Joinpoint): 程序能夠應用通知的一個“時機”&#xff0c;這些“時機”就是連接點&#xff0c;例如方法被調用時、…

如何使用Plotly在Python中為任何DataFrame繪制地圖的衛星視圖

Chart-Studio和Mapbox簡介 (Introduction to Chart-Studio and Mapbox) Folium and Geemap are arguably the best GIS libraries/tools to plot satellite-view maps or any other kinds out there, but at times they require an additional authorization to use the Google…

Java入門系列-26-JDBC

認識 JDBC JDBC (Java DataBase Connectivity) 是 Java 數據庫連接技術的簡稱&#xff0c;用于連接常用數據庫。 Sun 公司提供了 JDBC API &#xff0c;供程序員調用接口和類&#xff0c;集成在 java.sql 和 javax.sql 包中。 Sun 公司還提供了 DriverManager 類用來管理各種不…

3.19PMP試題每日一題

在房屋建造過程中&#xff0c;應該先完成衛生管道工程&#xff0c;才能進行電氣工程施工&#xff0c;這是一個&#xff1a;A、強制性依賴關系B、選擇性依賴關系C、外部依賴關系D、內部依賴關系 作者&#xff1a;Tracy19890201&#xff08;同微信號&#xff09;轉載于:https://…

Can't find temporary directory:internal error

今天我機子上的SVN突然沒有辦法進行代碼提交了&#xff0c;出現的錯誤提示信息為&#xff1a; Error&#xff1a;Cant find temporary directory:internal error 然后試了下其他的SVN源&#xff0c;發現均無法提交&#xff0c;并且update時也出現上面的錯誤信息。對比項目文件…

snowflake 數據庫_Snowflake數據分析教程

snowflake 數據庫目錄 (Table of Contents) Introduction 介紹 Creating a Snowflake Datasource 創建雪花數據源 Querying Your Datasource 查詢數據源 Analyzing Your Data and Adding Visualizations 分析數據并添加可視化 Using Drilldowns on Your Visualizations 在可視化…

jeesite緩存問題

jeesite&#xff0c;其框架主要為&#xff1a; 后端 核心框架&#xff1a;Spring Framework 4.0 安全框架&#xff1a;Apache Shiro 1.2 視圖框架&#xff1a;Spring MVC 4.0 服務端驗證&#xff1a;Hibernate Validator 5.1 布局框架&#xff1a;SiteMesh 2.4 工作流引擎…

高級Python:定義類時要應用的9種最佳做法

重點 (Top highlight)At its core, Python is an object-oriented programming (OOP) language. Being an OOP language, Python handles data and functionalities by supporting various features centered around objects. For instance, data structures are all objects, …

Java 注解 攔截器

場景描述&#xff1a;現在需要對部分Controller或者Controller里面的服務方法進行權限攔截。如果存在我們自定義的注解&#xff0c;通過自定義注解提取所需的權限值&#xff0c;然后對比session中的權限判斷當前用戶是否具有對該控制器或控制器方法的訪問權限。如果沒有相關權限…

醫療大數據處理流程_我們需要數據來大規模改善醫療流程

醫療大數據處理流程Note: the fictitious examples and diagrams are for illustrative purposes ONLY. They are mainly simplifications of real phenomena. Please consult with your physician if you have any questions.注意&#xff1a;虛擬示例和圖表僅用于說明目的。 …

What's the difference between markForCheck() and detectChanges()

https://stackoverflow.com/questions/41364386/whats-the-difference-between-markforcheck-and-detectchanges轉載于:https://www.cnblogs.com/chen8840/p/10573295.html

ASP.NET Core中使用GraphQL - 第七章 Mutation

ASP.NET Core中使用GraphQL - 目錄 ASP.NET Core中使用GraphQL - 第一章 Hello WorldASP.NET Core中使用GraphQL - 第二章 中間件ASP.NET Core中使用GraphQL - 第三章 依賴注入ASP.NET Core中使用GraphQL - 第四章 GrahpiQLASP.NET Core中使用GraphQL - 第五章 字段, 參數, 變量…

POM.xml紅叉解決方法

方法/步驟 1用Eclipse創建一個maven工程&#xff0c;網上有很多資料&#xff0c;這里不再啰嗦。 2右鍵maven工程&#xff0c;進行更新 3在彈出的對話框中勾選強制更新&#xff0c;如圖所示 4稍等片刻&#xff0c;pom.xml的紅叉消失了。。。

JS前臺頁面驗證文本框非空

效果圖&#xff1a; 代碼&#xff1a; 源代碼&#xff1a; <script type"text/javascript"> function check(){ var xm document.getElementById("xm").value; if(xm null || xm ){ alert("用戶名不能為空"); return false; } return …

python對象引用計數器_在Python中借助計數器對象對項目進行計數

python對象引用計數器前提 (The Premise) When we deal with data containers, such as tuples and lists, in Python we often need to count particular elements. One common way to do this is to use the count() function — you specify the element you want to count …

套接字設置為(非)阻塞模式

當socket 進行TCP 連接的時候&#xff08;也就是調用connect 時&#xff09;&#xff0c;一旦網絡不通&#xff0c;或者是ip 地址無效&#xff0c;就可能使整個線程阻塞。一般為30 秒&#xff08;我測的是20 秒&#xff09;。如果設置為非阻塞模式&#xff0c;能很好的解決這個…

經典問題之「分支預測」

問題 來源 &#xff1a;stackoverflow 為什么下面代碼排序后累加比不排序快&#xff1f; public static void main(String[] args) {// Generate dataint arraySize 32768;int data[] new int[arraySize];Random rnd new Random(0);for (int c 0; c < arraySize; c)data…