Python Grammar Basics

Posted by jumphopper on Fri, 10 May 2019 12:10:05 +0200

# Direction of variables
a  = "abc"
b = a
a = "def"
print(a)
print(b)
def
abc
print(10/3)  # The result is a decimal
print(10//3) #The result is an integer
print(10%3)  # Remainder
3.3333333333333335
3
1
#Summary
 #Python supports a variety of data types. Within a computer, any data can be viewed as an object, and variables are used in programs to point to these data objects.
#Assigning to variables means associating data with variables.

#Assigning x = y to a variable points the variable x to the real object that the variable y points to.Subsequent assignments to the variable y do not affect the direction of the variable x.

Note: Python integers have no size limitations, and some languages have size limitations based on their storage length, for example, Java limits the range of 32-bit integers to -21474848-2147483647.

The #Python floating point number has no size limit, but beyond a certain range it is expressed as inf (infinite).
# Character string
print('Hello, %s,Your salary this month is %s'%('hufei', 234112)) # First
'Hello, {0}, Your phone bill this month is {1}'.format('hufei', 23.1) # Second

# Code
# ASCII encoding: At first, only 127 characters were encoded into the computer, that is, uppercase and lowercase letters, numbers, and some symbols. This encoding table is called ASCII encoding. For example, the encoding of capital letter A is 65, and the encoding of lowercase letter z is 122.
# Unicode unifies all languages into a set of codes, expressed in binary.The letter A is encoded in ASCII as 65 decimal and the binary 01000001; the character 0 is encoded in ASCII as 48 decimal and the binary 00110000
# UTF-8 encoding: UTF-8 encoding encodes a Unicode character into 1-6 bytes according to different number sizes. Common English letters are encoded into 1 byte. Chinese characters are usually 3 bytes. Only very unusual characters are encoded into 4-6 bytes.If the text you are transferring contains a large number of English characters, you can save space by encoding it in UTF-8
#ASCII encoding is one byte, while Unicode encoding is usually two bytes, and UTF-8 is not the same size in different languages.

# Storage in computer
#Character encoding methods common to computer systems:
# Unicode encoding is used uniformly in computer memory and is converted to UTF-8 encoding when it needs to be saved to a hard disk or transmitted.
# When editing with Notepad, UTF-8 characters read from the file are converted to Unicode characters in memory. When editing is completed, UTF-8 characters converted to Unicode are saved to the file when saving
Hello, hufei, your monthly salary is 23412





'Hello, hufei, your phone bill this month is 23.1'
# list
name_list = ['Director of Research and Development', 'Service Engineer', 'Front End Engineer', 'Test Engineer']
name_list.append('UI Design')
name_list.insert(0, 'Boss')
name_list
['Boss', 'Director of Research and Development', 'Service Engineer', 'Front End Engineer', 'Test Engineer', 'UI Design']
# tuple
classmates = ('Michael', 'Bob', 'Tracy')
# What tuple calls "unchanged" is that each element of a tuple points to never change.That is, to point to'a', you cannot change to point to'b', point to a list, you cannot change to point to other objects, but the list itself is variable!
# dict
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
# d.get('Bob')
# d['Bob']


# It is important to note that there is no relationship between the order in which dict s are stored and the order in which key s are placed.

# Compared with list, dict has the following characteristics:

#     Finding and inserting are very fast and do not slow down as key s increase;
#     It takes up a lot of memory and wastes a lot of memory.

# Instead of list:

#     The time to find and insert increases with the number of elements.
#     Small footprint, little waste of memory.

# So dict is a way to exchange space for time.

# Dict can be used in many places where high-speed lookups are required, almost everywhere in Python code, and it is important to use Dict correctly. The first thing to keep in mind is that dict's key must be an immutable object.

# This is because dict calculates the storage location of the value based on the key, and if the same key is calculated differently each time, the dict is completely confused.This algorithm for calculating locations by key is called a hash algorithm (Hash).

# To ensure hash is correct, the object as key cannot be changed.In Python, strings, integers, and so on are immutable, so you can safely use them as keys.Lists are mutable and cannot be used as keys:
75
# set
# A set can be viewed as a set of disordered and unreplicated elements in a mathematical sense, so the two sets can do mathematical intersections, unions, and so on.
s1 = set([1, 1, 2, 2, 3, 3])
s2 = set([2, 3, 4, 3, 2])
print(s1)
print(s2)
print(s1 & s2)
print(s1 | s2)
{1, 2, 3}
{2, 3, 4}
{2, 3}
{1, 2, 3, 4}
# Parameters of the function
def person(name, age, *, city='Beijing', job):
    print(name, age, city, job)
person('Jack', 24, job='Engineer')


# Python's functions have a very flexible parameter form that allows for both simple calls and very complex parameters to be passed in.

# Default parameters must use mutable objects, if they are mutable objects, the program will run with logic errors!

# Note the syntax for defining variable and keyword parameters:

# *args is a variable parameter, args receives a tuple;

# **kw is a keyword parameter and kW receives a dict.

# And how to pass in variable and keyword parameters when calling a function:

# Variable parameters can be passed in either directly: func(1, 2, 3), or by assembling a list or tuple and then by *args: func(*(1, 2, 3));

# Keyword parameters can either be passed in directly: func(a=1, b=2), or dict can be assembled first and then passed in through **kw: func (**{'a': 1,'b': 2}).

# Using *args and **kw is a Python idiom and of course can use other parameter names, but it is best to use the idiom.

# Named keyword parameters are used to limit the parameter names that callers can pass in while providing default values.

# Define named keyword parameters Don't forget to write the delimiter * without variable parameters, otherwise the positional parameters will be defined.
Jack 24 Beijing Engineer
#Recursion and its optimization
 The advantage of #regression is that it is easy to define and logical.Theoretically, all recursive functions can be written as loops, but the logic of loops is not as clear as recursion.
#Use of recursive functions requires attention to prevent stack overflow.In computers, function calls are made through a data structure called stack, which adds a layer of stack frames whenever a function call is entered.
#Each time the function returns, the stack is reduced by one stack frame.Because the stack size is not infinite, too many recursive calls can cause the stack to overflow.
#The way to resolve the stack overflow of recursive calls is through tail recursion optimization, which in fact has the same effect as a loop, so it is also possible to think of a loop as a special tail recursive function.
Tail recursion means that when a function returns, it calls itself, and the return statement cannot contain an expression.This allows the compiler or interpreter to optimize tail recursion.
#Make the recursion itself occupy only one stack frame, no matter how many calls it makes, without overflowing the stack.
When #tail recursive calls are made, the stack does not grow if optimized, so no matter how many calls there are, the stack will not overflow.
#Unfortunately, most programming languages are not optimized for tail recursion, and Java,Python interpreters are not optimized, so even changing the fact(n) function above to tail recursion will cause stack overflow.

#Application: Factorial, Fibonacci Sequence, Hannotta

Topics: Programming encoding Python ascii Java