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以及如何学习语言。
先做这个... (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的乐趣应该在于看到简短,简洁,易读的类,这些类以少量清晰的代码表达很多动作,而不是让大量琐碎的代码使读者无聊而死。”
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。 单击以下链接练习代码示例。
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感兴趣吗? 回答这些问题后,请查看答案。 每个答案的类型不同。 第一种是基于文本的数据。 第二个是数值数据。 第三个是分类数据。
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美元。 您总共需要十块巧克力。 收集完巧克力后,您必须支付账单。 现在,您将如何计算金额?
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。
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中有三个逻辑运算符。 它们是and , or 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中的决策控制语句来实现。 决策控制语句如下。
- if 如果
- if…else 如果别的
- 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.
在编程中一次又一次地循环或重复相同类型的操作是很重要的。 这种方法称为循环。
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”。
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”
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.
要访问特定索引中的字符,我们必须将索引号放在变量名末尾的方括号[]中。
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()方法将字符串的第一个字符转换为大写。 如果第一个字符已经大写,则不会进行任何更改。
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()方法用于将字符串中的所有大写字符转换为小写字符。
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()方法用于将大写字母转换为小写字母,并将小写字母转换为大写字母。
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()是一个字符串方法,用于大写字符串中的所有字符。
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()也是一个字符串方法,用于将整个字符串转换为小写字母。
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中所有单词的首字符。
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。
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。
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。
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。
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。
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。
string = " "
print(string.isspace())
Output
输出量
True
🔖istitle()
🔖istitle()
istitle() is used to check whether a string is a title or not.
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()方法用于计算子字符串在字符串中出现的时间。
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()方法用于检查字符串是否以给定的子字符串开头。
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。
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()方法将创建一个异常。
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()方法相同。 但是,它返回字符串中最后一次出现子字符串的索引。
string = "I love Python"
print(string.rindex("o"))
print(string.rfind("o"))
Output
输出量
11
11
🔖 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()方法用于将字符串放置在通过它的宽度中心。
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()方法用于将字符串以特定宽度对齐到左右两端。
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()有助于自定义字符串中选项卡的长度。
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.
在列表中,所有元素都用逗号分隔。 可以通过将所有元素插入方括号内来创建列表。 列表中的元素可以有多种类型。
用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中所有元素的索引都与字符串数据类型相同。 每个元素都可以使用正整数和负整数进行访问。
访问列表中的值 (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()方法用于在列表的末尾添加项目。 我们可以将许多项目连续添加到列表中。
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()方法清除列表中的所有条目。 删除所有元素后,它将返回一个空列表。
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()方法用于复制现有列表并将该列表存储在另一个列表变量中。
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()方法用于计算一个值在列表中重复的次数。
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()用于将诸如列表的收集项添加到另一个列表变量。 传递的列表将附加在上一个列表的末尾。
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将通过异常。
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()方法用于在列表中的特定索引处添加元素。
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()方法用于删除特定索引中的元素。
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()方法,但是在此方法中,元素是通过传递的,而不是索引。
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()用于反转列表中的所有元素。 不需要任何争论。
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()方法用于按升序对列表中的所有元素进行排序。
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.
通过用逗号分隔每个元素来创建元组。 元组元素用括号()括起来。 元组中的项可以有多种。
用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.
元组中的每个元素都用整数索引。 元组中的任何项都可以通过正或负索引访问。
访问元组中的值 (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()中发生了多少次。
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()方法用于获取第一次出现的项目的索引。
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元素用花括号括起来。 集合中的所有元素都是唯一值。
创作集 (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()方法用于添加要设置的元素。
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.
此方法清除集中存在的所有元素。
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.
此方法返回一个新集合,其中包含存在于一个集合中但不存在于另一个集合中的元素。
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()方法用于从集合中删除一个项目。
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.
交集()方法用于创建一个在所有集合中具有共同元素的新集合。
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()删除指定元素。
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.
使用这种方法的原因是很难记住大脑中的许多数字。 但是,您可以轻松记住这些名称。 当您需要拨打电话时,可以借助列表中的姓名参考联系人列表,这也足以访问电话号码。 词典数据类型以相同的方式工作。
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.
字典中的每个元素将采用以下形式。
字典的结构 (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.
词典将具有一个或多个用逗号分隔的键值对。 使用花括号{}创建字典。 字典中每个元素的键和值用冒号分隔:。 词典中的每个键都必须是唯一的。
用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,
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 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.
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.
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.
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.
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.
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.
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.
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.
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.
- Opening or Creating a File Opening or Creating a File
- Writing a File Writing a File
- Reading a File Reading a File
- Closing a File Closing a File
- Renaming a File Renaming a File
- 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.mzph.cn/news/388033.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!