Introduction to Python Basics Lesson 3--Overview of Variables and Functions

    From now on, we will start to learn the basics of Python. I remember that there is a book about databases called "SQL Must Know and Know". It is very thin but the content is very substantial. I have read it at least three times. I also dare to call ours "Python must know" here.

Note: The python code generated in the HTML/XML editor will have a tag language similar to <span style= "color:#333333;" >, this part is not in the code, please ignore it automatically.

1. Variables

    As we all know, python evolved from the C language, so its variables are basically the same as those of the C language. We commonly use global variables, local variables, static variables, and instance variables.

   1. Global variables

       In general, the function directly calls the global variable, if there is no operation on the global variable, there is no problem. But if there is an update operation, but it is not declared in the function body, it is equivalent to creating a local variable with the same name as the global variable in the function body. Questions will come up that will surprise you.

Remember: local variables take precedence over global variables.

Example:

#coding:utf-8
#author:youzi
all_var="Hello World!" #Global variable declaration
def Test():
   global all_var #global tells the function body that this is a global variable
   print all_var #print variables
Test()
print all_var

Another Example(Error):

#coding:utf-8
#author:youzi
all_var=8 #Global variable declaration
def Test():
   all_var=0 #Modify the value of the variable, but not declare it as a global variable
   print all_var #print variables
Test()
print all_var

Test the above two codes by yourself, and experience the scope of a global variable. You will have some initial feelings.

   2. Local variables

A little cute in the function body can only work in the function body, and there is no cute attribute when it goes out.

Example: 

#coding:utf-8
#author:youzi
def Cute():
  name="youzi"
  print name
Cute()

   3. Static variables and instance variables

The concepts of static variables and instance variables are better described in classes. Please see the following code first (just focus on the red and blue parts):

class Province(object): #Create a class named Province
    memo='One of the 23 provinces in China' #Static field
    #Instance
    def __init__(self,name,captial,leader,flag):#方法
        self.Name=name
        self.Captial=captial
        self.Leader=leader#dynamic field
        self.__Thailand=flag#Private field
#dynamic method
    def sports_meet(self):
        return self.Name + 'a sports meeting is being held'
#Change dynamic method to static method
    @staticmethod
    def Foo():
        print('The province should take the lead in fighting corruption')
#Change dynamic methods to properties
    @property
    def Bar(self):
        print(self.Name)
    #Use dynamic methods to call private fields read-only
    @property
    def Thailand(self):
        return self.__Thailand
    @ Thailand.setter
    def Thailand(self,value):
        self.__Thailand=value

hb=Province('Hebei','Shijiazhuang','Li Yang','True')
sd=Province('Shandong','Jinan','Wang Shenghui','False')
japan=Province('Japan','Okinawa','Aoi','True')

print(hb.Captial)#Object can access dynamic fields
print(Province.memo)#class can access static fields
print(sd.memo)#Object can also access static fields
print(sd.Name)#Object can access dynamic fields
print(hb.sports_meet())#Object can access dynamic methods
print(sd.sports_meet())#Object can access dynamic methods
Province.Foo()# class can access static methods
hb.Bar#feature access
print(japan.Thailand)#read-only feature access
japan.Thailand=False
print(japan.Thailand)

    First, we create a class named Province, and inside this class we can initialize any province we want. And perform some corresponding operations to achieve their own needs.

    Second, a static field created by memo for us also becomes a static variable. And sd is an object we create to instantiate the Province class, why instantiate the Province class and create an object? In order to realize the idea of ​​object-oriented programming, we write some very practical methods in order to call the class. As you can see in the printing part that follows, the static field memo belongs to the class Province and the object sd. That is to say, we can call it through classes and objects.

    Finally, we focus on the content of the blue part, we call it a dynamic field, and use the self parameter in the initialization function to call it, self.Leader, which is also what we often call instance variables. Instance variables belong to objects, and dynamic fields can be called through objects, that is, instance variables. For static fields or static variables, there is no such thing as self.static fields, and at the same time, classes cannot call dynamic fields. Note in particular that an Attribute Error will be thrown if called like this.

   4.Summary

    In the process of writing code, the processing of variables is generally divided into two cases: public and private. Don't share it with other parts, just enjoy it yourself. Just like the exclusive lock in the database, the local variables of a function body, the dynamic fields or instance variables of a concrete class are all private and not shared. Shared in a certain scope and domain to achieve synchronization purposes, shared global variables, static fields or static variables shared between parent classes and subclasses, etc.

    In the programming to achieve a specific function, the classification of specific variables is very important, and to some extent reflects your mastery of this function and your understanding of the design of the code structure. In conclusion, don't overlook every step of implementing functional programming.

2. Function

    Functions are like small programs that can be used to implement specific functions. Python has many functions that can do many wonderful things. You can also customize functions. Therefore, we usually turn standard functions such as pow into built-in functions, and turn user-written functions into third-party functions or custom functions. In short, functions with corresponding names cannot be found in the standard library.

   1. Define the function

    Creating a function is the key to organizing a program, so how do you define a function? Just use the def (or "function definition") statement.

def hello(name):
   return 'Hello.' + name + '!'
print hello('World')
print hello('Youzi')

    Running this program will get a function named hello, which can return a greeting statement with the input parameter as the name. You can use it like a built-in function, give the corresponding parameters, and print the output. Print is One of the most basic Python built-in functions. Let's look at another example:

def fibs(num):
  result=[0,1]
  for i in range(num-2):
     result.append(result[-2]+result[-1])
   return result

    I believe everyone is familiar with this example. This is a typical Fibonacci sequence processing algorithm. After executing this statement, the editor knows how to calculate the Fibonacci sequence, so basically you don’t need to pay attention to Sister Xie now. , just use the function fibs. Pay attention to the little thing pass.

def no():
   pass

    The pass statement is nothing to do, nothing to process. In fact, it can only be used as a placeholder. If you write a specific function, the specific function of the function is related to the context, and you have not yet figured out how to write it. You can fill in the pass without affecting the execution of the program. Pass can also be used in the following small details.

if time_of_study >=24:
      pass

    Combining work and rest is the best way to study, the study time is more than 24 hours, emmmmm.... rest, do nothing, do nothing. But it cannot be empty, otherwise a syntax error will occur.

   2. Call the function

The function call is actually very easy to understand, especially for the functions in the standard library. Just look at a few examples.

>>>from math import sqrt
>>>sqrt(9)
3.0
>>>sqrt(9,10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sqrt() takes exactly one argument (2 given)

    The above program is executed in the shell, and sqrt, the standard square root function, is imported from the math library. First execute the correct parameter input to get the correct result, then pass in the wrong parameter, that is, the wrong call, the interpreter will tell you that there is a TypeError, the sqrt() function has only one parameter, and you passed in two .

    The following are also some commonly used function calls, familiar with them:

>>>int('1234567')
1234567
>>>str(1234567)
'1234567'
>>>bool('1')
True
>>>bool('')
False
>>>float(1)
1.0

    This part of the function will introduce so much first, and later we will introduce the combination of recursion, function and dictionary, list, class, etc. And some wonderful built-in functions in the standard library.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325776329&siteId=291194637