Python's path One (grammar basis)

Source: Internet
Author: User
Tags locale terminates python script

1, what is programming? Why do you want to program?

A: Programming is a verb, programming is equivalent to writing code, then write code for what? That is why programming, it must be to let the computer to help us do things, the code is the computer can understand the language.

2. What is the evolutionary history of programming languages?

Answer: machine language------> assembly language------> Advanced Language

  Machine language: Because the computer can only accept binary code, so the instructions described in binary code 0 and 1 are called machine instructions, the set of all machine instructions constitute the machine language of the computer, machine language belongs to the low-level language.

Assembly language: Its essence and machine language is the same, are directly to the hardware operation, but the instruction takes the abbreviation of the English identifier, easier to identify and memory.

High-level language: is the choice of most programmers, compared with assembly language, he not only synthesized many related machine instructions into a single instruction, and removed the details related to the operation but not the completion of the work, the high-level language is mainly relative to assembly language, it is not specifically specific language, Instead, it contains many programming languages. such as C/c++,java,php,python are high-level languages.

Machine language: The advantage is the lowest level, the speed is fast, the disadvantage is complex, the development efficiency is low

Assembly language: The advantage is the lower level, the speed is fast, the disadvantage is complex, the development efficiency is low

High-level language: The compiled language executes fast, does not depend on the language environment to run, the cross platform difference

Interpreted cross-platform is better, a code that is used everywhere, the disadvantage is that the execution is slow, dependent on the interpreter to run

Compared to the machine and assembly language, the high-level language is more friendly to developers and greatly improves the efficiency of development.

3, briefly describe the differences between compiled and interpreted languages, and list which languages you know are compiled, and those that belong to the explanatory type

High-level language programming program can not be known by the computer, you have to say that the conversion can be executed, according to the conversion mode, you can divide it into two categories, one is the compilation class, one is the interpretation of the class

  Compile class : The program source code is "translated" Into the target code (machine language) before the application code program executes, so its target program can be executed independently from its locale. The use is convenient, the efficiency is also high, but once the application needs to modify, must first modify the source code, and then recompile builds the new target (*.obj, namely obj file) to execute, only the target file but does not have the source code, the modification is very inconvenient.

  features : After compiling the program does not need to re-translate, directly using the results of the compilation is OK. High efficiency of program execution, relying on compiler, poor cross-platform, such as C,c++,delphi, etc.

Advantages: 1, when executing the program, do not need source code, do not rely on the locale, because the machine source files are executed.

2, the execution speed is fast, because the program code has been translated into machine language that the computer can understand.

Cons: 1, each time you modify the source code, you need to recompile, generate machine-encoded files

2, cross-platform is not good, different operating systems, call the bottom of the machine instructions are different, you need to generate different machine code files for different platforms.

  Interpretation class : The execution is similar to the "simultaneous translation" in our life, the application source code is "translated" by the interpreter of the corresponding language into the target code (machine language), while executing, while translating, so the efficiency is lower.

  features : low efficiency, unable to generate a standalone executable file, the application can not be separated from its interpreter, but this method is more flexible, dynamic adjustment, modify the application. such as Python,java,php,ruby and other languages.

Advantages: 1, the user invokes the interpreter, executes the source file, and can be modified at any time, immediate effect, change the source code, directly run to see the results

2, the interpreter to the source file as a machine instruction, one side to the CPU execution, natural cross-platform, because the interpreter has done a different platform for the interactive processing, user-written source code does not need to consider platform differences.

Cons: 1, code is clear text

2, the operating efficiency is low, all the code is required to interpret the side of the interpreter side execution, the speed is much slower than the compiler type.

4, what are the two ways to execute a python script?

1, interactive execution, running temporary input code on the console

2, file operation, execute a saved py file

The difference between the two is: one is memory operation, one is the hard disk operation,

Memory Features: Fast read speed, but loss of data when power is lost

Hard disk features: slow, but can save data

5. What are the considerations for declaring variables?

Variable definition rules:

1, variable names can only be any combination of letters, numbers, or underscores

2, the first character of a variable name cannot be a number

3, keyword cannot life ask variable name

Precautions:

1, variable name cannot be too long

2, variable nouns do not reach meaning

3, the variable name is Chinese, pinyin

6, what is a constant?

Constants are constant quantities, or quantities that do not change during the course of a program's operation

In Python, there is no specific syntax for constants, and programmers have used the variable names to represent constants in all capitals .

What is the single-line comment and multiline comment for 7,python?

Single line comment # Multiline comment "" "

Code Comment principle:

1, do not annotate all, just need to comment on the part that you feel important or not understand

2, comments can be in Chinese or English, but definitely not pinyin

8, what are the Boolean values, respectively?

Boolean type is simple, two values, one is true (true), one is False (false), mainly used for logical judgment

9, how do I see the address of a variable in memory?

Use ID here

Print (id.__doc__) Return the identity of an object. This was guaranteed to be unique among simultaneously existing objects. (CPython uses the object ' s memory address.)
10, write code

10-1, realize the user input user name, when the user name is James, and the password is 123456, the login is successful, otherwise the login failed.

_username = "James" _password = "123456" username = input ("Please enter name >>>") password= input ("Enter password >>>") if Username==_username and Password==_password:    print ("login Successful") Else:    print ("Login Failed")

  

10-2, the implementation of user input user name, when the user name is James, and the password is 123456, the display is successful, otherwise the login failed, the number of failures allowed to repeat three times

_username = "James" _password = "123456" Count =0while count<3:    username = input ("Please enter name >>>")    Password = input ("Please enter password >>>")    if Username==_username and Password==_password:        print ("Login successful")        Break    Else:        print ("Login Failed")    count +=1

 

10-3, the implementation of user input user name, when the user name is James, or password is 123456, the display login is successful, otherwise the login failed, the number of failures allowed to repeat three times

_username = "James" _password = "123456" Count =0while count<3:    username = input ("Please enter name >>>")    Password = input ("Please enter password >>>")    if Username==_username or Password==_password:        print ("Login successful")        Break    Else:        print ("Login Failed")    count +=1
11, write code

A, using the while loop to achieve output 2-3+4-5+6....+100 and

Count =2num =0while count<=100:    if count%2==0:        num = num+count    else:        num = num-count    count+= 1print (num)

  

b, using the while loop to implement the output 1,2,3,4,5,7,8,9,11,12

Count =1while count<=12:    if count==6 or count==10:        pass    else:        print (count)    count+=1

C, use while loop output 100-50, from large to small, such as 100,99,98 ..., to 50 and then from 0 loop output to 50, and then end

Count =100while count >:    print (count)    count-=1    if count==50: Count=1 while        count<=50:            print (count)            count+=1        break

  

D, using a while loop to implement all the odd numbers in output 1-100

Count =0while count <=100:    if Count%2!=0:        print (count)    count +=1

  

E, use the while loop to implement all the even numbers in output 1-100

Count =0while count <=100:    if Count%2==0:        print (count)    count +=1

  

12, Programming Questions: Enter a year to determine if the year is a leap years and output the results

(Note that leap year conditions: 1, can be divisible by four but not divisible by 100, 2, divisible by 400)

If number%4==0 and number%100!=0 or number%400==0:    print ("%s is leap year"%number) Else:    print ("%s is not a leap year"% number)

  

13, programming Question: Suppose that the one-year periodic interest rate is 3.24%, calculate how many years, 10,000 yuan of one-year time deposit can double the interest?
Money =10000rate = 0.0324years =0while money <20000:    years+=1    Money  = money* (1+rate) print (str (years))
14, what is an operator?

There are many kinds of computations that can be performed by computers, which can be divided into arithmetic operations by types, comparison operations, logical operations, assignment operations, member operations, identity operations, bit operations, and so on subtraction.

The following is a brief introduction to arithmetic operations, comparison operations, logical operations, assignment operations

15, what is the loop termination statement?

If, for some reason, you do not want to continue the loop during the loop, how do you stop it? It's a break or a continue statement.

Break is used to completely end a loop, jumping out of the loop body to execute the statement following the loop

Continue and break are a bit similar, the difference is that continue just terminates the loop, and then executes the subsequent loop, and break terminates the loop completely.

16,python method of interrupting multiple loops Exit_flag

Common methods: Exit_flag = Flasefor loop: For    loop:        if condition            Exit_flag = True break   #跳出里面的循环        if Exit_flag:            Break  #跳出外面的循环

17, classification of basic data types and extended data types?

Basic data type:

mutable data types: Lists, dictionaries, collections

Immutable data types: string, meta-ancestor, number

Extensibility Data types:

 1,namedtuole (): Generates a tuple subclass that can use the name to access the content of the element

2,deque: Double-ended queue that can quickly append and eject objects from the other side

3,counter: Counter, mainly used to count

4,orderdict: Ordered Dictionary

5,defaultdict: Dictionary with default values

18, the characteristics and functions of the tuple

Characteristics:

Immutable, so it's called a read-only list.

is inherently immutable, but if Yongzu also contains other mutable elements, these mutable elements can change

Function:

Index

Count

Slice

19, simply talk about the hash

Hash, the general translation to do "hash", there is a direct transliteration of "hashing", that is, arbitrary length of input, through the hashing algorithm, change to a fixed-length output, the output is a hash value, this conversion is a compression mapping, that is, the hash value of the space is usually much smaller than the input space, Different inputs may be hashed to the same output, so it is not possible to uniquely determine the input value from the hash value, simply to have a function that compresses any length of message to a fixed length.

Characteristics: The calculation process of the hash value is based on some characteristics of this value, which requires the value of the hash must be fixed, so the value of the hash is immutable.

20, why use 16 binary

1, the computer hardware is 1012 binary, 16 binary is just a multiple of 2, it is easier to express a command or data, hexadecimal is shorter, because when the conversion of a 16 binary number can be the top 4 binary number, that is, a byte (8-bit binary can be represented by two 16 binary)

2, the earliest provisions of the ASCII character to take is 8bit (late expansion, but the basic unit or 8bit), 8bit with two 16 directly can express it, no matter reading or storage tease force other into the system more convenient.

3, the CPU in the computer is also following the ASCII string, in order to 16,32,64 such a method in the development, so the data exchange when the 16-binary also appears better

4, in order to unify the specification, CPU, memory, hard disk we see the 16 binary calculations that are taken

21, character encoding conversion summary

python2.x

    In-memory characters default encoding is ASCII, the default file encoding is also ASCII

When the file header encoding is declared, the encoding of the string is according to the file encoding, in short, what the file encoding is, then python2.x str is what

python2.x Unicode is a separate type, denoted by U "Code"

python2.x str==bytes,bytes is directly stored in 2 binary format in memory by character encoding.

python3.x

    The strings are all Unicode

The file encoding is utf-8 by default, and read memory is automatically turned into Unicode by the Python interpreter

Bytes and Str make a clear distinction.

All Unicode character encodings will be programmed bytes format

22, use code to find elements in the list, remove spaces for each element, and find all elements that begin with a or a and end with C

Li =[' Alex ', ' Eric ', ' rain ']tu = (' Alex ', ' Aric ', ' Tony ', ' rain ') dic = {' K1 ': ' Alex ', ' Aroc ': ' Dada ', ' K4 ': ' Dadadad '}for i in Li:    i_new = I.strip (). Capitalize ()    if I_new.startswith (' A ') and I_new.endswith (' C '):        print (i_new) for I in Tu:    i_new0 = I.strip (). Capitalize ()    if I_new0.startswith (' A ') and I_new.endswith (' C '):        print (i_new0) for I in dic:    i_new1 = I.strip (). Capitalize ()    if I_new1.startswith (' A ') and I_new.endswith (' C '):        print (i_ NEW1)

23, using the For loop and range output 9*9 multiplication table

For I in Range (1,10):    for J in Range (1,i+1):        print (str (i) + "*" +str (j) + "=" +str (i*j), end= ')    print ()

  

24, use for loop and range loop output:

1,for cycle from large to small output 1-100

2,for cycle from small to large output 100-1

3,while cycle from large to small output 1-100

4,while cycle from small to large output 100-1

A =info.setdefault (' age ') print (a) print (info) b =info.setdefault (' Sex ') print (b) print (info) for I in Range (1,101):    Print (i) Value =list (range (1,101)) print (value) for I in Range (100,0,-1):    print (i) Value =list (range (100,1,-1)) i = 1while i<101:    print (i)    i+=1i =100while i>0:    print (i)    i-=1

25, there are two listings, L1 and L2 L1 =[11,22,33] L2 = [22,33,44]

1, get a list of elements of the same content

2, get an element that is not in the L1, L2

3, get an element that is not in the L2, L1

4, get the element that is not in L1, L2

L1 = [11,22,33]L2 = [22,33,44]a =[]for i1 in L1: for    i2 in L2:        if I1==i2:            a.append (i1) print (a) a =[]for i1 in L 1:   if I1 not in L2:            a.append (i1) print (a) a =[]for i1 in L2:   if I1 not in L1:            a.append (i1) print (a) A1 =set (L1 ) &set (L2) print (A1) A2 =set (L1) ^set (L2) print (A2)

26, enumerate all values with a Boolean value of False

All standard objects can be used for Boolean testing, and objects of the same type can be compared in size, with each object having a Boolean value, an empty object, any number with a value of 0, or a Boolean value of None for the null object is False

The following object has a Boolean value of false:        All values are 0 in number        0 (integer)        0 (floating point)        0L (long reshape)        0.0+0.0j (plural)        "" (empty string)        [] (Empty list)        () (empty tuple)        {} (Empty dictionary)

Values that are not listed above are true.

27, enter the product list, user input serial number, display the user selected goods, goods = "' phone ', ' computer ', ' TV ', ' refrigerator '" allows users to add content, user input serial number display content

Print ("Output product list, user input serial number, display user selected item") Li = ["Mobile phone", "Computer", "mouse pad", ' yacht ']for i,j in Enumerate (li,1): #自定义列表索引下标, starting from 1, assigns the list index subscript to I, Assigns the list value to the J    print (I,J) #打印出列表的索引下标, and the value of the list A = input ("Please enter the serial number") #要求用户输入商品序号if a.isdigit (): #判断用户输入的是否是纯数字    Passelse :    exit ("You are not entering a valid item number") #如果不是纯数字打印提示信息, and exit the program, do not perform a = Int (a) #将用户输入的序号转换成数字类型b = Len (li) #统计li列表的元素个数if a > 0 and a <= B: #判断    c = li[a-1]    print (c) Else:    print ("Product does not exist")

  

28, Element classification, has the following set [11,22,33,44,55,66,77,88,99], all values greater than 66 are saved to the value of the first key, all values less than 66 are saved to the value of the second key, {' K1 ': value greater than 66, ' K2 ': ' Value less than 66}

List1 = [11,22,33,44,55,66,77,88,99]b =[]c=[]for i in List1:    if i>66:        b.append (i)    else:        c.append (i) print (b) print (c) dict1 = {' K1 ': B, ' K2 ': c}

  

29, Element Classification, has the following set [11,22,33,44,55,66,77,88,99], all values greater than 66 are saved to a list, less than 66 are saved to another list

List1 = [11,22,33,44,55,66,77,88,99]dict1 = {' K1 ': {}, ' K2 ': {}}b =[]c=[]for i in List1:    if i>66:        b.append (i) C3/>else:        c.append (i) print (b) print (c)

Look for lists, tuples, dictionaries, elements, remove spaces for each element, and find all elements that begin with a or a and end with C.

Li = ["Alec", "Aric", "Alex", "Tony", "Rain"] Tu = ("Alec", "Aric", "Alex", "Tony", "rain") dic = {' K1 ': "Alex", ' K2 ': ' Aric ', ' K3 ': ' Alex ', ' K4 ': ' Tony '}
Print ("Finds elements in a list, removes spaces for each element, and finds all elements that start with a or a and end with C.) ") Li = [" Aleb "," Aric "," Alex "," Tony "," Rain "]for I in li:    b = I.strip () #移除循环到数据的两边空格    #判断b变量里以a或者A开头, and the element ending in C c2/> #注意: If a conditional statement, or (or), and (and), in the conditional judgment, the front or part is wrapped in parentheses, as a whole,    #不然判断到前面or部分符合了条件, will not judge and behind the, The    if (B.startswith ("a") or B.startswith ("a")) and B.endswith ("C"):        print (b) #, regardless of the preceding character not conforming to the condition; Print out the judged element tu = ("Aleb", "Aric", "Alex", "Tony", "Rain") for I in Tu:    b = I.strip ()    if (B.startswith (' a ') or B.start Swith ("A")) and B.endswith ("C"):        print (b) dic = {' K1 ': "Alex", ' K2 ': ' Aric ', "K3": "Alex", "K4": "Tony"}for I in Dic:
   b =dic[i].strip ()    if (B.startswith (' a ') or B.startswith ("a")) and B.endswith ("C"):        print (b)

31, write code: Like the following list, please follow the functional requirements to achieve each function

li=[' Hello ', ' seveb ', [' mon ', [' H ', ' key '], ' all ', 123,446]

1, please output ' Kelly ' according to index

2, use the index to find the "all" element and modify it to "all", such as "li[0][1][9" ...

Li =[' hello ', ' seven ', [' mon ', [' H ', ' Kelly '], ' All '],123,446]print (li[2][1][1]) print (li[2][2]) li[2][2] = "All" Print ( LI[2][2]) A = Li[2][2].upper () print (a)
Li[2][index] = "All"
Print (LI)

32, write code, required to implement each of the following functions

li=[' Alex ', ' Eric ', ' rain '

1, calculate the list length and output

2, append the element "SERVN" to the list and output the added list

3, insert the element ' Tony ' in the first position of the list, and output the added list

4, modify the list position element ' Kelly ' and output the modified list

5, please delete the element ' Eric ' in the list and output the deleted list

6, delete the 2nd element in the list, and output the value of the deleted element and the list after the element is deleted

7, delete the third element in the list and output the deleted list

8, delete the 2nd to 4th element of the list, and output the list after the delete element

9, use the for Len range to output the index of the list

10, use the Enumrate output list element and ordinal

11, use the For loop to output all the elements in the list

Li = [' Alex ', ' Eric ', ' Rain ']# 1, calculate the list length and output # print (Len (LI)) # Append the element "seven" to the list and output the added list # li.append (' seven ') # print (LI) # Please insert the element "Tony" in the 1th position of the list and output the added list # Li.insert (1, ' Tony ') # Print (LI) #请修改列表第2个位置的元素为 "Kelly" and output the modified list # Li[1] = ' Kelly ' # Print (LI) # Remove the element "Eric" from the list and output the modified list # a =li.pop (2) # Print (LI) # li.remove (' Eric ') # Print (LI) # delete the 2nd element in the list and output the list after the delete element # b =li.pop (1) # print (b) # print (LI) # delete the 2nd to 4th element in the list and output the list after the delete element # c = li[2:4]# D = Set (LI)-set (c) # # print (list (d)) # del Li [1:4]# Print (LI) # invert all the elements of the list and output the inverted list # E = Li.reverse () # Print (LI) # Use the index of the for, Len, range output List # for I in range (Len (LI)): #< C0/>print (i) # Please use the Enumrate output list element and ordinal (ordinal starting from 100) # for index in Enumerate (LI): #     Print (index) # for Index,i in enumerate ( li,100): #     print (index,i) # for I in li:#     print (i)

33, write code, have the following tuple, please follow the functional requirements to achieve each function

Tu = (' Alex ', ' Eric, ' Rain ')

1, calculates the length of the tuple and outputs

2, gets the second element of the meta-ancestor, and outputs

3, gets the 第1-2个 element of the meta-ancestor, and outputs

4, please use the for output element of the progenitor

5, use the index of the for,len,range output tuple

6, use enumerate output tuple element and ordinal, (starting from 10)

 

Tu = (' Alex ', ' Eric ', ' Rain ') # 1, calculate the length of the tuple and output print (Len (TU)) # 2, get the second element of the tuple, and output print (Tu[1]) # 3, get the 第1-2个 element of the progenitor, and output print (tu[0 : 2]) # 4, use the for output element for the elements of the ancestor for I in Tu:    print (i) # 5, use the index of the for,len,range output tuple for I in range (Len (TU)):    print (i) # 6, use Enumerate output tuple elements and ordinal, (starting from 10) for Index,i in Enumerate (tu,10):    print (index,i)

34, there are the following variables, please implement the required functions
Tu= ("Alex", [11,22,{"K1": ' V1 ', "K2": ["Age", "name"], "K3":(11,22,33)},44])

  A. Describing the characteristics of Ganso
A: Tuples have all the attributes of a list, but the elements of a tuple cannot be modified

  B. Can you tell me if the first element in the TU variable, "Alex", could be modified?
Answer: No


  C. What is the value of "K2" in the TU variable? Is it possible to be modified? If you can, add an element, "Seven", to the

A: list, you can

Tu = ("Alex", [One, one, "{" K1 ": ' V1 '," K2 ": [" Age "," name "]," K3 ": (One, one, one)}, and]) tu[1][2][" K2 "].append (" Seven ") Print (TU )

  

  D. What is the value of "K3" in the TU variable? Is it possible to be modified? If you can, add an element, "Seven", to the

A: tuples, you cannot

35, Practice Dictionary

dic={' K1 ': "v1", "K2": "V2", "K3": [11,22,33]}

A. Please loop out all the keys

B. Please loop out all the value

C. Please loop out all the keys and value

D. Add a key-value pair in the dictionary, "K4": "V4", and output the added dictionary

E. In the modified dictionary, the value of "K1" corresponds to "Alex", Output the modified dictionary

F. Please append an element 44 to the value of the K3, and output the modified dictionary

G. Insert element 18 in the 1th position of the K3 corresponding value, output the modified dictionary

dic={' K1 ': "v1", "K2": "V2", "K3": [11,22,33]}# A. Please loop out all keyfor i in dic:    print (i) for I in Dic.keys ():    print (i) # B. Please loop out all valuefor i in Dic.values ():    print (i) # C. Please loop out all keys and valuefor i,j in Dic.items ():    print (I,J) # D. Please in the dictionary Add a key-value pair, "K4": "V4", output the added dictionary Dic2 = {' K4 ': ' V4 '}dic.update (dic2) print (DIC) dic[' K4 '] = ' v4 ' Print (DIC) # E. In the Modify dictionary, "K1"   The corresponding value is "Alex", Output the modified dictionary dic[' k1 ' = ' Alex ' Print (DIC) # F. Append an element 44 to the corresponding value in the K3, output the modified dictionary dic[' K3 '].append (x) print (DIC) # G. Insert element 18 in the 1th position of the K3 corresponding value, output the modified dictionary dic[' K3 '].insert (0,18) print (DIC)

  

Python's path One (grammar basis)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.