Python hard to understand? Buy a watermelon once and you'll get it!


What is it?code?

Code would be a language, a language that computers can read. The computer is a dumb*ss who can't understand anything that defaults to two. For example, if you ask your husband to go buy a watermelon, your husband will decide on his own where to buy it, how many to buy, find one that is on sale, in short, you pay him and he will buy you back a watermelon that will make you feel good. But you want the computer to buy a watermelon? You have to tell him: go to the fresh and plentiful fruit shop at the entrance and buy sand-fleshed seedless watermelon, if the shop next to it is on sale. In short, you can't let the computer make any decisions, and you need to clearly tell him all the behaviors in all situations. Code, on the other hand, is the language you use to communicate with the computer, or commands to the computer.

Let's just understand a computer as a person, a person who is very rigid and can only follow the detailed commands you give him. And this person works exceptionally, exceptionally fast and makes sure that the work turns out all right.

The programming language doesn't really matter, it's important to understand how to communicate with the computer, and once you understand that you'll be able to read the code as well.

program = algorithm + data structure

python is a language that communicates with computers, a language with few words (keywords) and few rules. All of the following is based on python.

1. Judgement

When you command a computer to do something, that something may be processed in a number of situations.

Judgments usually involve keywords such as if , else, elseif, and, or,,=,=, ==

For example, you ask the computer to buy watermelon and expect to get it on sale, and you won't eat it if it's not.

If Fruit Shop Discount:

buy watermelon

else:

No more.

With this command, the computer becomes a little smarter and he can execute your commands depending on the situation.

You can't eat watermelon without a discount at the fruit store, and you're not happy. Well, let's make the computer a little smarter. If the watermelon is on sale, buy the watermelon; if not, let the computer bargain with the owner, who agrees to the discount, buy the watermelon; if not, no more.

If Fruit Shop Discount:

buy watermelon

else:

Bargaining with the owner

if bargaining is successful.

buy watermelon

else:

No more food.

Although bargaining with the owner is usually successful, some owners give a 50% discount and some only give a 10% discount. You just thought, if the owner takes 50% off, I'll buy two and eat one today and one tomorrow. If the owner doesn't give less than 50% off, buy one and eat it today, then tomorrow.

If Fruit Shop Discount:

buy watermelon

else:

Bargaining with the owner

if Discounted Success and Discount Strength

Buy two watermelons.

elseif Discounted Success and Discount Strength > 5:

Buy a watermelon

else:

No more food.

Also, did you notice that the code for hitting success could actually be written as.

if the discount is successful:

if discount strength

Buy two watermelons.

else:

Buy a watermelon

else:

No more food.

As you can see, the computer is not completely static; it can do the job as long as you give it commands that it understands and doesn't default to either.

and means that it represents and,or The meaning of the representative or。and harmonyor in a different order, The results are also different, The priority of the judgment condition can be indicated by brackets。

a==b means to compare whether a and b are equal, while = stands for assignment. The meaning of assignment is covered in the variables section below.

2. Circulation

Keywords in python that involve loops include: for... in...,while,break,continue

In the above example we have made it possible for the computer to successfully go to the fruit store and buy watermelon depending on the situation, but if the owner doesn't give a discount, you won't be able to eat the watermelon. At this point, you're thinking, there are three fruit stores in front of our neighborhood, namely Fresh Fruit, Four Seasons Fruit and Roadside Stall, just because one isn't on sale doesn't mean all three aren't, so you're hoping the computer can go to all three and pick a store that's on sale to buy watermelon.

for Fruit Shops in (Fresh Fruit, Seasonal Fruit and Roadside Stalls):

if Fruit Shop Discount.

buy watermelon

break(end of loop)

else:

Nothing.

Bring home the watermelon.

The point of looping is that the computer can be used to execute the same commands on different objects.

Introducing.break,break means to end the loop。 for example, The code in thisbreak express, Once we bought the watermelon, Then it's... Bring home the watermelon.。

3, variables

Now it's time to introduce the important thing of 'variables'.

We still understand a computer as a person who helps us work, then as a person he needs to have memory, and we can then control and use the memory of the computer through variables.

A variable can be understood as a memory unit of a computer, Computers have an excellent memory, consequently, You can use it as you wish, Use it up and throw it away., If you need it, you need it.。( definitely, It's not strict to say that you can do whatever you want., But you can interpret it as whatever you want.)

So why is it called a variable? It's because it can be changed. Why the change? For example, we all have our ages, I'm 18 this year and I'll be 19 next year. So, 'age' is changed every year in my memory.

The variable corresponds to a thing called a constant, and as far as I can remember, my wife is a fellow student of Jiang Jiang. And this 'wife' as a memory unit will never change in my head, she will always be Jiang Jiang's classmate. Constants you don't have to understand right now, I wrote it mostly for show and tell.

present ., The computer is going to buy watermelon again。 But this time, You want the computer to be able to do three fruit shops in, Find a fruit store with the biggest discount and go buy fruit。

Maximum discount for all previous fruit stores = None

The fruit store that gave the biggest discount before = None

for Fruit Shops in (Fresh Fruit, Seasonal Fruit and Roadside Stalls):

Current fruit store discounts = Discount from the owner

if Current fruit store discounts

Maximum discount for all previous fruit stores = current fruit store discount

The fruit store that gave the biggest discount before = fruit store

go to (a place) The fruit store that gave the biggest discount before Buy a watermelon

These are several memory units:

The largest discount of any fruit store before

The fruit store that gave the biggest discount before

Current fruit store discounts

fruit shop note,for a in b,a It's also a variable, He was in every executionb An element of the current execution in。

Some concepts need to be introduced here.

None means empty in python, indicating that this memory unit has nothing right now. For example, when I was in the beginning of my love life, I already had the memory unit of my lover in my mind, and I was looking for it, but I never found it before I met you, so it was empty inside this memory unit for that time.

Assignment notation: =. Note that inside a computer language, one '=' sign indicates an assignment, and two equal signs '==' indicate a comparison of the elements before and after. Assignment means to take the element that comes after and put it inside the variable that comes before.

Scope of variables

The scope thing is very important, but I really don't want to talk about it because there's no way to incorporate real world examples, but I'll explain it in general terms.

Still with the example from earlier, I added line numbers and I used - for spaces to indicate indentation of the code.

1 Maximum discount for all previous fruit stores = None

2 The fruit store that gave the biggest discount before = None

3 for Fruit Shops in (Fresh Fruit, Seasonal Fruit and Roadside Stalls):

4 --- Current fruit store discounts = Discount from the owner

5 ---if current fruit store discount

6 ------ Maximum discount for all previous fruit stores = current fruit store discount

7 --- fruit store that gave the biggest discount before = fruit store

8 go to (a place) The fruit store that gave the biggest discount before Buy a watermelon

You may look at this example and wonder, Why give first’ The largest discount of any fruit store before’、’ The fruit store that gave the biggest discount before’ These two variables are assigned the valuesNone this (Cantonese)。 It's because of the scope issue。

Look at this program., Each line of code is indented differently。 Variable scopes can be understood as: A variable, Only the indent where it first appears, As well as indenting more of the code inside, It's only effective.。 our first1、2 Variables in rows, It can then be used for3-8 go, Because these codes are indented in1、2 Back of the line。 And the fourth line of the variable’ Current fruit store discounts’, only in5、6、7 effective

1 A = None

2 ————B = None

3 ————..

4 ————————C = None

5 ————————..

6 ————D = None

7 ————..

8 ————————..

9 ————————..

10 ..

11 ..

For example, ABCD is a variable,.. Represents some code. The scope of A is lines 1-11, i.e. lines 1-11 can all use A. The scope of B is 2-9 lines, the scope of C is only 4-5 lines, note that 8-9 lines can no longer use C, although his indentation and 4, 5 lines, the scope encountered the first can not use indentation code to end. The scope of D is line 6-9.

4. Functions

By reading the above sections, you should probably understand how computers execute code.

The functions and modules, on the other hand, are not quite the same as the previous presentation. It was previously an introduction to how to make computers work and was computer oriented. And this section, which is human-oriented, is about how to make the code we write for computers look cleaner and clearer. Functions and modules are optimizations of the code structure, otherwise a slightly larger project, a large pile of code, computer-readable people can not read, not conducive to management and communication.

Let's start with the function. A function is a collection of code that is typically used for several reasons:

1.Give a name to a piece of code.

2.This code has little to do with the code that uses it, so it can be pulled out and the code is cleaner when it is pulled out. Not very related means: the code that uses the function executes the function by passing it a few arguments.

3.A collection of codes can then be used in different places in the code.

Still we went to buy watermelon, but we hope the computer can buy another one tomorrow after today's watermelon. The way it was done before, the logic would have been written as follows.

for Fruit Shops in (Fresh Fruit, Seasonal Fruit and Roadside Stalls):

If Fruit Shop Discount:

buy watermelon

else:

Bargaining with the owner

if Discounted Success and Discount Strength

Buy two watermelons.

elseif Discounted Success and Discount Strength > 5:

Buy a watermelon

else:

No more food.

Take a day off.

for Fruit Shops in (Fresh Fruit, Seasonal Fruit and Roadside Stalls):

If Fruit Shop Discount:

buy watermelon

else:

Bargaining with the owner

if Discounted Success and Discount Strength

Buy two watermelons.

elseif Discounted Success and Discount Strength > 5:

Buy a watermelon

else:

No more food.

The code above does what we want, but the code for buying watermelons is actually duplicated, and for duplicate code, it's tricky to manage, like if you want to change a little bit, then you have to go to each place and change it once.

or so, Let's make the code for buying watermelons a function, The code can then be organized as:

def buy_watermelon_function():

for Fruit Shops in (Fresh Fruit, Seasonal Fruit and Roadside Stalls):

If Fruit Shop Discount:

buy watermelon

else:

Bargaining with the owner

if Discounted Success and Discount Strength

Buy two watermelons.

elseif Discounted Success and Discount Strength > 5:

Buy a watermelon

else:

No more food.

Buy Watermelon-Function ()

Take a day off.

Buy Watermelon-Function ()

This time, the code is much neater, and, every time we want to change the code for buying watermelon, we only need to change this function one place code are available.

In python, use the def function_name (): defines a function, and all indentations below the function belong to the function, called the function body.

Use function_name() to call the function.

4.1 Function parameters

Now you're not satisfied with a computer that only buys watermelons, You want grapefruit again.。 What to do?, So are we going to write another function to buy grapefruit。

Of course, you can write another function to buy grapefruit, but the logic of buying grapefruit function and buy watermelon function logic are the same, the command is the same, the only difference is that before is to sell watermelon, now buy grapefruit. If you write a similar function to buy grapefruit, then there is just said the problem, every time you modify the logic of buying fruit, you need to modify the purchase of watermelon, buy grapefruit function, if grapefruit is tired, but also to buy bananas, apples, pears, is not to write a very many functions?

To solve this problem, Actually, there's a better way., is the use of function parameters。

Since we buy fruit (either watermelon, or grapefruit) the function is the same, so we can write a buy fruit function, the buy fruit function defines the process of buying a fruit, when we use this function, we just tell the function what fruit we want to buy, the function can go and buy the corresponding fruit according to the name of the fruit you tell him.

The code for the Buy Fruit function is as follows:

def Buy fruit function( fruit name):

for Fruit Shops in (Fresh Fruit, Seasonal Fruit and Roadside Stalls):

If Fruit Shop Discount:

Buy [fruit name]

else:

Bargaining with the owner

if Discounted Success and Discount Strength

Buy two.

elseif Discounted Success and Discount Strength > 5:

Buy a [fruit name]

else:

No more food.

Buy fruit function (watermelon) # Let the computer go buy watermelon

Buy fruit function (grapefruit) # Let the computer go buy grapefruit

To use function arguments in python, you just need to add the argument inside the parentheses when the function is defined, which in our case is the 'fruit name'. The code in the function body can use function parameters.

When a function is called, write a variable or constant in parentheses after the function name and pass it on to the function.

Note that if there are multiple arguments, the function definition and the order of the arguments to the calling function must be the same.

In python, there are also slightly more advanced uses of default arguments, keyword arguments, etc., to give an example without going into detail.

def sum(a, b = 0,c = 1):#b/c is the default parameter

return a+b+c

func(1,0,1)

func(1)

func(1,c=1)

All three of these func calls result in the same thing.

5. Modules

We have just talked about the function, A function is code that puts together。 And the module, It's all about putting more code together。

Modules and functions were introduced to solve a similar problem: Manage code segments, And give them a name.。

Generally speaking, a module is a py file, which may include many functions, and may also include some class definitions (we'll talk about this later).

Modules were introduced to make the code better managed.

We put the code in apy file, this onepy A file is a module, in otherpy Inside the file, We can then use theimport Keywords., Bringing modules into。

For example, we now have an a.py file with some functions like buy_xigua, buy_youzi, etc. If we want to use these functions in the b file, then we must import the a module before we can use it.

There are many ways to import a module and use the functions inside it, and I list common methods below.

Method I.

import a

a.buy_xigua()

a.buy_youzi()

This method imports module a and then passes module . The function calls the function.

Method II.

from a import *

buy_xigua()

buy_youzi()

This way you import everything in module a and can be used directly.

Method three.

from a import buy_xigua,buy_youzi

buy_xigua()

buy_youzi()

This way of importing modulesa Specified content in, Can be used directly, Generally this method is used more in the software development process, The reason is that we only import what we need to use, Unwanted not imported。( Use as needed, don't waste, It's a good habit everywhere., Deeper reasons beyond the tutorial)

6. Classes and objects

The concept of classes and objects may be slightly difficult to understand for students who have not been exposed to programming. I remember first encountering the concept back then and being confused for a while.

prior to, We have introduced‘ variable’。 Introduction of variables, is to describe the memory unit within the program。 A variable can be a number, It can also be a string( For example, setting a variable name=' water wind')。

However, some things need to be described using many variables together in order to work. For example, a man who buys watermelons. There are many characteristics of a watermelon buyer, such as: name, deposit, number of watermelons held. In addition, there are some behaviors of people who buy watermelons, such as the act of buying watermelons. In order to implement the function of a watermelon buyer, we introduce the concept of classes and objects. Note that the problem that the class/object introduces wants to solve is not the same as the problem solved by the function or module. Functions and modules were introduced more to manage code, while classes/objects were introduced to encapsulate state and behavior together.

So, what do classes and objects mean respectively. Classes are what states and behaviors we define for a kind of thing, for example, people who buy watermelons have states and behaviors, we define them in advance, the concept of class is a kind of virtual. And an object is an entity that the code goes on to create and generate dynamically during its execution.

Like the watermelon buyer.

We wrote about the process of buying watermelons earlier, Now we want to create two watermelon buyers, Each person is responsible for one day, That way the watermelon buyers can rest too。

Source: Code Bay

Highlights


Recommended>>
1、Can parking early to know Taiyuan began to move into the era of intelligent parking
2、When the Oracle database is unmounted
3、Kudos The worlds first driverless train enters a mine taking stock of two major breakthroughs in smart mining in 2017
4、SpringBoot integration with Kafka
5、ARCBLOCK Block Cornerstone

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号