Summary of Python basic syntax knowledge points

Keywords: Python Pycharm

Python learning notes

1. The first phthon program

print("Hello World!");

2. Basic grammar knowledge

2.1 notes

# Single line note content

"""
Multiline comment content
"""

print("Two representations of annotations");

2.2 prompt information in phcharm

  • Gray wavy line: indicates irregular writing
  • Green wavy line: indicates that there may be a problem with word spelling
  • Red wavy line: syntax check

2.3 arithmetic operation

Except for +, -, *,% which are the same as other languages at ordinary times:

  • /Indicates division (no rounding)
  • //Indicates division
  • **Represents a power operation
print(10 / 3);
print(10 // 3);
print(2 ** 4);

Operation result:

3.3333333333333335
3
16

Among them, multiplication has the highest priority and + and - have the lowest priority. However, we can use () to improve the priority of operation and the order of operation

2.4 variables

  • It can only be composed of numbers, letters and underscores
  • Cannot start with a number
  • Cannot be a keyword
  • Case sensitive
a = 10;   //Directly define variables
print(a);

The types of variables are divided into numerical type and non numerical type, in which:

Numeric types include: int, float, bool, etc

Non numeric types include: str string, etc

We can use type (variable name) to get which type the variable belongs to

t = 10;
print(type(t));
t = 15.6;
print(type(t));
t = True;
print(type(t));
t = "tmx520";
print(type(t));

Output results:

<class 'int'>
<class 'float'>
<class 'bool'>
<class 'str'>

2.5 string operation

  • Unlike Java, strings can only be connected with strings, not with other types (for example, int type), that is, use + to add
  • A string can be concatenated with a number using * to indicate that the string is concatenated repeatedly
a = "feng";
print(a * 5);

Output results:

fengfengfengfengfeng

2.6 standard input

Use * * input() * * to receive the information entered by the user. When the input() operation is executed, the program will wait for the user's input instead of executing downward

There are two ways:

# Method 1: without prompt
name = input();
print(name);

# Mode 2: with prompt information
name = input("Please enter your name:");
print(name)

Test:

feng
feng
 Please enter your name: feng
feng

matters needing attention:

  • The data obtained by using the input operation is of string str type
  • We can use int(), float() to convert the format, but note that int type can be converted to float type, but float type cannot be converted to int type

2.7 formatted output

Syntax format:

  • print (variable)
  • print ("format string"% variable)
  • print ("format string"% (variable 1, variable 2,..., variable n))

Where placeholder:

placeholder effect
%scharacter string
%dinteger
%6dInteger, number is used to set the number of digits (minimum value), and fill in blank if it is insufficient
%fFloating point number

Case: area of circle with input and output

pi = 3.14;
r = float(input("Please enter the radius of the circle:"));
area = pi * r ** 2;
print("The area of the circle is:%f" % area);

Output results:

Please enter the radius of the circle: 3
 The area of the circle is: 28.260000

2.8 string comparison operation

Character comparison operation sorting table:

  • 0... Number... 9 < a... Upper case letter... z < a... Lower case letter... z

2.9 relational operators

Relational operators are divided into and, or and not

Numbers can be used as Boolean expressions:

  • A number other than 0 indicates True
  • 0 means False

2.10 conditional statements

Code format:

if Condition 1:
    Execute code
else if Condition 2:
    Execute code
else:
    Execute code

2.11 circular statements

Code format:

for Variable name in array/character string/aggregate
	code

Test case:

# The for loop prints 1-10, where range(n) represents generating a continuous integer from 0 to n - 1
for i in range(10):
    print(i + 1);

# Traverse every character of the print str string
str = "abcdefg";
for ch in str:
    print(ch);

while loop code format:

while condition:
    Loop internal code block

2.12 functions

Definition of function:

def Function name():
    Function body

Note: the function must be called after the function definition!!!

In pyCharm, you can use F8 to directly execute large steps, and F7 to enter internal small steps

2.13 function document notes

We use multi line comments in the function to describe the content of the function

2.14 functions with parameters

def Function name(parameter):
    Function body content
 Use directly when calling a function: Function name(parameter)

2.15 scope of function variable

  • Local variable: the variables defined inside the function are valid from the definition position to the end of the function definition

  • Global variables: variables defined outside the function are valid throughout the file

  • Internally defined variables cannot be shared between functions

  • Global variables can be used inside functions

  • Note: if a local variable conflicts with a global variable, we can use the global keyword to promote the local variable to a global variable, but we need to declare it before using it

2.16 function definition -- with return value

def Function name(parameter list):
	Function body
    # Just add the return value statement here
    return The value that the function needs to return

2.17 case: find the maximum of three numbers

# Enter three numbers
x = int(input("please enter a number x:"));
y = int(input("please enter a number y:"));
z = int(input("please enter a number z:"));


# Function max for finding the maximum of two numbers
def max(a,b):
    if a >= b:
        return a;
    else:
        return b;

max = max(max(x,y),z);
print("x,y,z The maximum value of is: %d" %max);

3. Object oriented

3.1 definition of class

Define format 1:

class Class name:
	pass    

Define format 2:

class Class name:
    member

Among them, pass in format 1 means that the class is empty and there is nothing!!!

3.2 object creation format

Variable name = Class name();

3.3 member variables of class (often used!!!)

class Class name:
	def __init__(self):
        self.Variable name 1 = Value 1;
        self.Variable name 2 = Value 2;
        self.Variable name 3 = Value 3;
        self.Variable name 4 = Value 4;

Or we can declare variables directly:

  • If the variable declared at this time does not exist, it is regarded as a defined variable
  • If the variable name exists, it is regarded as a calling variable

3.4 member method of class: self is similar to this

class Class name:
	def Method name(self):
        Method body

Among them, self only represents the placeholder at the time of declaration, and there is no need to pass specific parameters

If it is a method with formal parameters:

class Class name:
	def Method name(self,Formal parameter 1,Formal parameter 2,...)
    	Method body

Member method calling member method: direct access, using self

3.5 init method and magic method

__ init__ Method is run when creating an object and can be executed without manual call

For the method declared in the program and automatically executed by the defined method at a specific time, we call it magic method. Among them, the magic method is characterized by two underscores before and after the method name!

3.6 str method

def __str(self):
    return "Information you need to display";
  • str method is called when using print function to output print object!!!

3.7 case: mobile phone case

Requirements:

  • Mobile phone power is 100 by default
  • Playing games consumes 10 power each time
  • Listening to music consumes 5 electricity each time
  • Phone consumption 4
  • Charging can replenish the power of the mobile phone to 100
class Phone:
    def __init__(self):
        self.quantity = 100;

    def consume(self, x):
        self.quantity -= x;
    # Play games
    def playGame(self):
        print("Playing games...");
        self.consume(10);
        print("After playing the game, the remaining power is: %d" %self.quantity);
    # listen to the music
    def listenMusic(self):
        print("Listening to a song...");
        self.consume(5);
        print("After listening to the song, the remaining power is: %d" %self.quantity);
    # phone
    def call(self):
        print("Calling...");
        self.consume(4);
        print("The remaining power after the call is: %d" %self.quantity);
    #charge
    def charge(self):
        print("Charging...")
        self.consume(3);
        print("After charging, the power is 100%")

myPhone = Phone();
myPhone.listenMusic();
myPhone.playGame();
myPhone.call();
print("At this time, the remaining power of the mobile phone is" + str(myPhone.quantity));
myPhone.charge();

3.8 object oriented encapsulation features

Privatization of member variables can effectively protect access to internal members of a class from the outside of the class

  • When defining variables, use**___** express

We use set and get methods to obtain private variables and set values

Standard definition format

Private setting of protected variables
self.__Variable name = value
 Power lifting external accessor
 Accessor(get method):
def get_Variable name(self):
    return self.__Variable name;
Accessor(set method):
def set_Variable name(self,Formal parameter):
    self.__Variable name = Formal parameter;

Code example:

class Person:
    def __init__(self):
        self.__name = "feng";
        self.__age = 18;
    def get_name(self):
        return self.__name
    def set_name(self, name):
        self.__name = name;
    def get_age(self):
        return self.__age;
    def set_age(self, age):
        self.__age = age;


p = Person();
print(str(p.get_name()) + str(p.get_age()));

Output results:

feng18

**The init method has parameters: * * the above code can be modified to

class Person:
    # Pass in two parameters directly
    def __init__(self,name,age):
        self.__name = name;
        self.__age = age;
    def get_name(self):
        return self.__name
    def set_name(self, name):
        self.__name = name;
    def get_age(self):
        return self.__age;
    def set_age(self, age):
        self.__age = age;

The format of the created object is:

Variable name = Class name(Parameter 1,Parameter 2,...)

3.9 class member variables

The member variables in the class describe the attribute values of objects, which will be different according to different objects. Such variables are called instance variables

A member variable in a class describes the attribute values of an object. According to different objects, there will be no difference. Such variables are called class variables

Class variables belong to the class, and instance variables belong to the object.

How to define class member variables:

class Class name:
    Variable name = value

Call format:

assignment:
    Class name.Variable name = value
 Value:
    Class name.Variable name

be careful:

  • Class variables are not allowed to be modified by using the object name. They can only be modified by the class name. If we make the object to modify the class variable, a new object variable is created
  • Class variables can be privatized

Class 3.10 methods

class Class name:
    @classmethod
    def Method name(cls,parameter list ):
        Method body

Call format:

Class name.Method name(Argument list)

matters needing attention:

  • Instance variables and instance methods are not allowed in class methods

  • Class variables and class methods are allowed in instance methods

  • Among them, self in the instance method and cls in the class method are just a name, which has no too much meaning

3.11 static method

class Class name:
	@staticmethod
    def Method name(parameter list ):
        	Method body

Call format:

  • Class name. Method name (argument parameter) or object name. Method name (argument parameter)

Among them, static methods are independent of classes and can be converted into functions for direct use

3.12 object oriented variable summary

Global variable: a variable defined directly in a py file or declared using global in a class is a global variable

**Local variables: * * directly defined in the method (without self modification) as local variables

Public variable: variables defined by self. In init method or other member methods are called public variables

Unique variable: there is no declaration and definition in our class. A variable attribute is added to the external program, which is called unique variable

Private variable: used before the variable of the class**__** Make declarations and definitions

Class variable: a variable defined directly in a class

For example:

class User:
    country = "Class variable"
    __title = "Class variable"


    def __init__(self):
        self.name = "public variable"
        self.__age = "Public variable"
        info = "local variable"

    def test(self):
        self.address = "public variable"
        email = "local variable"

city = "global variable"
info = "global variable"


u = User()
u.gender = "Unique variable"

Among them, the frequency of using variables: public variables > local variables > private variables, and our public variables = = member variables

3.12 object oriented inheritance

Define format:

class Class name(Parent class name):
    pass

be careful:

  • Subclasses can add members that the parent class does not have
  • Private members of a parent class cannot be inherited

If we want to know the inheritance relationship of our class at this time, we can use the * * mro * * method to display the inheritance relationship of its class

class Animal:
    pass


class Cat(Animal):
    pass


class RedCat(Cat):
    pass


print(RedCat.__mro__)

Output results:

(<class '__main__.RedCat'>, <class '__main__.Cat'>, <class '__main__.Animal'>, <class 'object'>)

Our object class is the parent class of all classes

Method override:
  • On the basis of inheritance relationship, the subclass overrides the existing non private methods of the parent class

  • If the subclass overrides the method of the parent class, when calling the overridden method with the subclass object, execute the method overridden by the subclass

class Person:
    def identify(self):
        print("I am a person")
class Man(Person):
    def identify(self):
        print("I am a Man")
m = Man()
m.identify();

If we want to call the method of the parent class when the child class overrides the method of the parent class, there are several ways:

Call mode 1:
    Parent class name.Method name(object)
Call mode 2:
    super(Name of this class.object).Method name()
Call mode 3:
    super().Method name()
class Person:
    def identify(self):
        print("I am a person")
class Man(Person):
    def identify(self):
        super().identify()
        print("I am a Man")
m = Man()
m.identify();

Output result:

I am a person
I am a Man
Multiple inheritance (supported in Python!!)

Define format:

class Class name(Parent class 1,Parent class 2,....)

If the same method appears in multiple parent classes at this time, it will conflict. It will call and inherit the previous method by default!!!

give an example:

class Father:
    def play(self):
        print("Dad sings")


class Mother:
    def play(self):
        print("Mom dancing")


class Son(Father,Mother):
    pass


s = Son()
s.play();

At this time, the play method of the Father class is called for print output. If you want to call Mother's play method:

  • It is inconvenient to write the Mother class first in the inheritance relationship
  • In the override method, use the first method above to manually specify the method to call Mother

3.13 object oriented polymorphism

  • An object has many forms and displays its functions in different forms in different use environments. It is said that its object has polymorphic characteristics.

  • Polymorphism occurs on the basis of inheritance

For example:

class Person:
    def work(self):
        print("People's work is life")


class Teacher(Person):
    def work(self):
        print("The teacher imparts knowledge in class")


class Driver(Person):
    def work(self):
        print("The driver drives and carries people")


# Pass in person object
def work(person):
    person.work()


# Pass in the teacher object and execute its corresponding work method
teacher = Teacher()
work(teacher)
# Pass in the driver object and execute its corresponding work method
driver = Driver()
work(driver)

Output results:

The teacher imparts knowledge in class
 The driver drives and carries people
Duck type

The object satisfies the calling relationship at the syntax level and does not actually have the corresponding object form. It is said that the object has duck type at this time

For example:

class Teacher:
    def teach(self):
        print("Impart knowledge")



def study(teacher):
    teacher.teach()

teacher = Teacher()
study(teacher)

3.14 object oriented case: anti terrorist elite case

Case requirements:

  • Set three terrorists to engage in gunfight with anti-terrorism elites. Each person sets 100 hp. If the HP is 0, it will be regarded as death. If one party dies, the gunfight will end
  • Anti terrorist elites describe themselves through personal status values
    • No damage: HP 100
    • Minor injury: HP 70 - 99
    • Serious injury: HP 1 - 69
    • Hung up: Health 0
"""
1. Defining humans: describing common attributes life(HP) name((first name)
2. Define elite and terrorist categories
3. Define the main function to describe the gun battle process
4. Define the method of shooting
"""
import random
class Person:
    def __init__(self,name):
        self.name = name
        self.life = 100     #The initial health value is 100
    def __str__(self):
        status = ""
        if self.life <= 0:
            status = "Hang up"
        elif self.life < 70:
            status = "Seriously injured"
        elif self.life < 100:
            status = "minor wound"
        else:
            status = "be without affect"
        return "%s The current status is: %s" %(self.name,status)


# Elite
class Hero(Person):
    def fire(self,p):
        damage = 40
        print("%s towards %s Shoot, cause %d hurt" %(self.name,p.name,damage))
        p.life -= damage
        if p.life < 0:
            p.life = 0
    pass

# terrorist
class Is(Person):
    def fire(self,p):
        damage = 10
        print("%s towards %s Shoot, cause %d hurt" %(self.name,p.name,damage))
        p.life -= damage
        if p.life < 0:
            p.life = 0
    pass





"""
According to the rules of the game, the three terrorists duel with the anti-terrorism elite in turn
 If the anti terrorist elite hangs up, the terrorists win
 If all three terrorists hang up, the anti terrorist elite will win
"""
def main():
    hero = Hero("[Counter terrorism elite]")
    is1 = Is("[Terrorists [1]")
    is2 = Is("[Terrorists 2]")
    is3 = Is("[Terrorists 3]")
    # Indicates the round
    index = 1
    while hero.life > 0 and (is1.life > 0 or is2.life > 0 or is3.life > 0):
        # Get a random number from 0 - 3
        num = random.randint(0, 3)
        print("The first%d Round of gunfight begins:" %index)
        index += 1
        if num == 0:
            hero.fire(is1)
            hero.fire(is2)
            hero.fire(is3)
        elif num == 1:
            hero.fire(is1)
            is1.fire(hero)
        elif num == 2:
            hero.fire(is2)
            is2.fire(hero)
        elif num == 3:
            hero.fire(is3)
            is3.fire(hero)
        #Export elite and terrorist status
        print(hero.__str__())
        print(is1.__str__())
        print(is2.__str__())
        print(is3.__str__())
        print()

    if hero.life == 0:
        print("[Terrorists] in the second%d Win a round of gunfight" %index)
    else:
        print("%s In the first%d Win a round of gunfight" %(hero.name,index))
#Call the main() method
main()

Output results:

The first round of gun battle begins:
[Counter terrorism elite] shoots at [terrorist 2], causing 40 damage
[Terrorist 2] shoots at [anti terrorist elite], causing 10 injuries
[[anti terrorist elite] current status: minor injury
[Terrorist 1] current status: no injuries
[Terrorist 2] current status: seriously injured
[Terrorist 3] current status: no injuries

The second round of gun battle begins:
[Counter terrorism elite] shoots at [terrorist 1], causing 40 damage
[Terrorist 1] shoots at [anti terrorist elite], causing 10 injuries
[[anti terrorist elite] current status: minor injury
[Terrorist 1] current status: seriously injured
[Terrorist 2] current status: seriously injured
[Terrorist 3] current status: no injuries

The third round of gun battle begins:
[Counter terrorism elite] shoots at [terrorist 1], causing 40 damage
[Terrorist 1] shoots at [anti terrorist elite], causing 10 injuries
[[anti terrorist elite] current status: minor injury
[Terrorist 1] current status: seriously injured
[Terrorist 2] current status: seriously injured
[Terrorist 3] current status: no injuries

The fourth round of gun battle begins:
[Counter terrorism elite] shoots at [terrorist 1], causing 40 damage
[Terrorist 1] shoots at [anti terrorist elite], causing 10 injuries
[[anti terrorist elite] current status: seriously injured
[Terrorist 1] the current status is: hung up
[Terrorist 2] current status: seriously injured
[Terrorist 3] current status: no injuries

The fifth round of gun battle begins:
[Counter terrorism elite] shoots at [terrorist 2], causing 40 damage
[Terrorist 2] shoots at [anti terrorist elite], causing 10 injuries
[[anti terrorist elite] current status: seriously injured
[Terrorist 1] the current status is: hung up
[Terrorist 2] current status: seriously injured
[Terrorist 3] current status: no injuries

The sixth round of gun battle begins:
[Counter terrorism elite] shoots at [terrorist 1], causing 40 damage
[Terrorist 1] shoots at [anti terrorist elite], causing 10 injuries
[[anti terrorist elite] current status: seriously injured
[Terrorist 1] the current status is: hung up
[Terrorist 2] current status: seriously injured
[Terrorist 3] current status: no injuries

The 7th round of gun battle begins:
[Counter terrorism elite] shoots at [terrorist 3], causing 40 damage
[Terrorists 3] shot at [anti terrorist elite], causing 10 injuries
[[anti terrorist elite] current status: seriously injured
[Terrorist 1] the current status is: hung up
[Terrorist 2] current status: seriously injured
[Terrorist 3] current status: seriously injured

The 8th round of gun battle begins:
[Counter terrorism elite] shoots at [terrorist 1], causing 40 damage
[Counter terrorism elite] shoots at [terrorist 2], causing 40 damage
[Counter terrorism elite] shoots at [terrorist 3], causing 40 damage
[[anti terrorist elite] current status: seriously injured
[Terrorist 1] the current status is: hung up
[Terrorist 2] the current status is: hung up
[Terrorist 3] current status: seriously injured

The 9th round of gun battle begins:
[Counter terrorism elite] shoots at [terrorist 1], causing 40 damage
[Counter terrorism elite] shoots at [terrorist 2], causing 40 damage
[Counter terrorism elite] shoots at [terrorist 3], causing 40 damage
[[anti terrorist elite] current status: seriously injured
[Terrorist 1] the current status is: hung up
[Terrorist 2] the current status is: hung up
[Terrorist 3] the current status is: hung up

[Counter terrorism elite] won the 10th round of gun battle

Later, we will update the advanced syntax knowledge of python and the summary of some common practical project notes. Please look forward to

Posted by lilywong on Mon, 18 Oct 2021 15:02:38 -0700