Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

1. Fundamentals of Python

The first stage

Take a look at this painstaking mind map of Python’s basic syntax

But this is what you need to learn in full stack Python. You don’t need that much to learn artificial intelligence

1.1 introduce Python

Nowadays, they are always talking about Python, saying that there will be Python textbooks in primary schools. They seem to be worse than primary school students who don’t know Python these days.

In that case, then? Do you know Python?

Won’t? It doesn’t matter! An introduction to Python! This article will take you through the basics of Python syntax!

Will be? All right, don’t go so fast! Take a look. After all, reviewing the old and learning the new can be a teacher!

As a high-level programming language, Python is easy to learn

Python 1.2 installation

Note that Python is now divided into python2. x and python3. x versions, and python3. x is the version we are introducing here. Do not download the error

1. Common version

You can go to the official website to download — the official website

Download and install foolproof, but there is one step to note: Add to path needs to be checked

If this parameter is not selected, you need to manually configure the environment

2. Anaconda distribution

Anaconda is a Python version, but it integrates the necessary libraries related to artificial intelligence, including Numpy, Matplotlib, etc

Download link – Click to download the 64-bit Windows installer

Then there is the foolproof installation

1.3 PyCharm editor installed

Download Pycharm professional version, how to crack my here will not teach, own Baidu

Is a fool installation, let you check all the places to check, wait until the installation is successful, then open, do not register, choose to skip, will let you try 30days

Then select New Project, click Create a New Project, fill in the information, and then Create

And then after a long wait, mind you, a long wait, a long wait

1.4 Basic Syntax

As a high-level language, Python has its own syntax format.

1. The comments

What is a comment? Comments explain our code so that others can understand it. But the computer will ignore our comments because it doesn’t need your explanation, it can understand them.

Single line comment: # This is a single line comment

Multi-line comment: “” “This is a multi-line comment “” “

2. Reserved words

Also called keywords in other languages, they are names that have a different purpose in Python.

Sometimes, you don’t need to know what the word means, you just need to know what it does, but in programming languages, you know what you mean by name, so being good at English is an advantage. But it’s not all about translation.

Python has a relatively small number of reserved words, 33

3. The identifier

Identifiers, this is something that we name ourselves, but we can’t just name it, because if we don’t know the stop frame specification, some people write this, some people write that, and the computer won’t understand it.

Specifications for identifiers: Identifiers can contain numbers, letters, and underscores, but cannot start with a number, and are case-sensitive.

Now, python3 has a Chinese Gospel: * We can use Chinese as our identifier! * Yes, that’s right, Chinese as identifier. Of course, you can’t start with a number either.

The use of identifiers will be covered in the next article.

Little practice

Determine if the following identifiers are correct

  1. 1smly
  2. smly
  3. _smly
  4. smly_
  5. sm_ly

Determine if the following identifiers are the same

  1. smly Smly
  2. smly sMly
  3. SMLy smLY
  4. smly1 Smly1

4. The indentation

Indentation is extremely important in Python, just like punctuation when we speak, but not exactly, because indentation is necessary in Python. Indentation is to let the computer know where our code is paragraphing from, and without indentation, the computer won’t know your code and will report an error.

So what is error reporting? It is like your friend’s output of gibberish to you, but you don’t understand. At this time, you will say, I don’t understand, you say that you don’t understand, is error reporting, to your friend, he knows you don’t understand, he will reorganize the language, until you understand.

If you don’t indent your code, the computer doesn’t understand it, and it gives you an error so that you understand it, and it doesn’t understand it, and you modify your code so that the computer understands what you mean.

This process is how we debug our code.

Different codes put together, just like different Chinese characters put together, separate different segments, have different meanings.

And the indentation also has the meaning of inclusion, the same level of code indentation, the lower level of the indentation in order to reduce. (This is not a temporary understanding is ok, will be understood later)

Little practice

# 1. Determine if the following code works
print("Hello")
 print("World")
print("!")
Copy the code

5. Input

We already know the output, print(), what about the input? input()

input(a)print(a)Copy the code

Run it:

It will prompt you to type something here, so what do we do if we want a prompt?

input("Please enter: 1/2, press Enter to end")
print("Input correctly")
Copy the code

Results:

6. The output

So print() is an output function, and you can print out to the console what you want to display in brackets and of course, what you want to display in brackets is double quotation marks, single quotation marks, For example, if you want to say hello, this is what you should say

print ('Hello')
Copy the code

So this is the print () function that prints a string what is a string? The string is what’s inside the English single and double quotation marks like

"Hello World"
"Hello?"
"Hello, beginner."
Copy the code

These are all strings and strings in a computer are kind of what we talk to each other about, strings are things that computers talk to computers, or people who know programming languages talk to computers

7. The variable

What is a variable? As the name suggests, variable quantities.

The strings that we learned before are immutable, and by immutable I mean, what’s stored in memory doesn’t change, it’s not the content.

Because you can do all kinds of things with a string, but it doesn’t change its location in memory, you just copy it and change it again.

It’s like I said a word, you can take it, you can modify it, but it’s not what I said, it’s been copied by you.

So what’s the use of variables? Variables can receive our data and make successive, repeated calls, such as our “Hello World!” This is a very long string, and if we want to use it in many places, we’ll have to write it over and over again, so that’s not a lot of trouble, so we have a variable, and we define a variable to receive this string and use it later, and we can call it directly from the name of the variable.

And that variable name is the identifier we learned about in the last section.

Simple use:

a = "Hello World"
print(a)
Copy the code

The second stage

1.5 Data Types

Data types, that’s what we store data in. What is a data type? That’s the type of data! No offense.

So why do we need data types?

If we need to do some math, let’s say 1 plus 1,1 times 1,1 over 1, et cetera, et cetera

We need numbers, and numbers have decimals, integers, complex numbers. Right

Data types are classified into basic data types and advanced data types.

Basic data types include: int (float), complex (complex), and Boolean

Advanced data types include: string (STR), list (list), set (set), dict (dict), tuple (tuple)

So why are advanced data types called advanced? Because they have additional operations.

For example, add, delete, change, check and so on.

1. Several types

Integers are called integers in Python and are represented by ints, and decimals are represented by floats in Python

Such as:

Int type 1,10,100,1000,10000 float type 1.1 1.11 1.1111

Look at this code

print(100+0.555)
Copy the code

The output is 100.555

The 100 is an int, and 0.555 is a float

2. The Boolean

The Boolean has only two valuesCopy the code

One is True for correct and one is False for error

Just like I tell you 1 > 2 and you say it’s wrong

Computers can think. Look at these two lines of code

print (1>2)
print (1<2)
Copy the code

Running results:

3. The string

A string is just like what we normally say, a string together, called a string, and the characters are one by one

Well, first of all, strings can be iterated over, which means we can use our loop to show all the elements, one by one, and pull them out, and do all sorts of things

Of course, other advanced data types can also be traversed, but the dictionary will be different

Code display:

str_ = "Hello World!"
for i in str_:
    print(i)
Copy the code

Running results:

As you can see, the loop takes our strings apart one by one and prints them out


And then there’s string formatting

What is a formatted string? It just makes our code simpler

Understand by question

How to output a sentence containing variables

Example: Given a variable a = 1, how to output the result: “THE value of a is: 1”

  1. Print (“a = “, a)
  2. Print (“a value: {}”. Format (a))
  3. Print (“a: %d”%a)
  4. Print (f”a = {a}”)

In fact, we can add variables to the string, and the first method is more troublesome when dealing with multiple variables in a string, at this time we need to use the following three, relatively simple, I like the fourth method. Because it’s easy to write


A native string is just a string, and unlike formatting, everything inside a native string quote is a string and is not recognized by the machine as anything else

For example, our escape character \

\t means our TAB \n means newline

So how do you define it? Just add r to the parentheses before the string

So if we look at this code, what does it look like

print(R "Hello \t world")
print(R "Hello \n world")
Copy the code

Running results:

As you can see, our escape character doesn’t do anything, it’s just represented, that’s what our native string does, right

I won’t say more about escape characters. If you know, you can search for them

As for strings, there are more operations, such as how to determine whether a string is a number, how to determine the case, and so on. If you want to know all the operations of searching strings, this article will not cover so much.

List of 4.

Basic understanding of

List the list

A list is a set of data enclosed in brackets such as this [1, 2, 3, 4, 5,] is a list

This is a list of integers between 1 and 5

Accept a list with a variable: li = []

As a high-level data type, lists can be added, deleted, modified, or queried.

Traversal, I’m not going to say it’s the same thing as strings

You don’t have to understand, you just have to know that lists are bags that help us store more stuff.

And we can also use this bag to operate the things inside, such as the above increase, deletion, change and check, is not to put things in the bag, take out the things in the bag, take out the things in the bag to change things, look at the things in the bag


Add data:

Add elements to the list: li.append()

For example:

li = [1.2.3.4]
li.append(5)
print(li) 
Copy the code

Results: [1, 2, 3, 4, 5]

As advanced data types, you can add any data type to the list


Delete data:

Remove the specified element from the list: li.remove()

For example:

li = [1.2.3.4]
li.remove(1)
print(li)
Copy the code

The results are: [2, 3, 4]

I took the “1” out of the bag and put it there.


Find elements:

Find elements:

Lists support element lookup, but with subscript lookup, python subscripts start at 0, and of course strings also support subscript values

For example:

li = [1.2.3.4]
print(li[0])
Copy the code

The result is: 1

Speaking of values in the table below, let’s talk about slices and step sizes

Slice: You can restrict which subscript ranges of data are taken

Step size: the fetch of several elements

Table [subscript: table: step size] 1 indicates that positive values are taken one by one. -1 indicates that positive values are taken backward

Let’s say we just take the elements of 1,3

a = [1.2.3.4.5.6]
print(a[1:3])
[2, 3]
print(a[::2])
[1, 3, 5]
print(a[;;-1])
[6, 5, 4, 3, 2, 1]

Copy the code

Change data:

Again, elements need to be modified with subscripts

For example:

li = [1.2.3.4]
li[0] = 2
print(li)  
Copy the code

The results are: [2, 2, 3, 4]

5. A tuple

Unlike others, tuples are immutable, meaning they cannot be added, modified, or deleted

Tuples use parentheses to define tu = (1, 2, 3, 4)

Elements are separated by commas, just like lists, sets, and dictionaries

You can refer to lists, except that tuples, like collections, cannot be modified, but not because of disorder, tuples can be evaluated by subscripts


Although tuples are immutable, we can simply delete the entire tuple

tu = (1.2.3.4.5)
del tu
print(tu)
Copy the code

The results are :()

6. The dictionary

Why return the dictionary at the end? Because dictionaries are key-value pairs.

Dic = {“key”: value}

Keys must be unique, but values do not.

The value can take any data type, but the key must be immutable, such as string, number.

In the dictionary, access key to get value


Add elements:

We can define an empty dictionary, or we can define an element

And we’ll do some examples

An empty dictionary:

di = {}
di["name"] = "Tom"
di["age"] = 18
print(di)
Copy the code

{“name”: “Tom”, “age”: 18}

Dictionaries with elements:

di = {"name": "Tom"}
di["age"] = 18
print(di)
Copy the code

{“name”: “Tom”, “age”: 18}

This works because our key is unique, so we can add elements this way


Delete element:

Let’s do it with a unique key, and then delete it

di = {"name": "Tom"."age": 18}
del di["age"]
print(di)
Copy the code

Result: {“name”: “Tom”}


Modify elements:

Reassignment via keys to modify elements, which I won’t explain or demonstrate


Find elements:

You can’t find elements by subscript, you need to get them by key

di = {"name": "Tom"."age": 18}
print(di["name"])
Copy the code

Result: “Tom”

Collection of 7.

Sets: Sets are unordered, and unrepeatable unordered: there is no order

It is possible to create an empty set, but not s = {}.

Because this is defining an empty dictionary, we should do set of s.

Format (look) :

s = {1, 2, 3, 4, 5}


Add elements:

Add element s.dd ()ands.update() to collection

s = {1.2.3.4.5}
s.add(6) 
s.upadte(7)
print(s)
Copy the code

{1, 2, 3, 4, 5, 6, 7}


Delete data:

s = {1.2.3.4.5}
s.remove(1)
print(s)
Copy the code

{2, 3, 4, 5, 6}

Delete all: s.clear()


Modify elements:

This feature is not available because elements are unordered and cannot be found or modified by subscript

It’s okay because you use lists and dictionaries a lot in your program

8. Type conversion

What are type conversions? Literally, the data type has changed.

Type casting is divided into automatic type casting and cast casting.

In our example above, 100+0.555

One is an integer, one is a floating-point, and their result is a floating-point, and that’s when the conversion happens.

Sometimes, we need to cast, because sometimes certain data types do not meet our needs, we need to cast.

Python provides functions for casting (like the print() function) that support casting

The function name is the name of the data type, just a pair of extra semicolons, put the data that needs to be converted in parentheses, and it will do

For example: we want to convert other data to a string (almost any data can be converted to a string)

Type conversion
a = 1
b = 1.1
c = 1+1j
d = "ss"
print(str(a))
print(str(b))
print(str(c))
print(str(d))
Copy the code

Running results:

1.6 the operator

When we use Python, we also need to perform operations, so we introduced operators

1. Arithmetic operators

It’s basically the same thing as in math

symbol role symbol role
+ add Subtracting the
* multiply / division
% Take more than ** chengfang

For example,

print(1+1-2*5/2%5**2)
Copy the code

Don’t bother, just do the math

Notice the order of operations

The answer is:

3.0
Copy the code

2. The assignment operator

Think of the variable we just mentioned, the auxiliary operator =

+= *= /=….

A plus 1 is the same thing as a plus 1

Other analogies will do

3. Bit operators

Bitwise operator, bitwise operation

Bitwise operators are binary operators and only work with int, short, byte, long, and char. Operators have, &, |, < <, > >, < < <, ^ ~

  1. & If the corresponding bits are both 1, the result is 1, otherwise 0
  2. | if the corresponding bit is 0 the result is 0, or 1
  3. ^ The result is 0 if the corresponding bits have the same value, 1 otherwise
  4. The ~ bitwise reverses each bit of the operand, that is, 0 becomes 1,1 becomes 0
  5. << bitwise left shift operator. The left operand moves the right operand by bits to the left
  6. >> Bitwise right shift operator. The left operand moves right by bit to the number of digits specified by the right operand
  7. >>> The bitwise right shift zeroing operator. The value of the left-hand operand moves to the right by the number of digits specified in the right-hand operand, and the resulting space is filled with zeros. So I don’t understand deeply enough, please forgive me

4. Compare operators

As the name implies, it calculates the relationship between the two of you. The relational operators are: ==,! =, >, <, <=, >= are all English symbols. Note that relational operators are binocular operators and return Boolean values true/false

  1. == is used in the same way that = is used in mathematics. For example, if you see someone write 1 = 2, you automatically know that it is wrong. Similarly, if you write 1 == 2 in Java, the computer knows that it is wrong and will tell you false
  2. ! = is not equal to the same thing as ≠\neq= in mathematics. For example, if you see 1 ≠\neq= 2, you will say, that’s right. Similarly, you show the computer 1! =2, and the computer will tell you that’s true, true.
  3. The following is greater than or equal to, greater than or equal to, less than or equal to, and mathematics in the same, presumably attended primary school, will not understand it – laugh
symbol role
= = Equal – Whether the objects are equal
! = Not equal – Compares whether two objects are not equal
> Greater than – Returns whether x is greater than y
< Less than – Returns whether x is less than y. All comparison operators return 1 for true and 0 for false. This is equivalent to the special variables True and False respectively. Note that the variable names are capitalized.
> = Greater than or equal to – Returns whether x is greater than or equal to y.
< = Less than or equal to – Returns whether x is less than or equal to y.

The output is Boolean data, that is, either True or Flase

5. Logical operators

If there are operators, how can there be no and or not? Three operators: and, or, and!

  1. I have a girlfriend and you have a girlfriend, so everybody is happy. As long as I don’t have a girlfriend or you don’t have a girlfriend, it’s not everybody’s happy, but if we both have a girlfriend, it’s everybody’s happy
  2. Everyone is happy as long as one of us has a girlfriend
  3. ! This time neither of us has a girlfriend, so everyone is happy. Why is it weird?

The third stage

1.7 Branch Control Statements

So what is a branch control statement? I’m sure you all know about flow diagrams in mathematics.

What? Have not seen? That’s okay. I’ll show you!

This is what a flow chart in mathematics looks like

So what does our branch control statement have to do with this thing?

It’s almost the same thing.

Branch control statements are divided into conditional control statements and loop control statements.

“You can use it a few times.” “You can use it a few times.

If you have any doubts, you must, because you have a vague idea in your head.

Then follow me to take you to understand in detail!


Conditional control statements, which execute our code by judging conditions, are like yes and no in a mathematical flowchart.


1. Single if statement

Let’s look at the format first:

ifCondition: codeCopy the code

This is translated into Chinese

If the condition is true:

Execute the code

The end of the

If the condition is false

The end of the


That’s the process

2. Easy to use

So let’s look at a little example

a = int(input("Please enter an integer"))
b = int(input("Please enter an integer"))
c = a+b
if c<10:
    print("The sum of the two numbers is less than 10.")
Copy the code

Let’s see what it looks like in action

Got it? Isn’t that easy? Yeah, that’s what conditional control does, but that’s just the simplest conditional control, so let’s look at a little bit more complicated.

3. Multiple judgments

Format:

ifCondition: codeelifCondition: codeelseCode:Copy the code

Use:

Continue with the example above

a = int(input("Please enter an integer"))
b = int(input("Please enter an integer"))
c = a+b
if c<10:
    print("The sum of the two numbers is less than 10.")
elif c==10:
    print("The sum of the two numbers equals 10.")
else:
    print("The sum of the two numbers is greater than 10.")
Copy the code

Okay, okay, our program can do a lot more

Let’s just put in a 5 and a 6 this time

Oak, it’s the perfect implementation of our function

1.8 Loop control statements

Cycle, cycle, what is cycle, is always going on, never stop

So how do you stop? We have to set our own terms

There are two types of loop control statements, a for loop and a while loop.


1. The for loop

Format:

In general, the for loop is used a lot

forTemporary variableinConditions for the loop: codeCopy the code

Our for loop needs a temporary variable. There is no need to define a variable in advance to receive the value inside the loop

This also frees memory. If you define a variable in advance, which is a global variable, it will always use memory, and the temporary variable in the for loop will be destroyed at the end of the loop, freeing memory.

In plain English, temporary variables can only live until the beginning of the loop to the end of the loop, and at the end of the loop the temporary variable dies.

And our for doesn’t require us to manually update variables

Use:

Remember at the end of the last variable, we used 10 print() functions to print Hello World 10 times?

So we can also do this with our loop, with less code

a = "Hello World!"
for i in range(10) :print(a)
Copy the code

The I in this code starts at 0, and the values in this range() function are from I to 10 (no 10), so it loops 10 times

Let’s run it

Perfect. That’s what we wanted


2. The while loop

Format:

whileCondition: codeCopy the code

Use:

Again, 10 times Hello World!

a = "Hello World!"
i = 0
while i<10:
    print(a)
    i+=1
Copy the code

The while loop not only defines the global variable, but also requires us to manually update the value of the variable ourselves (I)

If you don’t update, the value of I will not change, the condition will always be true, and the loop will never stop, so when you use while, don’t forget to update the variable

3. End of active cycle

Three statements can stop the loop: break return continue

A return is usually a function that uses a break

Continue is not used to terminate a loop, as shown in the following code example


Break:

Look at the Chinese also have a general idea: break

Its function is to break the cycle so that the cycle stops when it hits it

Break breaks the structure, causing the program to exit the current code block

In this example, what we want to do is loop through the data that the user enters from the keyboard until q is entered to launch the program

while True:
    a = input(a)if a == "q":
        break
    else:
        print(a + "Entered successfully, enter 'q' to exit the program.")
Copy the code

Running results:

At this point, we find that the input Q comes out, but we are not comfortable with it, we can also add a hint, or ask him to enter “confirm” again to confirm whether to come out

while True:
    a = input(a)if a == "q":
        print("Sure to push exit, if yes, please enter OK exit to confirm.")
        if input() = ="Definitely out":
            print("Exit, program terminated.")
        break
    else:
        print(a + "Entered successfully, enter 'q' to exit the program.")
        
Copy the code

Running results:

This is perfect, I this is not who words ah, I this is obsessive-compulsive (serious face)!


The continue:

“Continue” is to break out of the current loop and execute the next loop, that is, it does not have the ability to terminate the loop, it can only make the loop loop fewer times

Let’s try changing break to continue in the code above

while True:
    a = input(a)if a == "q":
        print("Sure to push exit, if yes, please enter OK exit to confirm.")
        if input() = ="Definitely out":
            print("Exit, program terminated.")
        
    else:
        print(a + "Entered successfully, enter 'q' to exit the program.")
        
Copy the code

It won’t work

Can’t quit!

Sure enough, what does continue do?

I don’t say, you see:

for i in range(10) :if i % 5= =0:
        continue
    else:
        print(i)  
Copy the code

Running results:


Return:

Return means to return, and is used to return a value in a function, which we’ll cover in more detail in this column

We calculate that when I goes up to 5, we let a+b, and then we terminate

When I is 5, the loop is forcibly terminated regardless of whether it has finished

def sum(a, b) :
    for i in range(10) :if i<a:
            pass
        else:
            a+=b
            return a
print(sum(5.2))
Copy the code

Pass means do nothing, right

The result is 7

So what if we change the return position?

def sum(a, b) :
    for i in range(10) :if i<a:
            pass
        else:
            a+=b
        return a
print(sum(5.2))
Copy the code

Our loop is going to terminate the first time, because the first time I is zero, we’re going to execute a return statement, we’re going to terminate the loop

So what if we switch again? I’m going to put it outside of the loop, so I’m going to finish the loop, and I’m going to do a+=b once, again 7

def sum(a, b) :
    for i in range(10) :if i<a:
            pass
        else:
            a+=b
    return a
print(sum(5.2))
Copy the code

The fourth stage

1.9 Functional programming

Not to be confused with functions in math

So what exactly is a function?

A function is basically when we need a lot of duplicate code blocks in a program, we wrap it up into a block of code, which is represented by a name, and that name is an identifier. Rules for identifiers need to be followed.

The advantage of functions is to avoid code duplication and improve development efficiency.

For example, we need to ask the computer to tell us a love story, like this one

"I love you."
"I'm gonna give you monkeys."
"Ahhhh, I love you."
Copy the code

Print () one by one

But what do I need you to tell me whenever?

I’m afraid I’m not going to use a loop at this point, but I’m going to use our function

Of course, Python comes with many built-in functions, and the ones we define ourselves are called custom functions.


1. No-parameter function:

Parameterless functions are the most basic functions, and are rarely used, just to practice understanding functions.

defFunction name ():codeCopy the code

Use:

# define
def Qinghua() :
    print("I love you.")
    print("I'm gonna give you monkeys.")
    print("Ahhhh, I love you.")
# call
Qinghua()
Copy the code

Running results:

It doesn’t seem to make much difference!

It’s not. Look at this

# define
def Qinghua() :
    print("I love you.")
    print("I'm gonna give you monkeys.")
    print("Ahhhh, I love you.")
# call
Qinghua()
for i in range(10) :print("After {} seconds".format(i))
    Qinghua()
Copy the code

It can be invoked whenever you want, without requiring you to call it again.

It’s like a variable, but it’s a little bit more complicated than a normal variable


2. Parameterized functions

Functions can pass parameters, and parameters are divided into parameters and arguments

A parameter is a formal parameter, just like a company has employee, cleaner, president, etc., but some positions are empty. These vacant positions are equivalent to a parameter, and the person who can play the role of the position is called an argument (actual parameter).

And when we define a function with parameters, we need to define parameters to represent our function, and with these things, if you want our function to work, you need to pass us the actual parameters.

There are arguments, there are arguments, where are there arguments?

When we define, we need to define parameters inside parentheses to receive parameters

When we call, we pass the arguments in parentheses after the function name

Use:

We’re going to define a parameter function to concatenate the two parameters and iterate over them

def PinJie(a, b) :
    str_ = str(a)+str(b)
    print(str_)
    for i in str_:
        print(i)

PinJie("sasa".4564)
You could also write # this way
"" PinJie(a="sasa",b= 'sasa') (a="sasa",b= 'sasa') (a="sasa",b= 'sasa')
Copy the code

Run:

3. The role of return

As mentioned earlier, return is usually used in functions, so what does it do?

First according to the name of the law to understand: return

Indeed, his job is to return, return value

Return XXX (” XXX “) return XXX (” XXX “) As we all know, XXX can be anything!

So where does the returned value go? When the function is called, the function name (argument) is the value returned

Use:

Look at the function above, which displays the concatenated result using the print() function (built-in)

So let’s try return

def PinJie(a, b) :
    str_ = str(a)+str(b)
    return str_
    for i in str_:
        print(i)

PinJie("sasa".4564)
Copy the code

So what happens?

The answer is, nothing!

Why is that? Because we didn’t use the print() function (nonsense, that’s not there!)

Why do you say that? Because we saw last time that a return is used to end a piece of code, and if we return in the middle, the lecture doesn’t get executed, it just ends.

How do I show the loop? Put return at the bottom of the function, I will not show, to try their own, or the advantage of water words! (Save your life!)

The return value is received by the function name ()**, so it is now a value. If you want to display it, you have to print().

def PinJie(a, b) :
    str_ = str(a)+str(b)
    return str_
    for i in str_:
        print(i)

p = PinJie("sasa".4564)
print(p)
Copy the code

Results:

It shows the return value, which is the result of the concatenation of functions

1.10 Object-oriented programming

The fifth stage

1. Understand

There are object-oriented (Java, Python) and procedural (C) programming languages, and object-oriented requires some abstract thinking.

What’s the difference between procedural and object oriented?

Process oriented focus on hands-on, which means to do it yourself; Object oriented people tend to find people to do things for them.

Take the well-worn example of doing laundry:

Process-oriented:

Process-oriented laundry is:

  1. Take your clothes to the washing machine
  2. Put it in
  3. Waiting for the
  4. Scoop out

The next time you do laundry, you have to do it all over again

And that’s functional programming

Object-oriented:

Object oriented is:

  1. Create a robot
  2. Teach him how to wash clothes
    1. Take your clothes to the washing machine
    2. Put it in
    3. Waiting for the
    4. Scoop out
  3. Put him to work

The next time you need to do laundry, just let the robot do it

The thing that object orientation can’t get around is classes and objects, so read on

Class 2.

A class is an abstract thing, such as a human, an animal, or a plant. A class is a collection of things that share some of the same characteristics

So how do we define a class that belongs to us? There are three methods, and the third is recommended

# define a Xxx class
class Xxx:The code blockclass Xxx() :The code blockclass Xxx(object) :codeCopy the code

This is a

Classes need to have properties, behaviors (methods) and so on

Properties are local variables inside a class

And the behavior is the function defined in the class

Construction method:

And every class has some default behavior (methods), such as this constructor __init__

Every class has this constructor by default, and the contents of the constructor are run at instantiation time, that is, when you instantiate, the __init__ constructor is called.

And what is the object?

3. The object

An object is an instantiation of a class, and in the case of a human, a human is a class, and each of us is an instantiation of that class.

Look at the code:

# Define a human being
class Person(object) :
    pass

Instantiate the object
xiaoming = Person()
Copy the code

In this case, the name of the object is “Person” and the name of the object is “Person”

4 code to achieve the washing machine

Code:

class Robot(object) :

    def __init__(self) :
        print("Take your clothes to the washing machine.")
        print("Put your clothes in the washing machine.")
        print("When the laundry is done.")
        print("Fish out the clothes.")

        
xiaoming = Robot()
Copy the code

Running results:

5. Packaging

Constructor parameters can be wrapped so that they can be called in each method

It would be wrong to think of such code

class Person(object) :

 def __init__(self, name, age) :
     pass
 
 def speak(self) :
     print(f"{age}At the age of{name}Will talk")

Menger = Person("Cloth Little Zen".20)
name = Menger.name
age = Menger.age
person.speak()
print("Name: {} \n Age: {}".format(name, age))
Copy the code

Self. Name = name and self. Age = age

class Person(object) :

 def __init__(self, name, age) :
     self.name = name
     self.age = age
 
 def speak(self) :
     print(f"{age}At the age of{name}Will talk")

Menger = Person("Cloth Little Zen".20)
name = Menger.name
age = Menger.age
Menger.speak()
print("Name: {} \n Age: {}".format(name, age))
Copy the code

That’s it. The output is:

Name: Bu Xiaochan

Age: 20

6. Inheritance

Python object orientation can be inherited, just as you inherit some of the characteristics of your father and your mother. In Python, subclasses inherit from superclasses. Speaking of inheritance, you’ve all seen the third of the three ways I defined classes in my last article:

class ClassNmae(object) :The code blockCopy the code

The object in parentheses after ClassNmae is the parent class, and ClassName is the subclass

A subclass inherits everything from its parent class

Privatization of 7.

In the previous article, we talked about encapsulation, which means that we don’t want others to see the content of the code, but we need to use the content, through internal class calls to implement the call.

Speaking of which, I have to mention the previous article:

class Person(object) :
    def __init__(self, name, age) :
        self.xxx = name
        self.xxxx = age
        
Copy the code

The name after self in this one, you can name it any way you want, the last one is the same as the last one just for memorization

As long as you remember, it’s okay to be upside down


Attribute privatization:

What is an attribute private?

For example: your private money, your cell phone, your computer secrets, etc. These are things that you don’t want others to know

So what’s the purpose of encapsulation? Isn’t it to hide code that you don’t want anyone to know

So there is a private property, which makes your class properties private, unlike encapsulation in the previous part, which can also be called by instantiating the object; Once this property is private, you can’t call it outside the class

What if I want to use it? Call it inside a class!

All right, so I’m sure you’re getting tired of this, so code up

Use format:

class Xxx(object) :
    age = 20
    _name = "Xxx"
Copy the code

Such attributes, preceded by an underscore, are private and cannot be called by methods that instantiate objects outside the class

Specific application:

""" Define a pretty human with name, age, weight, height privatized weight Settings by class internal calls so that you can see your weight outside the class ""
class Person(object) :
    _weight = 70
    def __init__(self, name, age, height) :
        self.name = name
        self.age = age
        self.height = height
 
    def weightPrint(self) :
        print("My weight is:", self._weight)

person = Person("Cloth Little Zen".20.180)
person.weightPrint()

Copy the code

The weight cannot be called by person.weight, person._weight, because the property is private

* * method