[programming help] use of Python basic syntax and example demonstration

Posted by siesmith on Tue, 22 Feb 2022 12:32:23 +0100

1. Notes

1.1 notes - single line notes

   ① "#" is a single line annotation, and the Python interpreter will ignore the input after #, and will not execute it.
   ② # can be placed on the top and right of the code.
   ③ long press the left mouse button to select a single line or multiple lines of code, and press Ctrl + / to directly annotate them as single line comments

# I love God Li Linghua
print("Shenli Linghua is my wife.") # The print() function prints the content to the console

1.2 comments - multiline comments

   ① three quotation marks (single quotation marks and double quotation marks) are multiline annotators. The Python interpreter will ignore the contents within the quotation marks and will not execute them.
   ② multi line comments cannot be placed on the right side of the code.

"""
I love Ling Hua
 Ling Hua loves me
"""
'''
I love the son of God
 The son of God loves me
'''
print("Ling Hua is my wife.") 

2. Variables

2.1 variable - variable concept

   in short, a variable is a code used to store data.

age=18

  at this time, age is a variable, and the variable value is 18.

2.2 variables - naming rules

   ① must start with English letter (recommended), underline or Chinese (not recommended).
   ② variable names can only be composed of English letters, numbers, underscores or Chinese characters.
   ③ English letters are case sensitive. Age and age are two different variable names.
   ④ Python built-in functions and reserved words cannot be used as variable names.

3. Data type

   six basic data types of Python: number (int,float), string (str), list (list), Dictionary (dictionary), tuple (tuple), set (set).

3.1 data type - numeric type

3.1.1 numeric type - integer int

   integer refers to a number without decimal point (positive integer, negative integer, 0).

a=10
b=-10
c=0

print(a,b,c)

3.1.1 number type - float ing point

   floating point refers to a number with a decimal point.

a=10.5
b=3.1415926
c=-0.55

print(a,b,c)

3.2 data type - string type str

   ① a string is a combination of characters.
   ② put the string content in a pair of quotation marks (quotation marks can be single, double or three quotation marks).

a='I love China'
b="I love China"
c='''I love China'''

print(a)
print(b)
print(c)


   ③ string numbers cannot participate in arithmetic operation (both str+int and str+float report errors).

a='10'         # String type
b=10          # Integer type
c=20.5       # Floating point type

print(a)
print(b)
print(a+b)
print(a+c)
print(b+c)


   ④ quotation marks cannot be mixed. For example, a pair of quotation marks must be followed by a single quotation mark.

a="I'am XiaoMing"

print(a)

3.3 data type - list type

3.3.1 list type - definition list

   list name = [element 1, element 2, element 3...]

My_list = ["Eight God son","Shenli Linghua","Ke Qing","Cory","Barbara "]
print(My_list)


   of course, the elements of the list can be strings, numbers, or even another list.

My_list = ["Zhong Li",1314,[1,2,3]]
print(My_list)

3.3.2 list type - traversal list

My_list = ["Eight God son","Shenli Linghua","Ke Qing","Cory","Barbara "]
for i in My_list:     # Take out the elements in the list from left to right
    print(i)

3.3.3 list type - count the total number of all elements in the list

   len (list name)

My_list = ["Eight God son","Shenli Linghua","Ke Qing","Cory","Barbara "]
a = len(My_list)
print(a)

3.3.4 list type - counts the total number of occurrences of a single element in the list

my_list = ["Eight God son","Shenli Linghua","Eight God son","Eight God son","Barbara ","Eight God son","timely rain","Condensing light"]

nums1 = my_list.count("Eight God son")
print(nums1)
my_list = ["Eight God son","Shenli Linghua","Ke Qing","Cory","Barbara ","Diona ","timely rain","Condensing light"]

nums2 = my_list.count("Diluk")    # 0 is returned when the value to be found is not found in the list
print(nums2)

3.3.5 list type - Retrieve element index

my_list = ["Eight God son","Shenli Linghua","Ke Qing","Cory","Barbara "]


ke1 = my_list.index("Cory")  # Find the subscript (index) corresponding to the element "Cori"
print(ke1)
my_list = ["Eight God son","Shenli Linghua","Ke Qing","Cory","Barbara "]

ke2 = my_list.index("Diluk")  # The element "diluk" is not in the list and an error is reported
print(ke2)

3.3.6 list type - extracts a single element from a list

  list name [subscript]

My_list = ["Eight God son","Shenli Linghua","Ke Qing","Cory","Barbara "]
a = My_list[2]
print(a)

3.3.7 list type - extract multiple elements of the list (list slice)

My_list = ["Eight God son","Shenli Linghua","Ke Qing","Cory","Barbara ","Diona ","timely rain","Condensing light"]

a = My_list[1:4]
print(a)

a = My_list[1:]
print(a)

a = My_list[:4]
print(a)

a = My_list[:]
print(a)

a = My_list[::2]
print(a)

a = My_list[::-1]
print(a)

a = My_list[-2:]
print(a)

a = My_list[:-2]
print(a)

3.3.8 list type - add elements at the end of the list

  list name Append (element)

My_list = []   # Create an empty list

My_list.append("Eight God son")
print(My_list)
My_list.append("timely rain")
print(My_list)

3.3.9 list type - list insert element

my_list = ["timely rain", "Shen He", "Piano"]

my_list.insert(1, "12306")
print(my_list)

3.3.10 list type - modify list elements

  list name [subscript] = element

My_list = ["Eight God son","Shenli Linghua","Ke Qing","Cory","Barbara "]
My_list[2] = 1314
print(My_list)

3.3.11 list type - summation of list elements (all elements are numeric)

My_list = [1,2,3,4,5,6]

print(sum(My_list))

3.3.12 list type - maximum and minimum values of list elements (all elements are numeric)

My_list = [1,2,3,4,5,6]

print(max(My_list))    # Take the maximum value
print(min(My_list))    # Take the minimum value

3.3.13 list type - list to string

  convert the list into a string connected with a connector (comma, semicolon, etc., or don't write it into a sentence at all)
  'connector' Join (list name)

My_list = ["Eight God son","Shenli Linghua","Ke Qing","Cory","Barbara "]

a = ','.join(My_list)
print(a)
a = ''.join(My_list)
print(a)

3.3.14 list type - string to list

   string split("separator")

a = "I always like Shenli Linghua"

My_list=a.split(" ")
print(My_list)

My_list=a.split(",")
print(My_list)

3.3.15 list type - list addition

my_list1 = ["Shenli Linghua","Eight God son"]
my_list2 = ["Shen He"]

my_list3 = my_list1 + my_list2
print(my_list3)

3.3.16 list type - list multiplication

my_list1 = ["Shenli Linghua","Eight God son"]

my_list2 = my_list1 * 2
print(my_list2)

3.3.17 list type - delete list elements

  ① del delete

my_list = ["Eight God son","Shenli Linghua","Ke Qing","Cory","Barbara ","Diona ","timely rain","Condensing light"]

# Delete an element by index
del my_list[0]
print(my_list)
my_list = ["Eight God son","Shenli Linghua","Ke Qing","Cory","Barbara ","Diona ","timely rain","Coagulate>light"]

# Delete list interval elements by index
del my_list[0:3]
print(my_list)
my_list = ["Eight God son","Shenli Linghua","Ke Qing","Cory","Barbara ","Diona ","timely rain","Condensing light"]

# Delete list interval elements by index
del my_list[0:3:2]
print(my_list)

   ② pop() function

my_list = ["Eight God son","Shenli Linghua","Ke Qing","Cory","Barbara ","Diona ","timely rain","Condensing light"]


my_list.pop(1)    # My without subscript_ list. Pop() deletes the last item by default
print(my_list)


   ③ remove() function

my_list = ["Eight God son","Shenli Linghua","Ke Qing","Cory","Barbara ","Diona ","timely rain","Condensing light"]

my_list.remove("Ke Qing")
print(my_list)

3.3.18 list type - sort

  ① sort from small to large

my_list = [3, 4, 1, 2, 9, 8, 7]


print("Before sorting:", my_list)
my_list.sort()
print("After sorting:", my_list)


  ② sort from large to small

my_list = [3, 4, 1, 2, 9, 8, 7]


print("Before sorting:", my_list)

my_list.sort(reverse=True)
print("After sorting:", my_list)

3.4 data type - dictionary type

3.4.1 dictionary type - Definition Dictionary

   dictionary name = {key 1: value 1, key 2: value 2, key 3: value 3...}

my_dict = {"Xiao Ming":85,"Xiao Hong":76,"Xiaolan":97,"Little green":100}

print(my_dict)

3.4.2 dictionary type - get value by key

my_dict = {"Xiao Ming":85,"Xiao Hong":76,"Xiaolan":97,"Little green":100}

a = my_dict["Xiao Ming"]

print(a)

3.4.3 dictionary type - add element

my_dict = {"Xiao Ming":85,"Xiao Hong":76,"Xiaolan":97,"Little green":100}

my_dict["Xiao Hei"] = 60

print(my_dict)

3.4.4 dictionary type - modify element

my_dict = {"Xiao Ming":85,"Xiao Hong":76,"Xiaolan":97,"Little green":100, "Xiao Hei": 60}

my_dict["Xiao Hei"] = 13

print(my_dict)

3.4.5 dictionary type - delete element

my_dict = {"Xiao Ming":85,"Xiao Hong":76,"Xiaolan":97,"Little green":100, "Xiao Hei": 60}

del my_dict["Xiao Hei"]

print(my_dict)

3.4.6 dictionary type - empty dictionary

my_dict = {"Xiao Ming":85,"Xiao Hong":76,"Xiaolan":97,"Little green":100, "Xiao Hei": 60}

my_dict.clear()

print(my_dict)

3.4.7 dictionary type - traverse key value pairs

# Directly to my_dict traversal
my_dict = {"Xiao Ming":85,"Xiao Hong":76,"Xiaolan":97,"Little green":100, "Xiao Hei": 60}


for item in my_dict:
   print(item)
# Traverse my_ items method of Dict
my_dict = {"Xiao Ming":85,"Xiao Hong":76,"Xiaolan":97,"Little green":100, "Xiao Hei": 60}


for item in my_dict.items():
   print(item)
# Traverse my_ The items method of dict and receive it with key and value
my_dict = {"Xiao Ming":85,"Xiao Hong":76,"Xiaolan":97,"Little green":100, "Xiao Hei": 60}


for key,value in my_dict.items():
   print("key:{},value:{}".format(key,value))

3.4.8 dictionary type - traversal key

my_dict = {"Xiao Ming":85,"Xiao Hong":76,"Xiaolan":97,"Little green":100, "Xiao Hei": 60}


for key in my_dict.keys():
   print(key)

3.4.9 dictionary type - traversal value

my_dict = {"Xiao Ming":85,"Xiao Hong":76,"Xiaolan":97,"Little green":100, "Xiao Hei": 60}


for value in my_dict.values():
   print(value)

3.4.10 dictionary type - get method

my_dict = {"Xiao Ming":85,"Xiao Hong":76,"Xiaolan":97,"Little green":100, "Xiao Hei": 60}


x = my_dict.get("Xiao Hong")
print(x)

my_dict = {"Xiao Ming":85,"Xiao Hong":76,"Xiaolan":97,"Little green":100, "Xiao Hei": 60}

# An attempt was made to return the value of an item that does not exist
x = my_dict.get("Xiao Huang",45)
print(x)

3.5 data type - tuple type

   tuples are basically used in the same way as lists
  the difference is:
   ① the tuple uses parentheses (), and the list uses brackets [].
   ② and the elements in the tuple cannot be modified.

3.5.1 data type - definition tuple

① Declare a tuple object

my_tuple = (1, 2, 3)


print(my_tuple)
print(type(my_tuple))
my_tuple1 = ("www", "aaa", "ggg")


print(my_tuple)
print(type(my_tuple))


② Declare a tuple object with only one element

my_tuple2 = ("www", )


print(my_tuple2)
print(type(my_tuple2))

3.6 data type - set type

   ① a set is an unordered non repeating sequence, that is, there will be no repeating elements in the set.
   ② a set can be defined by braces {} or created by the set() function.

3.6.1 set type - create set

a = ["Piano","Barbara ","Cory","Barbara ","seven seven","Barbara ","Barbara ",]

b=set(a)
print(b)

4. Operator

4.1 operator - arithmetic operator

Symbolnamemeaning
+Addition operatorCalculate the sum of two numbers
-Subtraction operator (minus sign)Calculate the difference between two numbers (representing the opposite of a number)
*Multiplication operatorCalculate the product of two numbers
/division operator Calculate the divisor of two numbers
**Power operatorCalculate the square of a number
//Division operator*Calculate the integral part of the quotient divided by two numbers, and the decimal part is rounded off
%Modulo operator*Calculates the remainder of the division of two positive integers
>>> 9//two 	   #  Rounding
4
>>> 9 % 2        # Surplus
1

4.2 operator - string operator

   ① string - connection between strings

a = "my"
b = "name"

c = a+b
print(c)
>>>myname

   ② string - connection between numbers and strings

a = 123
b = "name"

c = str(a) + b    # str(a) converts the integer variable a into a string, otherwise an error is reported
print(c)
>>>123name

4.3 operator - comparison operator

Symbolnamemeaning
>Greater than operatorJudge whether the left value is greater than the right value
<Less than operatorJudge whether the left value is less than the right value
>=Greater than or equal to operatorJudge whether the left value is greater than or equal to the right value
<=Less than or equal to operatorJudge whether the left value is less than or equal to the right value
==equal operator Judge whether the left value is equal to the right value
!=Not equal to operatorJudge whether the left value is not equal to the right value

4.4 operator - assignment operator

Symbolnamemeaning
=Simple assignment operator Assign the operation result on the right side of the operator to the left side
+=Assignment operator additionPerforms an addition operation and assigns the result to the left
-=Subtraction assignment operatorPerforms a subtraction operation and assigns the result to the left
*=Multiplication assignment operatorPerforms multiplication and assigns the result to the left
/=Division assignment operatorPerforms a division operation and assigns the result to the left
**=Power assignment operatorPerforms a meter calculation and assigns the result to the left
//=Integer division assignment operatorPerforms an integer division operation and assigns the result to the left
%=Modulo assignment operatorPerforms a modulo operation and assigns the result to the left
i=10
i += 10    # Equivalent to i = i+10 
print(i)
>>>20

4.5 operators - logical operators

Symbolnamemeaning
andLogic andThe operator returns True only when the values on both sides of the operator are True. Otherwise, it returns False
orLogical orIf both sides of the operator are True, it returns True; otherwise, it returns False
notLogical nonTrue is returned only when both sides of the operator are False, otherwise False is returned
score = -10
year = 2019

if (score < 0) and (year == 2019):    # Only when the score is less than 0 and the year is equal to 2019 can it be executed
	print("Enter database") 
else:
	print("Do not enter database")

>>>Enter database

5. Escape character

5.1 \t - equal to pressing a Tab key

print("\tPython")

5.2 \n - equal to pressing an enter key

print("Python\nJAVA\nC++\nJavaScript\nC#")

5.3 \ - continue to output multiple lines of code as one line of content

new_os = 'huawei' \
        'HarmonyOS' \
        ' is coming'
print(new_os)

6. Formatting characters

%d integer output
%f floating point number output
%s string output

name = "Xiao Ming"
age = 18
score = 100

# Format a variable output
print("I am %s" % name)
# Format multiple variable outputs
print("I am %s this year %d Years old, I got it in the exam%.2f branch" % (name,age,score))     ># . 2 means to keep two decimal places

# format function
print("I am{},this year{},Got the exam{:.2f}".format(name,age,score))     # ":. 2f" Table > the numbers shown are floating-point numbers with two decimal places reserved

Topics: Python Back-end