Python foundation -- variable and variable, conditional, in, is, process control if

Today's test

1. Simply describe the storage of a variable x=10 in the heap area of the stack area in memory. Stack area: storage is the corresponding relationship between the variable name and the memory address, so it can be simply understood as: variable name is stored in the memory address heap area: it stores the variable value
Emphasis: we only talk about one thing from the perspective of variable name. The assignment of variable name (x=y) and the transfer parameter of variable name (print(x)) transfer the data of stack area, and the data of stack is the corresponding relationship between variable name and memory address, or the reference to value
python is reference passing

Example 1:
       x=10
       y=20
       x=y
   Example 2:
       l=[111,222,333]
       l1=[22222222,333333333,4444444]
		l2=l

2. Briefly describe what is a direct reference and what is an indirect reference
Direct reference refers to the memory address directly referenced from the stack area. Indirect reference refers to the memory address that can only be reached through further reference after starting from the stack area and referring to the heap area.
3. Briefly describe the reference counting, mark clearing and generation recycling of python interpreter garbage collector
Garbage collection mechanism (GC for short) is a machine provided by Python interpreter, which is specially used to recover the memory space occupied by unavailable variable values. Python GC module mainly uses "reference counting" to track and collect garbage. On the basis of reference counting, you can also solve the problem of circular references that may be generated by container objects through mark and sweep, and further improve the efficiency of garbage collection by exchanging space for time through generation collection.
Reference count is the number of times the variable value is associated with the variable name
Mark / clear: when the available memory space of the application is exhausted, the whole program will be stopped, and then two tasks will be carried out, the first is mark and the second is clear
The core idea of generational recycling is: if there is no recycled variable after multiple scans, the gc mechanism will think that the variable is a common variable, and the frequency of gc scanning will be reduced. The specific implementation principles are as follows: 1 Generation refers to dividing variables into different levels (i.e. different generations) according to survival time. 2 The newly defined variable is placed in the level of Cenozoic generation. It is assumed that the Cenozoic generation is scanned every 1 minute. If it is found that the variable is still referenced, the
4. Write a program to receive the user name, age and gender entered by the user, and then select the best format string and output it in the following format

My name is: xxx
	My age is: xxx
	My gender is: xxx


	Format output
	    %
	    str.format()
	    f''

5. Arithmetic operator correlation

/
   	//
   	Demonstrate with examples
   		Modular operation
   		
   		augmented assignment 
   			age += 1 # age = age + 1
   		Cross assignment
   			x,y=y,x
   		Chained assignment 
   			x=y=z=10
   		Decompression assignment
   			x,y,*_,z=[10,20,30,40,50]
   			_,_,*m,_=[10,20,30,40,50]

Knowledge supplement

l = [111, 222, 333]
l2 = l  # Give the memory address of l to l2


l[0] = 'balabla'
print(l)

print(l2)

l2[1] = 4444444444444
print(l2)
print(l)

del l2

Format output
print('my name is %s age is %s' % ('egon', 18))
print('Probability of success %s%% ' % (97,))

"""
name:{}
age:{}
sex:{}
""".format('egon', 18, 'male')

"""
name:{x}
age:{y}
sex:{z}
""".format(z='male', x='egon', y=18)

format newly added(understand): 
print('{x}=============='.format(x='Start execution'))  # Start execution******
print('{x:=<10}'.format(x='Start execution'))  # Start execution******
print('{x:=>10}'.format(x='Start execution'))  # Start execution******
print('{x:=^10}'.format(x='Start execution'))  # Start execution******

rounding
# Accurate to 3 decimal places and rounded to the nearest 3 decimal places, the result is 1232132.124
print('{salary:.3f}'.format(salary=1232132.12351))


x = 'egon'
y = 18
res = f'name:{x} age {y}'
print(res)


x = 'egon'
y = 18
res = f'name:{{{x}}} age {y}'
print(res)

understand f New usage of:{}Strings within can be run as expressions
res = f'{10+3}'
print(res)

f'{print("aaaa")}'

Today's content

1: Variable immutable type

2,What are the conditions? What can be used as a condition? Why use conditions?
    Explicit Boolean: True,False
    Implicit Boolean: all data types, where 0 None,Null is false

3: Logical operators: used to
    # not, and , or
    # Prioritization: not > and > or

4,member operator 

5,Identity operator

6,Process control if judge

Details of today's content

Variable immutable type

Variable type: value change, id Unchanged, prove that the original value is changed, and prove that the original value can be changed
 Immutable type: value change, id It also changes. It is proved that a new value is generated, and the original value is not changed at all. It is proved that the original value cannot be modified

verification

int is an immutable type

x = 10
print(id(x))
x = 11  # Generate new value
print(id(x))
The result is variable id Changed

float is an immutable type

x = 3.1
print(id(x))
x = 3.2
print(id(x))

str is an immutable type

x = "abc" print(id(x)) x = 'gggg' print(id(x))

Summary: int,float,str Are designed as an indivisible whole and cannot be changed

list is a variable type

l = ['aaa', 'bbb', 'ccc']
print(id(l))
l[0] = 'AAA'
print(l)
print(id(l))

dict

dic = {'k1': 111, 'k2': 222}
print(id(dic))
dic['k1'] = 3333333333
# print(dic)
print(id(dic))

bool immutable

About dictionary supplement:

definition:{}Separate multiple with commas inside key: value,
among value Can be any type
 however key Must be an immutable type

dic = {
    'k1': 111,
    'k2': 3.1,
    'k3': [333, ],
    'k4': {'name': 'egon'}
}

dic = {
    2222: 111,
    3.3: 3.1,
    'k3': [333, ],
    'k4': {'name': 'egon'}
}
print(dic[3.3])

dic = {[1, 2, 3]: 33333333}
dic = {{'a': 1}: 33333333}

condition

What are the conditions? What can be used as a condition? Why use conditions?

The first category: explicit Boolean

The condition can be: comparison operator
age = 18
print(age > 16)  # After conditional judgment, you will get a Boolean value

The conditions can be: True,False
is_beautiful = True
print(is_beautiful)

The second category: implicit Boolean values. All values can be used as conditions

Of which 0 None,empty(Empty string, empty list, empty dictionary) =>The Boolean value represented is False,The rest is true

Logical operator

Basic use of not, and, or

not: Is to reverse the result of the immediately following condition
ps: not And the condition immediately following is an inseparable whole
print(not 16 > 13)
print(not True)
print(not False)
print(not 10)
print(not 0)
print(not None)
print(not '')

and: Logic and, and It is used to link the left and right conditions. The two conditions are True,The final result is true
print(True and 10 > 3)

print(True and 10 > 3 and 10 and 0)  # If all conditions are True, the final result will be True
print(10 > 3 and 10 and 0 and 1 > 3 and 4 == 4 and 3 != 3)  # Lazy principle

or: Logical or, or It is used to link the left and right conditions. If one of the two conditions is True,The end result is True,
Both conditions are False The final result is False
print(3 > 2 or 0)
print(3 > 4 or False or 3 != 2 or 3 > 2 or True)  # Lazy principle

Priority not > and > or

ps: 
If it's just a string alone and Links, or just a single string or Links can be calculated in sequence from left to right (lazy principle)
In case of mixed use, priority needs to be considered

res = 3 > 4 and not 4 > 3 or 1 == 3 and 'x' == 'x' or 3 > 3
print(res)

#       False                 False              False
res = (3 > 4 and (not 4 > 3)) or (1 == 3 and 'x' == 'x') or 3 > 3
print(res)


res = 3 > 4 and ((not 4 > 3) or 1 == 3) and ('x' == 'x' or 3 > 3)
print(res)

Member operators and logical operators

member operator

print("egon" in "hello egon")  # Judge whether a string exists in a large string
print("e" in "hello egon")  # Judge whether a string exists in a large string

print(111 in [111, 222, 33])  # Determine whether the element exists in the list

judge key Does it exist in the dictionary
print(111 in {"k1": 111, 'k2': 222})
print("k1" in {"k1": 111, 'k2': 222})

not in
print("egon" not in "hello egon")  # Recommended use
print(not "egon" in "hello egon")  # The logic is the same as above, but the semantics is not clear, so it is not recommended

Identity operator

is  # It determines whether the IDs are equal

if judgment of process control

print(1)
print(2)
print(3)
if condition:
    Code 1
    Code 2
    Code 3
print(4)
print(5)
'''
Grammar 1:
if condition:
    Code 1
    Code 2
    Code 3

'''
age = 60
is_beautiful = True
star = 'Horizontal seat'

if age > 16 and age < 20 and is_beautiful and star == 'Horizontal seat':
    print('I like it. Let's be together...')

print('Other codes.............')


'''
Grammar 2:
if condition:
    Code 1
    Code 2
    Code 3
else:
    Code 1
    Code 2
    Code 3
'''

age = 60
is_beautiful = True
star = 'Horizontal seat'

if age > 16 and age < 20 and is_beautiful and star == 'Horizontal seat':
    print('I like it. Let's be together...')
else:
    print('Hello, aunt. I'm teasing you. I'm deep in merit and fame')

print('Other codes.............')


'''
Grammar 3:
if Condition 1:
    Code 1
    Code 2
    Code 3
elif Condition 2:
    Code 1
    Code 2
    Code 3
elif Condition 2:
    Code 1
    Code 2
    Code 3
'''
score = 73
if score >= 90:
    print('excellent')
elif score >= 80 and score < 90:
    print('good')
elif score >= 70 and score < 80:
    print('ordinary')

improvement
score = input('Please enter your grade:')  # score="18"
score = int(score)

if score >= 90:
    print('excellent')
elif score >= 80:
    print('good')
elif score >= 70:
    print('ordinary')


'''
Grammar 3:
if Condition 1:
    Code 1
    Code 2
    Code 3
elif Condition 2:
    Code 1
    Code 2
    Code 3
elif Condition 2:
    Code 1
    Code 2
    Code 3
...
else:
    Code 1
    Code 2
    Code 3
'''
score = input('Please enter your grade:')  # score="18"
score = int(score)

if score >= 90:
    print('excellent')
elif score >= 80:
    print('good')
elif score >= 70:
    print('ordinary')
else:
    print('Bad, little garbage')

print('=====>')


'''
if nesting if
'''
age = 17
is_beautiful = True
star = 'Horizontal seat'

if 16 < age < 20 and is_beautiful and star == 'Horizontal seat':
    print('Start confessing.....')
    is_successful = True
    if is_successful:
        print('Since then, the two have lived a shameless life...')
else:
    print('Hello, aunt. I'm teasing you. I'm deep in merit and fame')

print('Other codes.............')

ore >= 80:
print('good ')
elif score >= 70:
print('normal ')
else:
print('Very bad, little garbage ')

print('=====>')

'''
If nested if
'''
age = 17
is_beautiful = True
star = 'horizontal seat'

if 16 < age < 20 and is_ Beautiful and star = = 'horizontal seat':
print('Start confessing... ')
is_successful = True
if is_successful:
print('the two will live a shameless life... ')
else:
print('Hello, aunt, I'm teasing you. I'm deep in merit and fame ')

print('Other codes... ')

Keywords: Python Back-end

Added by thirdeye on Wed, 23 Feb 2022 10:28:59 +0200