The basic syntax of Python based on machine learning (1)

       Today's world has entered the era of big data. With the continuous development of informatization, words such as artificial intelligence and machine learning are becoming more and more familiar to people, and they have gradually become the trendsetters of this era, walking in the forefront of the information age. Starting from this blog, the editor will lead you into the machine learning part of artificial intelligence, so that deep learning is no longer difficult. At the same time, related articles will be published in my blog column "Python from entry to deep learning" , welcome everyone to pay attention~

      The series of blogs "Python from Getting Started to Deep Learning" were written by the editor after careful consideration. The purpose is to facilitate everyone to learn together and to consolidate their knowledge. This column is mainly based on code. The principle explanation of related algorithms will be explained in a separate column of new algorithms after this column is updated, so stay tuned. In order to facilitate common learning, the editor lists detailed comments in the code.


content

1. The basic syntax of Python based on machine learning (1)

2. The basic syntax of Python based on machine learning (2)

Third, the use of the Numpy library based on machine learning


        Disclaimer: The running environment of the code is Python3. Python3 and Python2 will be different in some details, I hope readers will pay attention. Let's start our first lecture: the basic syntax of Python based on machine learning (1).


【Code】

'''
Basic syntax of Python for machine learning
'''

# Print data to the console: brackets are not required in python2; brackets are required in python3
print("Hello World!!") # It is worth mentioning that the ; at the end of the code is optional
# Print multiple variables at the same time, separate each variable with
a = "I am:"
b = "The elephant is dancing"
print(a, b)
# Unicode (utf-8) strings are supported in python3
name = 'The elephant is dancing'
print(name)

# Use of annotations: single-line comments start with #; multi-line comments are represented by three single quotes ''' or three double quotes """

# Data type: 1. Variable assignment in Python does not require type declaration; 2. In Python, all identifiers can include English, numbers and underscores (_), but cannot start with numbers and are case-sensitive;
# 3. Identifiers starting with an underscore have special meaning. For example: _foo cannot be accessed directly, it needs to be accessed through the interface provided by the class; 4. In python, variables have no type, such as: a=[1,2,3];a="Runoob"
# [1,2,3] is a List type, "Runoob" is a String type, and the variable a has no type, it is just a reference to an object (a pointer), which can point to a List type object or a String type object ;
# Python3 has six standard data types: Number (number); String (string); List (list); Tuple (tuple); Dictionary (dictionary); Set (collection, new in Python3)

# Numbers: Python3 supports three different number types: int (signed integer); float (floating point); complex (complex number: composed of real and imaginary numbers, use a + bj, or complex(a,b) to Express)
# long (long, note: removed in Python 3)
a = 100
print(a)
b = 1.23
print(b)
c = 10 + 2j # complex number (real + imaginary)
print(c)

# String: Use quotation marks ( ' ), double quotation marks ( " ), triple quotation marks ( ''' or """ ) to represent strings, where triple quotation marks can consist of multiple lines
a = 'xzw'
b = "I'm an elephant dancing"
c = '''I am an elephant dancing,
from Shanghai'''
print(a, b, '\n', c) # separated by spaces

str = 'Hello World!'
print(str)
print(str[0]) # print the first character in the string
print(str[2:5]) # Output the string between the third and fifth (excluding the fifth) in the string
print(str[2:]) # print the string starting from the third character
print(str * 2) # print the string twice
print(str + "I am xzw.") # print the concatenated string
# print(str+1) # error, cannot be a non-string type (not the same as java)
# This method is inefficient. Strings in python are immutable types. When using + to connect two strings, a new string will be generated. To generate a new string, you need to re-apply for memory.
# When there are many strings to be added (a+b+c+d+e+f+...), inefficiency is inevitable
print('a' + 'b' + 'c')
# Slightly complicated, but it is efficient to connect multiple characters, and there is only one memory application. This method is the first choice when connecting the characters of the list.
listStr = ['a', 'b', 'c']
s = ''.join(listStr)
print(s)
# String formatting, this method is very common
print('%s%s%s' % ('a', 'b', 'c'))
print( 'Hello: %s %s %s' % ('xzw', 100, 22.3) )
# Assign multiple variables at the same time
a, b, c = 1, 2.2, "xzw"
print(a, b, c)

# List: List (list) is the most frequently used data type in Python. Lists support characters, numbers, strings, and can also contain lists (that is, nested)
list = ['xzw', 786, 2.23, 'Eric', 70.2]
tinylist = [123, 'Eric']
print(list) # print the full list
list[0] = 'aaa'
print(list[0]) # print the first element of the list
print(list[1:3]) # print the second to third elements, excluding the third
print(list[2:]) # prints all elements from the third to the end of the list
print(tinylist * 2) # List elements are repeated twice
print(list + tinylist) # merge the two lists

# Tuple: Group is another data type, similar to List. Tuples are identified with "()". Inner elements are separated by commas. But tuples cannot be assigned twice, and are equivalent to read-only lists.
tuple = ( 'xzw', 786 , 2.23, 'Eric', 70.2 )
tinytuple = (123, 'Eric')
print(tuple) # print the full tuple
# tuple[0]='aaa' # error
print(tuple[0]) # print the first element of the tuple
print(tuple[1:3]) # print the second to third elements
print(tuple[2:]) # prints all elements from the third to the end of the list
print(tinytuple * 2) # print the tuple twice
print(tuple + tinytuple) # print the combined tuple

# dictionary
dict = {}
dict['xzw'] = "This is xzw"
dict[2] = "This is two"
tinydict = {'name': 'xzw', 'code':6734, 'dept': 'sales'}
print(dict['xzw']) # print the value with key 'one'
print(dict[2]) # print the value with key 2
print(tinydict) # print the complete dictionary
print(tinydict.keys()) # print all keys
print(tinydict.values()) # print all values

# Set: New in Python 3
student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'}
print(student) #Duplicate elements are automatically removed
if('Rose' in student) :
    print('Rose is in the set')
else :
    print('Rose is not in the set')
# set can perform set operations
a = set('abcde')
b = set('abcfg')
print(a)
print(b)
print(a - b) # Difference of a and b
print(a | b) # union of a and b
print(a & b) # intersection of a and b
print(a ^ b) # elements in a and b that do not exist at the same time

# bytes type: newly added in Python3
b = b'xzw'
print(b[0]) #Print out the ascii code
print(type(b)) #View the type
s = b.decode() #convert to string
print(s)
b1 = s.encode() #Convert to bytes type
print(b1)

# Mutable and immutable: In python, string, tuple, and number are immutable objects, while list, dict, etc. are modifiable objects
# Immutable type: assign a=5 to the variable and then assign a=10, here is actually a newly generated int value object 10, and then let a point to it, and 5 is discarded, not changing the value of a, which is equivalent to a new generation a
# Variable type: variable assignment list=[1,2,3,4] and then assigning list[2]=5 is to change the value of the third element of llist, the list itself does not move, just a part of its internal value has been modified

# operator
print(2 ** 3) # 8 exponentiation
print(10 // 3) # 3 Find integer quotient
print(1 / 2) # 0.5, different from other languages

a = 100
a += 1 # no a++
print(a)

# Relational operators: > < == != ( <> not supported in Python 3) >= <=
# Logical operators: 0 is false, non-0 is true
a = 10
b = 20
if (a and b):
    print("1 - variables a and b are both true")
else:
    print("1 - one of the variables a and b is not true")

if (a or b):
    print("2 - both variables a and b are true, or one of them is true")
else:
    print("2 - neither variable a nor b is true")

# modify the value of variable a
a = 0
if (a and b):
    print("3 - variables a and b are both true")
else:
    print("3 - one of the variables a and b is not true")

if (a or b):
    print("4 - both variables a and b are true, or one of them is true")
else:
    print("4 - neither variable a nor b is true")

if not (a and b):
    print("5 - variables a and b are both false, or one of them is false")
else:
    print("5 - variables a and b are both true")

# Member operators: in, not in
a = 1
b = 20
list = [1, 2, 3, 4, 5];

if (a in list):
    print("1 - variable a is in the given list list")
else:
    print("1 - variable a is not in the given list list")

if (b not in list):
    print("2 - variable b is not in the given list list")
else:
    print("2 - variable b is in the given list list")

# identity operator
# is is to determine whether two identifiers refer to an object, x is y is similar to id(x) == id(y)
# The difference between is and ==: is is used to judge whether two variable reference objects are the same, == is used to judge whether the values ​​of reference variables are equal
a = 20
b = 20
print(a is b)
print(a is not b)
# modify the value of variable b
b = 30
print(a is b)
print(a is not b)
# is is special in the Python command line. In order to improve the memory utilization efficiency, for some simple objects, such as some int objects with small values, python adopts the method of reusing the object memory, such as pointing to a = 2, b = 2
# When 2 is a simple int type and the value is small, python will not allocate memory for it twice, but only once, and then point a and b to the allocated object at the same time
# c = 20
# d = 20
# c is d
# True
# But if the assignment is not 2 but a larger value, the situation is different:
# c = 5555
# d = 5555
# c is d
# False

# Condition: python does not support switch statements
num = 5
if num == 3:
    print('boss')
elif num == 2:
    print('user')
elif num == 1:
    print('worker')
elif num < 0:
    print('error')
else:
    print('roadman')

# Code group: The biggest difference between Python and other languages ​​is that Python code blocks do not use curly brackets. The most distinctive feature of Python is to use indentation to write modules, and the same set of indented statements form a code block, which we call a code group.
# The first line like if, while, def and class starts with a keyword and ends with a colon, and one or more lines of code after this line form a "code group"
# We call the first line and the following code group a "clause" The amount of indented whitespace is variable, but all code block statements must contain the same amount of indented whitespace, this must be strictly enforced!! !
# E.g:
# if expression:
# suite # code group
# elif expression:
#     suite
# else:
#     suite
# For example: (Note: There is no strict indentation, and an error will be reported during execution). Support Chinese through the coding attribute (add this sentence when Chinese is not supported)
# The following code will report an indentation error IndentationError
# # !/usr/bin/python
# # -*- coding: UTF-8 -*-
# if True:
#     print("aaa")
#     print("True")
# else:
#     print("bbb")
# print("False") # Pay attention to indentation, as long as it is aligned, there is no difference between using spaces or tabs to align
# Note: In some environments, tabs and spaces cannot be mixed, but in some environments, it is recommended to use them uniformly at each indentation level. 'single tab', 'two spaces' or 'four spaces', try not to mix them to avoid unnecessary trouble

# while
count = 0
while count < 10:
    # while (count < 10) : #Also possible
    print('The count is:', count)
    count = count + 1
# while … else …: When the loop condition is false, execute the else block, only once
count = 0
while count < 5:
    print(count, " is  less than 5")
    count = count + 1
else:
    print(count, " is not less than 5")

# continue
i = 1
while i < 10:
    i += 1
    if i % 2 != 0: # skip output if non-double
        continue
    print(i) # print the double numbers 2, 4, 6, 8, 10

# break
i = 1
while True:
    print(i)
    i += 1
    if i > 10: # break out of the loop when i is greater than 10
        break

# for
for letter in 'Python3':
    print('Current letter:', letter)

names = ['xzw', 'Eric', 'Josie']
for name in names:
    print('Current name:', name)

# Iterate through sequence index
names = ['xzw', 'Eric', 'Josie']
for index in range(len(names)):
    # for index in range(3): #The effect is the same, ie (1,2,3)
    print('Current name:', names[index])

# for ...else
for num in range(2, 10): # iterate over numbers between 2 and 10
    for i in range(2, num): # iterate by factors
        if num % i == 0: # determine the first factor
            j = num / i # calculate the second factor
            print('%d is equal to %d * %d' % (num, i, j))
            break # break out of the current loop
    else: # else part of the loop
        print(num, 'is a prime number')

# pass: The pass statement does nothing and is generally used as a placeholder
for letter in 'Python':
    if letter == 'h':
        pass
        print('This is the pass block')
    else:
        print('Current letter:', letter)

# Insert variable into string:
# method one:
name = 'xzw'
sayhello = 'Hello,' + name
print(sayhello)
# Method 2: Formatting function of characters % s represents strings, % d represents integers, both represent placeholders in characters, and there is a one-to-one correspondence between the position of variables and the placeholders in the string
name = 'xzw'
age = 22
sayhello = 'my name is %s ,and my age is %d ' % (name, age)
print(sayhello)
# Method 3: The format method of the passed string
sayhello = 'my name is {0},and my age is {1} '
print(sayhello.format('xzw', 22))

# File read and write operations:
# Read the file:
f = open('C:\\test.txt', 'r')
print(f.read())
f.close()
# write file:
f = open('C:\\test.txt', 'w') # w is overwrite, a is appended
f.write('hello python!!!')
f.close() # If the data written does not close the connection, the data may still be in the content

# Builder
# List: The data types stored in the list in python can be different, and the list can be dynamically extended in length. Use [] to represent a list
# Basic operations:
list = [12, 'xzw', 1.1, 'Eric', 111]
print(list[0])
print(list[-1])
list[0] = 13
print(list)
list.append(100)
list.extend([20444555, 440])
list.insert(1, 'str')
list.pop()
print(list)

# A slice of the list:
print(list[0:3]) # Left closed and right open
print(list[:3])
print(list[-3:-1]) # Left closed and right open
print(list[-3:])
print(list[0:99])
list = list(range(1, 100))
print(list)
print(list[10:20])
print(list[0:10:3])
print(list[::5])
print(list[::])

# list comprehension
# method one:
L = []
for i in range(1, 10):
    L.append(i * i)
print(L)

# Method 2 (list comprehension):
list = [x * x for x in range(1, 10)]
print(list)
list = [x * x for x in range(1, 10) if x % 2 == 0]
print(list)

# Generator generator: A list can be generated directly through the list generation, and the elements are calculated. If a list has a lot of elements, calculating the result directly will produce oom. The generator can solve:
# The generator does not directly calculate the value of the elements in the list, but saves the calculation algorithm. Each time the generator is called, a calculation is performed instead of directly calculating all the values. The type of the generator is the generator type
# list comprehension result is list type
# Create the generator:
# method one:
list = (x * x for x in range(1, 10) if x % 2 == 0)
print(list)
print(type(list))
# Method Two:
# If there is a yield keyword declaration in a function, the final return result of the function is a generator
list = range(1, 10)
def getSquare(list):
    for i in list:
        temp = i * i
        yield temp # Using the yield keyword, the function becomes a generator
print(getSquare(list))

# The value of the generator:
# Method 1: Every time the next method is called, it will be calculated once and the calculation result will be returned
print(next(getSquare(list)))
print(next(getSquare(list)))
print(next(getSquare(list)))
print(next(getSquare(list)))
# Method 2: The generator is also an iterable object, so you can use for to iterate
for x in getSquare(list):
    print(x)


What problems did you encounter in this process, welcome to leave a message, let me see what problems you have encountered.

Guess you like

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