500 oops_从基本到oops概念,Python中的零英雄

500 oops

Python language has become popular these days among almost every programmer. After research about python, I found that python language is compatible in all fields all over the world. The basic thought of every programmer is that why they are learning to program. The most common applications we found where we can explore the python programming are Web development, GUI, Game development, Database management, software development, Education and lots more. This article is for everyone who wants to start learning python programming. This article will guide you from basic python to the OOPs concept. So, maybe this will be a very long article. Learning is a new adventure.

如今,Python语言在几乎所有程序员中都变得越来越流行。 在研究了python之后,我发现python语言在世界各地的所有领域都兼容。 每个程序员的基本思想是他们为什么要学习编程。 我们发现可以探索python编程的最常见应用程序是Web开发,GUI,游戏开发,数据库管理,软件开发,教育等。 本文适用于所有想开始学习python编程的人。 本文将指导您从基本的python到OOPs概念。 因此,也许这将是一篇很长的文章。 学习是一种新的冒险。

Topics to be covered:

涉及的主题:

Section 1: Variable Fundamentals, Data Types (List, Tuple, Set, Range, String, Dictionary)

第1部分 :变量基础知识,数据类型(列表,元组,集合,范围,字符串,字典)

Section 2: Operators, Number System, Importing libraries and functions

第2节 :运算符,编号系统,导入库和函数

Section 3: Loops, Array, Matrices

第三节 :循环,数组,矩阵

Section 4: Functions

第4节 :功能

Section 5: OOPs and Exception handling

第5节 :OOP和异常处理

Section 1:

第1节:

Variable Fundamentals

可变基础

Variables are used to store data. It can be declared with any name.

变量用于存储数据。 可以使用任何名称声明。

Image for post

Examples:

例子:

#assigning value 5 to variable i
i=5print(i) #output: 5#assigning two value in same line
i,j = 4,5
print(i+j) #output: 9#Basic Arithmetic operations
x,y = 2,3
print(x+y) #output: 5
print(x*y) #output: 6x,y = 8,4
print(x/y) #output: 2.0
#using floor division to remove the decimal
print(x//y) #output: 2c = 3
print(x+y-c) #output: 9x,y = 2,3
#to make y the power of x, in python use double star
print(x**y) #output: 8

Data types

资料类型

  1. String: strings in Python are arrays of bytes representing Unicode characters. We can create a string with enclosed quotes.

    字符串: Python中的字符串是表示Unicode字符的字节数组。 我们可以创建一个带有引号的字符串。

Example:

例:

print('Amit')                      #output: Amit
print('Amit's House') #output: error#to solve this error use double quotes
print("Amit's House") #output: Amit's House

What if we want to access the string with indexing.

如果我们想使用索引访问字符串怎么办。

Image for post
x = ARGENTINA
print(x[0]) #output: A
print(x[8]) #output: A
print(x[-2]) #output: N
print(x[-8]) #output: R
print(x[1:4]) #output: RGE
print(x[5:7]) #output: TI#we cannot change the character with indexing
x[0] = 'W'
print(x[0]) #output: error
'str' doesn't support item assignment#to know the length of the string
print(len(x)) #output: 9

2. List: List is used to grouping together a number of things in a single bracket.

2.列表:列表用于将多个内容归为一个括号。

The list is mutable means we can change the value by indexing. Square bracket [] is used to define the list.

该列表是可变的,这意味着我们可以通过建立索引来更改值。 方括号[]用于定义列表。

Example:

例:

lst1 = [2,4,5,6]print(lst1[0])                      #output: 2
print(lst1[-1]) #output: 6lst2 = ['India', 'USA', 'Chile']
print(lst2) #output: ['India', 'USA', 'Chile']
Image for post
List containing multiple data types
包含多种数据类型的列表

Some operations/functions on list

列表中的一些操作/功能

#adding number in a list
lst1 = [2,4,5,6]
lst1.append(8)
print(lst1) #output: [2,4,5,6,8]#adding number in a list at particular position
lst1.insert(3,10)
print(lst1) #output: [2,4,5,10,6,8]#remove the particular known number from the list
lst1.remove(5)
print(list1) #output: [2,4,10,6,8]#deleting multiple values
del lst1[2:]
print(lst1) #output: [2,4]#extend list
lst1.extend([3,5,7])
print(lst1) #output: [2,4,3,5,7]print(min(lst1)) #output: 2
print(max(lst1)) #output: 7

3. Tuple: A Tuple is a collection of Python objects separated by commas. In some ways, a tuple is similar to a list in terms of indexing, nested objects and repetition. The tuple is immutable means we can not change the value by indexing. Round bracket () is used to define the tuple.

3.元组:元组是用逗号分隔的Python对象的集合。 在某些方面,元组在索引,嵌套对象和重复方面类似于列表。 元组是不可变的,这意味着我们无法通过索引更改值。 圆括号()用于定义元组。

Examples:

例子:

tup = (4,5,6,7,8)
print(tup) #output: (4,5,6,7,8)
print(tup[1]) #output: 5tup[1] = 9
print(tup) #output: error
'tuple' doesn't support item assignment

Where we use tuple?

我们在哪里使用元组?

The tuple is like a list, in a certain project there is a requirement of a list where we do not want the value to be changed, so tuple is useful in these conditions. Iteration in a tuple is faster than a list and enhance the speed of execution.

元组就像一个列表,在某些项目中,需要一个列表,我们不希望更改值,因此在这些情况下,元组很有用。 元组中的迭代比列表快,并提高了执行速度。

4. Set: A set is a collection of elements which is unordered and unindexed. Set is immutable means we can not change the value by indexing because it is unordered. Curly bracket {} is used to define the set.

4.设置:是其是无序和未加索引的元素的集合。 Set是不可变的,这意味着我们无法通过索引更改值,因为它是无序的。 花括号{}用于定义集合。

Examples:

例子:

s = {3,4,5,6}
print(s) #output: {4,6,3,5}#add operation to add something in a set
s.add(7)
print(s) #output: {3,6,5,4,7}

More on variables:

有关变量的更多信息:

If we want to know the address of the variable, then we can use the id operation on that variable.

如果我们想知道变量的地址,那么我们可以对该变量使用id操作。

Example:

例:

Image for post
address value of variable ‘a’
变量“ a”的地址值
a = 5
print(id(a)) #output: 1743928304

5. Range: The range() function is used to generate a sequence of numbers over time.

5.范围: range()函数用于随时间生成一系列数字。

Example:

例:

range(10)
print(range(10)) #output: range(0,10)#make a list of the range
print(list(range(10))) #output: [0,1,2,3,4,5,6,7,8,9]#range value from start, stop and step
print(list(range(2,10,2))) #output: [2,4,6,8]

6. Dictionary: Dictionaries are Python’s implementation of a data structure that is more generally known as an associative array. A dictionary is a collection that is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values.

6.字典:字典是Python对数据结构的一种实现,这种结构通常被称为关联数组。 字典是无序,可变和索引的集合。 在Python中,字典用大括号括起来,并且具有键和值。

Example:

例:

#empty dictionary
dict = {}
#dictionary with integer keys
dict = {1: 'India', 2: 'Japan'}
#dictionary with mixed keys
dict = {'City': 'Mumbai', 1: [4, 7, 2]}
#using dict() function
dict = dict({1:'India', 2:'Japan'})
#from sequence having each item as a pair
dict = dict([(1,'India'), (2,'Japan')])

To access the values in a dictionary, indexing is used with other data types to access values, a dictionary uses keys.

为了访问字典中的值,索引与其他数据类型一起使用来访问值,字典使用keys

print(dict['City'])                     #output: Mumbai# update value
dict['City'] = 'Delhi'print(dict) #output: dict = {'City': 'Delhi', 1: [4, 7, 2]}

Section 2:

第2节:

  1. Operators

    经营者

Arithmetic operator

算术运算符

x,y = 2,3
print(x+y) #output: 5
print(x-y) #output: -1
print(x*y) #output: 6
print(x/y) #output: 0.66666

Assignment operator

赋值运算符

x = 2
x = x+2
print(x) #output: 4x += 2
print(x) #output: 6x *= 2
print(x) #output: 12

Relational operator

关系运算符

a,b = 5,6print(a<b)                        #output: True
print(a>b) #output: False
print(a==b) #output: False
print(a<=b) #output: True
print(a>=b) #output: False
print(a!=b) #output: True

Logical operator

逻辑运算符

a,b = 5,4
print(a<7 and b<5) #output: True
print(a<7 and b<3) #output: Falseprint(a<7 or b<3) #output: Truex = True
print(x) #output: True
print(not x) #output: False

Bitwise operator

按位运算符

#compliment(~)
print(~12) #output: -13#Bitwise AND
print(12 & 13) #output: 12#Bitwise OR
print(12 | 13) #output: 13
print(25 | 30) #output: 24#XOR (^)
print(12^13) #output: 1
print(25^30) #output: 7# Left Shift
print(10<<2) #output: 40# right Shift
print(10>>2) #output: 2

2. Number System

2.编号系统

Image for post
#convert 25 to binary format
print(bin(25)) #output: 0b11001print(0b0101) #output: 5
print(oct(25)) #output: 0o31
print(hex(25)) #output: 0x19
print(0xf) #output: 15

3. Importing functions

3.导入功能

Python has a way to put definitions in a file and use them in a script or an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or the main module. In python, we have lots of modules to work with by default these modules are not there for us. If we want to use them then we need to import them in python.

Python提供了一种将定义放入文件中并在脚本或解释器的交互式实例中使用它们的方法。 这样的文件称为模块 ; 一个模块中的定义可以导入到其他模块或模块中。 在python中,默认情况下我们有很多模块可以使用,这些模块不适合我们。 如果要使用它们,则需要将它们导入python。

Example:

例:

x = sqrt(25)
print(x) #output: error
name sqrt is not defined#importing the moduleimport math
x = math.sqrt(25)
print(x) #output: 5.0x = math.sqrt(15)
print(x) #output: 3.872

What is alias name in a module?

什么是模块中的别名?

An alias is a second name for a piece of data. In python, aliasing happens whenever one variable’s value is assigned to another variable because variables are just names that store references to values.

别名是数据的第二个名称。 在python中,每当一个变量的值分配给另一个变量时就会发生别名,因为变量只是存储对值的引用的名称。

Example:

例:

#naming math variable to m variable as an alias name
import math as m#both will give the same output
print(math.sqrt(25)) #output: 5.0
print(m.sqrt(25)) #output: 5.0

Section 3:

第3节:

  1. Loops

    循环

A loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

循环用于循环访问序列(列表,元组,字典,集合或字符串)。

if — else — elif

如果-否则-Elif

#print the statement if it is true
if True:
print("Hello World") #output: Hello World#if condition is false then this print won't execute
if False:
print("Hello World") #output: #if block is false then statement outside the box is executed
if False:
print("India")
print("Japan") #output: Japan#if-elif-else ( elif means else-if)x=2
if x==1:
print("one")
elif x==2:
print("Two")
elif x==3:
print("Three")
else:
print("Four") #output" Two

while loop

while循环

while loops repeat as long as a certain boolean condition is met.

只要满足特定的布尔条件,循环就会重复。

Image for post

For example:

例如:

x = 1                                     #output: Amit
while x <=5: Amit print("Amit") Amit
x = x+1 Amit
Amit

For loop

对于循环

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

for 循环用于遍历一个序列(列表,元组,字典,集合或字符串)。

Example:

例:

a = ["Amit", 20, 1.2]
print(x) #output: ["Amit", 20, 1.2]#with for loop
a = ["Amit", 20, 1.2]
for i in a:
print(i) #output: Amit
20
1.2#for loop with string
a = "Amit"
for i in a:
print(i) #output: A
m
i
t
Image for post

2. Arrays

2.数组

An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. An array is a special variable, which can hold more than one value at a time.

数组是存储在连续内存位置的项目的集合。 想法是将相同类型的多个项目存储在一起。 数组是一个特殊变量,一次可以容纳多个值。

Example:

例:

from array import *
val = array('i',[1,2,3,4,5])
print(val) #output: array('i',[1,2,3,4,5])#buffer_info gives the address and size of an array
print(val.buffer_info()) #output: (5972435, 5)#for loop with array
for i in val:
print(i) #output: 1
2
3
4
5

the ‘i’ in the val list is typecode, i means integer, what if we want to work with the characters, yes we can, change the typecode to ‘u’.

val列表中的“ i”是类型代码,我的意思是整数,如果我们要使用字符,该怎么办,可以将类型代码更改为“ u”。

from array import *
val = array('u',['a', 'b'])
print(val) #output: a
b

we can create the array with the user input also in python.

我们也可以在python中使用用户输入来创建数组。

from array import *
arr = array('i',[])
n = int(input("Enter the length of the array: "))
for i in range(n):
x = int(input("Enter the next value: "))
arr.append(x)
print(arr)
#output:
Enter the length of the array: 3
Enter the next value: 2
Enter the next value: 5
Enter the next value: 8
array('i',[2,5,8])

Array package does not support multi-dimensional array that where we use third-party package names numpy.

数组软件包不支持我们使用第三方软件包名称numpy的多维数组。

from numpy import *
arr = array([1,2,3,4])
print(arr) #output: [1 2 3 4]#different ways for creating arrays#breaking numbers into 16 parts
arr = linspace(0,15,16)
#output:
[0, 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15.]#try other operations like logspace, arrange, zeros, ones#concatenate two arraysa1 =array([1,2])
a2 =array([3,4])
print(concatenate([a1,a2]) #output: [1 2 3 4]

3. Matrices

3.矩阵

A matrix is a two-dimensional data structure where numbers are arranged into rows and columns.

矩阵是一种二维数据结构,其中数字按行和列排列。

Example:

例:

a1 = array([
[1,2,3],
[4,5,6]
])
print(a1) #output: [[1,2,3]
[4,5,6]
]
#to know the type of array
print(a1.dtype) #output: int32#to know the dimension and shape(rows and column) of the arrayprint(a1.ndim) #output: 2
print(a1.shape) #output: (2,3)
print(a1.size) #output: 6#to flatten the array into single list from multi-dimensiona2 = a1.flatten()
print(a2) #output: [1 2 3 4 5 6]#to make the reshape of flatten into matrix( 2 rows and 3 columns)
a3 = a2.reshape(2,3)
print(a3) #output: [[1,2,3]
[4,5,6]
]

Section 4:

第4节:

Functions

功能

A function is a block of organized, reusable code that is used to perform a single, related action. when we are working on a big project and want to break into smaller tasks then, there is a need for functions.

函数是一组有组织的可重用代码,用于执行单个相关操作。 当我们在从事大型项目并想分解成较小的任务时,就需要功能。

There are two things related to functions

与功能有关的两件事

  1. Defining a function

    定义功能
  2. Calling a function

    调用函数

syntax:

句法:

def function_name:

def function_name:

Example:

例:

#defining a function
def hello():
print('India')
print('This is second statement')#calling a function
hello()
#output: India
This is second Statement

Allocate the task to a function then, we call the function multiple times in a program. The function does a task, one is to execute the task and second is return something.

然后将任务分配给一个函数,我们在程序中多次调用该函数。 该函数执行任务,其一是执行任务,其二是返回某些内容。

#adding two numbersdef add(x,y):
c = x+y
print(c)#calling a function and passing two values
add(5,4)
#output: 9

Types of arguments in function

函数中参数的类型

  1. Position

    位置
  2. Keyword

    关键词
  3. Default

    默认
  4. Variable length

    可变长度

Position:

位置:

In the below example, how do we know that Amit goes to name and 25 goes to age that’s where position comes into the picture, just to maintain the sequence.

在下面的示例中,我们如何知道阿米特(Amit)来命名,而25岁(25岁)则是位置的位置,只是为了保持顺序。

def person(name,age):
print(name)
print(age)person('Amit', 25) #output: Amit
25

Keywords:

关键字:

what if, we don’t know the sequence, we use keywords for it.

如果我们不知道序列,我们使用关键字怎么办。

#giving keywords when we call the function 
person(age = 25, name = 'Amit')

Default:

默认:

Just using with name only in the function calling.

仅在函数调用中与name一起使用。

def person(name,age = 25):
print(name)
print(age)person('Amit') #output: Amit
25
#if we pass a value in actual argument in function calling, then it
will overwrite the value in the formal argumentsperson('name', 26) #output: Amit
26

Variable length:

可变长度:

It is used for passing multiple values to a variable

它用于将多个值传递给变量

def sum(a, *b):
c= a+b
print(c)#5 goes to a variable and (6,7,8) goes to b variable as a tuple
sum = (5,6,7,8)
#output: error
can not add int and tuple#to resolve this error, we can use for loop in tupledef sum(a, *b):
c= a
for i in b:
c = c+i
print(c)
sum = (5,6,7,8) #output: 24

Scope in a function:

功能范围:

  • A variable created inside a function is available inside that function.

    函数内部创建的变量在该函数内部可用

  • The local variable can be accessed from a function within the function.

    可以从函数内的函数访问局部变量

  • A variable created outside of a function is global and can be used by anyone.

    函数外部创建的变量是全局变量,任何人都可以使用。

  • The function will print the local x, and then the code will print the global x.

    函数将打印本地x,然后代码将打印全局x。

Example:

例:

a = 10        #global variable
def value():
a = 12 #local variable
print('inside function: ',a)
print('outside function: ',a)
#output: inside function: 12
outside function: 10

Section 5:

第5节:

  1. OOPs

    面向对象

Object-oriented programming (OOP) is a method of structuring a program by bundling related properties and behaviors into individual objects. An object contains data, like the raw or pre-processed materials at each step on an assembly line, and behavior, like the action each assembly line component performs.

面向对象编程 (OOP)是一种通过将相关属性和行为绑定到单个对象中来构造程序的方法。 一个对象包含数据,例如流水线上每个步骤的原始材料或预处理材料,以及行为,例如每个流水线组件执行的动作。

  • Create a class, which is like a blueprint for creating an object

    创建一个 ,就像创建对象的蓝图

  • Use classes to create new objects

    使用类创建新对象

Example:

例:

#Create a classclass car:
def type(self):
print("Hello")#create object car1 and car2 belongs to car class
car1 = car()
car2 = car()car.type(car1) #output: Hellocar1.type() #output: Hello
car2.type() #output: Hello

In a system we have a heap memory, objects take space in this memory. The properties that all car objects must have been defined in a method called __init__(). Every time a new car object is created, __init__() sets the initial state of the object by assigning the values of the object’s properties. the init method is called automatically. Name and type are the two argument, if we want them to be a part of an object then the object here is self.

在一个系统中,我们有一个堆内存,对象占用了该内存中的空间。 必须在名为__init__()的方法中定义所有car对象的属性。 每次创建新的car对象时, __init__()通过分配对象属性的值来设置对象的初始状态 。 初始化方法会自动调用。 名称和类型是两个参数,如果我们希望它们成为对象的一部分,那么这里的对象就是自我。

class car:
def __init__(self, name, type):
self.name = name
self.type = type

In the body of __init__(), two statements are using the self variable:

__init__()的主体中,两个语句正在使用self变量:

  1. self.name = name creates an attribute called name and assigns to it the value of the name parameter.

    self.name = name创建一个名为name的属性,并为其分配name参数的值。

  2. self.type = type creates an attribute called type and assigns to it the value of the age parameter.

    self.type = type创建一个名为type的属性,并为其指定age参数的值。

Inheritance:

遗产:

In real it is like a parent and child relationship, what your parent has, it belongs to a child also that’s why we say Inheritance. Inheritance allows us to define a class that inherits all the methods and properties of another class.

实际上,就像父母与子女的关系一样,您的父母拥有的,它属于一个孩子,这就是我们说继承的原因。 继承允许我们定义一个类,该类继承另一个类的所有方法和属性。

Types of Inheritance

继承类型

Image for post

Single Inheritance

单继承

class A:
def car1(self):
print("This is car1 type")
def car2(self):
print("This is car2 type")class B(A):
def car3(self):
print("This is car3 type")
def car4(self):
print("This is car4 type")b1=B()

Multilevel Inheritance

多级继承

class A:
def car1(self):
print("This is car1 type")
def car2(self):
print("This is car2 type")class B(A):
def car3(self):
print("This is car3 type")
def car4(self):
print("This is car4 type")class C(B):
def car5(self):
print("This is car5 type")c1=C()

Multiple Inheritance

多重继承

class A:
def car1(self):
print("This is car1 type")
def car2(self):
print("This is car2 type")class B:
def car3(self):
print("This is car3 type")
def car4(self):
print("This is car4 type")class C(A,B):
def car5(self):
print("This is car5 type")

2. Exception handling:

2.异常处理:

The try and except block in Python are used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program’s response to any exceptions in the preceding try clause.

Python中的try和except块用于捕获处理异常Python将try语句之后的代码作为程序的“正常”部分执行。 except语句之后的代码是程序对前面try子句中任何异常的响应。

The try statement works as follows.

try语句的工作方式如下。

  • First, the try clause (the statement(s) between the try and except keywords) is executed.

    首先,执行try子句 ( tryexcept关键字之间的语句)。

  • If no exception occurs, the except clause is skipped and execution of the try statement is finished.

    如果没有异常发生,将跳过except子句 ,并结束try语句的执行。

while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again..."

A class in an except clause is compatible with an exception if it is the same class or a base class.

在A类except子句是具有异常兼容如果它是同一个类或基类。

Example:

例:

a=5
b=0
try:
print(a/b) #critical statement: not sure this will work or not
except Exception:
print("You cannot divide a number by zero") #if there is error
#i will accept this
print("bye") #error and hadle it.#if there is no error
a=5
b=2
try:
print(a/b) #critical statement: not sure this will work or not
except Exception:
print("You cannot divide a number by zero")
print("bye")

There are many free online courses available for python. Pick up anyone and start learning, and implement these logic in solving problems.

有许多适用于python的免费在线课程。 挑选任何人并开始学习,并在解决问题中实施这些逻辑。

If you are reading this means you completed this long basic concept article on python.

如果您正在阅读此书,则意味着您已完成了有关python的这一长篇基本概念文章。

You can reach me at my LinkedIn link here and on my email: design4led@gmail.com.

你可以在我的LinkedIn链接到我这里 design4led@gmail.com:和我的电子邮件。

翻译自: https://medium.com/analytics-vidhya/zero-to-hero-in-python-from-basic-to-oops-concept-1e875be03c39

500 oops

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值