Learn programming from python - vamei

Keywords: Python Programming less calculator

Programming and computer

Summary

Computer

Five structures of computer: input device, memory, controller, arithmetic unit, output device Memory and arithmetic unit are collectively called CPU The computer operating system is responsible for the management of computer hardware resources - > system call

programming

Programming is a way of interaction between human and computer, through which human can manipulate computer to accomplish things Programming paradigm: procedural programming, object - oriented programming, function - time programming. python is a multi - paradigm language

Language Thought (self summary)

  • From 0 to n
  • Simplicity: don't make things useless, simplify complicated things
  • Readable and easy to understand
  • Efficiency: segmentation

Programming idea

encapsulation Module is a higher level than function, file reuse

  • multiplexing
    • Symbolization provided by variables is the first step of code reuse
    • Functions encapsulate statements to realize code reuse
    • Introducing modules is file level code reuse

Features of python language

Advantages: easy to read, practical and expandable Disadvantages: not as good as C Characteristic:

  • Dynamic type: python can freely change the type of variables, so it runs slower than c
  • Strong indent: indent indicates code dependency. Big brother, little brother and classmates are especially important

The computer can do arithmetic

Numerical operation - > calculator

>>> 1+5 # plus
6
>>> 2-3 #reduce
-1
>>> 1*6 #ride
6
>>> 6/2 #Division default floating point
3.0
>>> 6.0/3 #floating-point
2.0
>>> 6/3.0 #floating-point
2.0
>>> 18//4
4
>>> 18%4 #Remainder
2
>>> 4**2 #Involution
16

Addition and multiplication of strings

>>> 'hi'*2 #String multiplication
'hihi'
>>> 'hi'+'hello' #String addition
'hihello'

Logical operation - > judge right and wrong

  • Boolean: true & false
>>> True
True
>>> False
False
  • Logical conjunction: and, or, not
>>> True and True
True
>>> False and True
False
>>> False and False
False
>>> not True
False
  • Judgment expression: equal to (= =), greater than (>), less than (<), less than or equal to, greater than or equal to, not equal to (! =)
>>> 1 == 1
True
>>> 8.0 != 8.0
False
>>> 4 < 5
True
>>> 3 <= 3
True
  • From one to many - > composite application
>>> 6>2 and 4>3 and 1>2 #Multiple sets of judgments
False
  • Operation priority problem (from high to low)
* power
 * / multiplication and division
 + + addition and subtraction
 ==> = ===========
not and or logic

In calculation, parenthesis first is omnipotent High priority first, same priority from left to right

>>> 4+2>=7 #priority order 
False
>>> 1>2 and 4<3 or 6>2
True
>>> 1>2 and (4<3 or 6>2)
False
  • Number can't judge right or wrong
>>> 4*2 and 6-3 # Number cannot be read
3
>>> 5 and 5 #Number can't be judged
5

Good computer memory

  1. Computer storage - > variable Revolution: Computer storage data is to store data in memory cells and extract data through memory address. Memory is divided into one cell, each cell has a memory address, type box and box number. But people have three problems in use. The first is that memory address is too long and hard to remember. The second is before use, Can't determine whether the box is empty? Third, the number of boxes required for different types of data is different, so it's difficult to determine the number of boxes. Therefore, a variable is invented, which stipulates that when creating variables, the computer allocates memory to empty cell cells to facilitate the loading of data. Variables of different types have different numbers of cells, and the data is extracted by variable names

It is the first step to abstract thinking that variable names directly participate in the operation. Mathematically, the way that symbols replace numbers is called algebra. The symbolic expression provided by variables is the first step of code reuse

>>> wood =5 # =Representation assignment
>>> wood = wood+5 # The computer first performs the operation to the right of the assignment symbol,
>>> print(wood)
10
>>> 6 = n #The left side of assignment number can only be variable name, assignment statement
SyntaxError: can't assign to literal
  1. Type of variable - > determined by data
  • Data type: integer, float, string, Boolean
>>> a = 100 #int
>>> b = 100.0 #float
>>> a = 'abc' #str, string is a string
>>> a = True #bool

The type of variables in python can be changed freely. The type of variables is determined by the stored data. It is called dynamic type

  • Variable type: single capacity variable, multi capacity variable: list (list), tuple (tuple), dict (Dictionary)
  1. Using variables
    1. Naming: naming rules of variables: letters, numbers, underscores, beginning of letters. In order to increase readability, variable names should have meaning. They cannot be the same as 31 keywords
>>> import keyword
>>> print (keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
2. Assignment statement: the assignment statement first executes the right side of the equal sign, and the left side of the equal sign can only be a variable

Sequence - > store an orderly column of data

  • Large container. Multiple data storage. Leading out large capacity variable: Sequence & Dictionary A sequence is a data set with sequence: a row of standing soldiers. A data in a sequence is called an element. A sequence can contain multiple elements, or it can have no one element. However, empty primitives are rarely created, usually empty lists
  • Classification of sequences List, tuple Difference: Elements in the list are mutable, elements in the ancestor are immutable, and are fixed data
  • Create sequence:
>>> example_list = [True,5,'smile'] # Create list
>>> type(example_list) # View type, type() function view type
<class 'list'>
>>> example_tuple = (1,2,1.3,'love',False) #Create a ancestor
>>> type(example_tuple) #View type
<class 'tuple'>
>>> kong_list = [] #Create an empty list
  • Read data in sequence Since sequences are containers for storing data, we can read the stored data The elements in a sequence are arranged. We find the corresponding elements according to their positions. The position index of sequence elements is called index. The subscript in a sequence starts from 0 to be consistent with C language
>>> example_tuple = (1,2,1.3,'love',False) # Comma stands for juxtaposition
>>> example_tuple[0]  #Extract the first element in the ancestor
1
>>> example_list = [True,5,'smile']
>>> example_list[2] #Extract the third element in the list
'smile'
>>> nest_list = [1,[3,4,5]] #Nested list in list
>>> nest_list[1][2] #Extract the third element in the second list
5
  • Extend read data in list In addition to finding individual elements through subscripts, you can also scope references Sequence name [lower limit: upper limit: step length], excluding upper limit
 >>> example_tuple[:5] #From subscript 0 to subscript 4, excluding elements of subscript 5. A colon indicates continuation
(1, 2, 1.3, 'love', False)
>>> example_tuple[2:] #From subscript 2 to the last element
(1.3, 'love', False)
>>> example_tuple[0:5:2] #Two values per interval from elements of subscript 0,2,4
(1, 1.3, False)
>>> example_tuple[0:5:2] 
(1, 1.3, False)
>>> a = example_tuple[0:5:2] 
>>> type(a) # Scope reference result or ancestor
<class 'tuple'>
>>> a
(1, 1.3, False)
  • Syntax for tail references
>>> example_tuple[-1] # Last element of sequence
False
>>> example_tuple[1:-1] #Sequence second to last second element - > range reference does not include upper limit
(2, 1.3, 'love')
  • Data in change list Assign a value to a single element in the list by subscript. The primitive is immutable
>>> example_list[1]=3.0 #Change the second element in the list to 3.0
>>> example_list
[True, 3.0, 'smile']

Dictionary

Dictionaries are containers that can hold multiple unordered data. Dictionaries allow data to be indexed in a custom (free) way, rather than subscripts (because there is no order)

>>> example_dict={'tom':11,'sam':57,'lily':100} #Create a dictionary
>>> type(example_dict)
<class 'dict'>
>>>example_dict={'hi':16,'hello':59,'free':99} #Create a dictionary
>>>print(example_dict['hi']) #Extract dictionary elements and print values corresponding to hi
>>>example_dict['lilei']=59 #Add dictionary element
>>>print(example_dict)# Print Dictionary
>>>example_dict={}#Create an empty dictionary
16
{'hi': 16, 'hello': 59, 'free': 99, 'lilei': 59}

Generally, string is used as the key of dictionary, but other data can also be used

Computer knows choice

background

At the beginning, computer programs are executed from top to bottom in order. We need to write a large number of repeated statements. Therefore, people begin to think about ways to change the execution order of statements, so that statement execution can jump. However, people find that jump statements make the program read like noodles, which is very hard, so the main function of jump is to choose & loop, People have created the choice statement and the circulation statement, through the choice statement and the circulation statement writing, causes the computer program to enter the structured time

if structure

  • if_else statement
>>> i=3
>>> if i>2:
	print('hi')
else:
	print('why')
hi
  • supplement
  1. else statement is not required (compact)
  2. if,elif multiple selection branches, unlimited number of elif statements
  3. If nested if statement, branch selection

Computer can cycle

  • for cycle for loop function:
  1. Ergodic sequence for element in sequence & Dictionary
#Traverses the dictionary, but only extracts values
for i in {'hello':6,'hi':5}:
	print(i)
hello
hi
  1. Loop specified number range() function For I in range
#Cycle print 1 to 9
for i in range(1,10):
	print(i)
# Cycle print 0 to 4, count from 0
for i in range(5): #Count from 0
	print(i)
  1. while Loop When is followed by a conditional statement. When the condition is true, the loop will start. In the statement body, there should be a statement that changes the conditional variable to terminate the loop and avoid infinite loop
#while infinite loop
while True: 
	print('hello world')
# while condition loop
while i>2: #Infinite cycle
	print('hi')
    
i=3
while i>2:#If the condition is true, the loop will be executed. There should be statements in the statement body that make the condition false
	print(i) #Print from 3 to forever
	i=i+1  

i=9
while i>2:#Print 9 to 3
	print(i) 
	i=i-1# Make the condition false
  1. continue statement and break statement continue statement: terminate this cycle and directly next cycle break statement: directly terminate the loop
#continue: stop this cycle and enter the next cycle
# Print out 9 to 5, in a dead cycle state at 4
i=9
while i>2:#Print 9 to 5
	if i==4:
		continue
	print(i) 
	i=i-1# Make the condition false

# Print out 9 to 5, in a dead cycle state at 4
i=9
while i>2:#Print 9 to 5
	if i==4:
		continue
		i=i-1 #continue statement will not execute
	print(i) 
	i=i-1# Make the condition false


# Print out 9 to 3, no 4
i=9
while i>2:#Print 9 to 5
	if i==4:
		i=i-1 #Conditions for jumping out of the continue loop
		continue
	print(i) 
	i=i-1# Make the condition false

i=9
while i>2:#Print 9 to 5
	if i==4:
		i=i-1 #Conditions for jumping out of the continue loop
		continue
	print(i) 
	i=i-1# Make the condition false
    
# break statement jumps out of loop
#Print 9 to 5
i=9
while i>2:#Print 9 to 5
	if i==4:
		break#Jump out of circulation
	print(i) 
	i=i-1# Make the condition false

#Print 9 to 5 with hello
i=9
while i>2:#Print 9 to 5
	if i==4:
		break#Jump out of circulation
	print(i) 
	i=i-1# Make the condition false
print('hello')
while i>2:#Print 9 to 5, condition variable value needs to be set first
	if i==4:
		break#Jump out of circulation
	print(i) 
	i=i-1# Make the condition false
print('hello')

Posted by bellaso on Wed, 08 Apr 2020 00:56:54 -0700