Python basic knowledge question bank

1、 Two ways to execute Python scripts

Interactive mode: command line

Under the Windows operating system, the shortcut key cmd, enter "python" to start the interactive python interpreter.

File format: python file

2、 Briefly describe the relationship between bits and bytes

A binary bit is the smallest unit of representation in the computer.

A byte is the smallest storage unit in a computer.

Binary bits=8bits=1Byte=1 byte

3、 Briefly describe the relationship between ascii, unicode, utf-8, gbk

The United States has formulated a set of character codes, and unified regulations on the relationship between English characters and binary bits. This is called ASCII code.

Unicode is a character encoding scheme developed by an international organization that can accommodate all characters and symbols in the world. Include all the symbols in the world. Each symbol is given a unique code, then the garbled problem will disappear. This is Unicode, as its name implies, this is an encoding of all symbols.

The popularity of the Internet strongly requires a unified coding method. UTF-8 is the most widely used implementation of Unicode on the Internet. One of the biggest features of UTF-8 is that it is a variable length encoding method. It can use 1 to 4 bytes to represent a symbol, and the byte length varies according to different symbols. In UTF-8, English occupies one byte, and Chinese occupies 3 bytes.

GBK: Chinese character national standard extension code, which basically uses all the Chinese characters and code points of the original GB2312-80, and covers all the Chinese characters in the original Unicode 20902. A total of 883 symbols, 21003 Chinese characters and 1894 characters are provided. Code point. Since GBK also covers all CJK Chinese characters in Unicode, it can also correspond to Unicode one-to-one. Windows default encoding GBK, Chinese occupies 2 bytes.

4、 Please write the number of digits coded with utf-8 and gbk for "Li Jie"

In utf-8, one English occupies one byte, one Chinese occupies 3 bytes, and "Li Jie" occupies 6 bytes here.

In GBK, a Chinese character occupies 2 characters, where "Li Jie" occupies 4 characters.

**5、 What are the use of Pyhton single-line comments and multi-line comments? **

Python single-line comments use #, and multi-line comments use triple quotation marks "''".

**6、 What are the precautions for declaring variables? **

Declare variables need to be assigned first. Variable names can contain letters, numbers, and underscore _. Variables cannot start with a number.

7、 How to check the address of a variable in memory?

id (variable name) #View the memory address.

**8、 What is the function of the automatically generated .pyc file when executing a Python program? **

Python saves bytecode in this way as an optimization for startup speed. The next time you run the program, if you haven't modified the source code after saving the bytecode last time, Python will load the .pyc file and skip the compilation step. When Python must be recompiled, it will automatically check the timestamp of the source file and the bytecode file: if you save the source code again, the bytecode will be automatically recreated the next time the program is run.

9、 write the code

**a. Realize that the user enters the user name and password. When the user name is seven and the password is 123, the login is successful, otherwise the login fails! **

username=input("username:")
passwd=input("passwd:")if username=="seven" and passwd=="123":print("login successful!")else:print("Login failed!")

b. Implement the user to enter the user name and password. When the user name is seven and the password is 123, the login is successful, otherwise the login fails. If it fails, it is allowed to enter three times repeatedly

count=0while True:
 username =input("username:")
 passwd =input("passwd:")if username=="seven" and passwd=="123":print("login successful!")break
 count +=1if count==3:print("Login failed!")break

10、 write the code

a. Use the while loop to achieve the sum of output 2-3 + 4-5 + 6 ... + 100

i=2
total_1=0
total_2=0while i<=100:if i%2==0:
  total_1+=i
 else:
  total_2+=-i
 i+=1
total=total_1+total_2
print(total)

b. Use for loop and range to realize the sum of output 1-2 + 3-4 + 5-6 ... + 99

total_1=0
total_2=0for i inrange(100):if i%2==1:
  total_1+=i
 else:
  total_2+=-i
total=total_1+total_2
print(total)

c. Use while loop to achieve output 1, 2, 3, 4, 5, 7, 8, 9, 11, 12

i=1while True:if i>=1 and i<=5:print(i)if i>=7 and i<=9:print(i)if i==11 or i==12:print(i)
 i+=1

d. Use a while loop to output all odd numbers within 1-100

i=1while i<=100:if i%2==1:print(i)
 i+=1

e. Use the while loop to output all even numbers within 1-100

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

11、 Write the binary representation of the numbers 5, 10, 32, and 7 respectively

Number 5: 00000101

Number 10: 00001010

Number 32: 00100000

Number 7: 00000111

12、 Briefly describe the relationship between the object and the class (anaphorically available)

A class is a collection of objects with the same data structure (attribute) and the same operation function (behavior). An object is an instance that conforms to a certain class.

**13、 There are the following two variables, please briefly describe the relationship between n1 and n2? **

n1  =  123

n2  =  123

n1 and n2 use the same memory address

Python internal optimization: The assignment variables between -5 and 157 are all the same address

**14、 There are the following two variables, please briefly describe the relationship between n1 and n2? **

n1  =  123456

n2  =  123456

n1 and n2 use different memory addresses

Python internal optimization: The assignment variables between -5 and 157 are all the same address

**15、 There are the following two variables, please briefly describe the relationship between n1 and n2? **

n1  =  123456

n2  =  n1

Use the same memory address, but the variable names are different

**16、 If there is a variable n1 = 5, please use the method provided by int to get the minimum number of binary bits that the variable can be represented by? **

3 Two binary digits, 00000101

**17、 What are the Boolean values? **

True and False

0, 1 in binary. In many cases, 0 is considered False, and all non-zeros are considered True.

18、 Read the code, please write the execution result

a  =  "alex"

b  =  a.capitalize()

print(a)

print(b)

**Please write the output result: **alex Alex #capitalize() capitalize the first letter and lowercase the other letters

19、 Write the code, there are the following variables, please implement each function as required

name  =  "  aleX"

a. Remove the spaces on both sides of the value corresponding to the name variable, and enter the removed content

name="  aleX"print(name.strip())

b. Determine whether the value corresponding to the name variable starts with "al" and output the result

name="  aleX"if name[0:2]=="al":print("True")else:print("False")

Output False
Method 2: print(name.startswith("al")) False

c. Determine whether the value corresponding to the name variable ends with "X", and output the result

name="  aleX"if name[-1]=="X":print("True")else:print("False")

Output True

Method 2: print(name.endswith("X"))     True
d.Replace &quot;l&quot; with &quot;p&quot; in the value corresponding to the name variable and output the result
name="  aleX"print(name.replace("l","p"))
Output: apeX

**e. Split the value corresponding to the name variable according to "l" and output the result. **

name="  aleX"print(name.split("l"))
Output:['  a','eX']

**f. Excuse me, what type of value is obtained after dividing e in the previous question? **

name.split("l") #Split the characters into a list with "l"

g. Capitalize the value corresponding to the name variable and output the result

name="  aleX"print(name.upper())
Output: ALEX

h. Change the value corresponding to the name variable to lowercase and output the result

name="  aleX"print(name.lower())
Output: alex

**i. Please output the second character of the value corresponding to the name variable? **

name=" aleX"print(name[1])
Output: a

**j. Please output the first 3 characters of the value corresponding to the name variable? **

name=" aleX"print(name[0:3])
Output: al

**k. Please output the last 2 characters of the value corresponding to the name variable? **

name=" aleX"print(name[-2:])
Output: eX

**l. Please output the index position of "e" in the value corresponding to the name variable? **

name=" aleX"print(name.index("e"))
Output: 3

**20、 Is the string iterable? If possible, please use for loop for each element? **

name="aleX"for i inrange(len(name)):print(name[i])

**21、 Please use code to achieve: Use underscores to splice each element of the list into a string, li = ['alex','eric','rain'] **

li=['alex','eric','rain']print('_'.join(li))
Output: alex_eric_rain

22、 Write the code, there is the following list, implement each function according to the requirements

li = ['alex', 'eric', 'rain']

**a. Calculate the length of the list and output **

li=['alex','eric','rain']print(len(li))
Output: 3

b. Add the element "seven" to the list, and output the added list

li=['alex','eric','rain']
li.append('seven')print(li)
Output:['alex','eric','rain','seven']

c. Please insert the element "Tony" at the first position of the list, and output the added list

li=['alex','eric','rain']
li.insert(0,'tony')print(li)
Output:['tony','alex','eric','rain']

d. Please modify the element in the second position of the list to "Kelly" and output the modified list

li=['alex','eric','rain']
li[1]="kelly"print(li)
Output:['alex','kelly','rain']

e. Please delete the element "eric" in the list and output the modified list

li=['alex','eric','rain']
li.pop(1)print(li)
Output:['alex','rain']
li=['alex','eric','rain']
li.remove("eric")print(li)
Output:['alex','rain']

f. Please delete the second element in the list, and output the value of the deleted element and the list after deleting the element

li=['alex','eric','rain']print(li[1])
li.pop(1)print(li)
Output: eric
[' alex','rain']

g. Please delete the 3rd element in the list, and output the deleted element list

li=['alex','eric','rain']
li.pop(2)print(li)
Output:['alex','eric']

h. Please delete the 2nd to 4th elements in the list, and output the list after deleting the elements

li=['tony','alex','eric','rain','seven']
del li[1:4]print(li)
Output:['tony','seven']

i. Please invert all the elements of the list and output the inverted list

li=['tony','alex','eric','rain','seven']
li.reverse()print(li)
Output:['seven','rain','eric','alex','tony']

j. Please use for, len, range to output the index of the list

li=['tony','alex','eric','rain','seven']for i inrange(len(li)):print(li.index(li[i]),li[i])
Output: 0 tony
  1 alex
  2 eric
  3 rain
  4 seven

**k. Please use enumerate to output the list elements and serial numbers (the serial numbers start from 100) **

li=['alex','eric','rain']for i,j inenumerate(li):print(i+100,j)
Output: 100 alex
  101 eric
  102 rain

l. Please use a for loop to output all elements of the list

li=['tony','alex','eric','rain','seven']for i inrange(len(li)):print(li[i])
Output: tony
  alex
  eric
  rain
  seven

23、 Write the code, there is the following list, please implement each function according to the functional requirements****li = ["hello",'seven', ["mon", ["h", "kelly"],'all'], 123, 446]

a. Please output "Kelly"

li =["hello",'seven',["mon",["h","kelly"],'all'],123,446]print(li[2][1][1])

b. Please use the index to find the'all' element and modify it to "ALL"

li =["hello",'seven',["mon",["h","kelly"],'all'],123,446]print(li[2][2].upper())

24、 Write code, have the following tuples, implement each function as required

tu = ('alex', 'eric', 'rain')

**a. Calculate the tuple length and output **

tu =('alex','eric','rain')print(len(tu))
Output: 3

**b. Get the second element of the tuple and output **

tu =('alex','eric','rain')print(tu[1])
Output: eric

**c. Get the 1-2 elements of the tuple, and output **

tu =('alex','eric','rain')print(tu[0:2])Output:('alex','eric')

d. Please use for to output the elements of the tuple

tu =('alex','eric','rain')for i inrange(len(tu)):print(tu[i])
Output: alex
  eric
  rain

e. Please use for, len, range to output the index of the tuple

tu =('alex','eric','rain')for i inrange(len(tu)):print(i,tu[i])
Output: 0 alex
  1 eric
  2 rain

**f. Please use enumerate to output the ancestor element and serial number (the serial number starts from 10) **

tu =('alex','eric','rain')for i,j inenumerate(tu):print(i+10,j)
Output: 10 alex
  11 eric
  12 rain

**25、 There are the following variables, please implement the required function ****tu = ("alex", [11, 22, {"k1":'v1', "k2": ["age", "name"], "k3 ": (11,22,33)}, 44])**a. Tell about the characteristics of Yuanzu

The same as the list, but the tuple is only readable and cannot be modified.

**b. Can the first element "alex" in the tu variable be modified? **

It cannot be modified. The tuple clearly stipulates that the stored data should not be modified. It can be modified after the list is forcibly changed.

c. What type is the value of "k2" in the tu variable? Can it be modified? If you can, please add an element "Seven"

k2 is a list and can be modified.

tu =("alex",[11,22,{"k1":'v1',"k2":["age","name"],"k3":(11,22,33)},44])
tu[1][2]["k2"].append("seven")print(tu)Output:('alex',[11,22,{'k1':'v1','k2':['age','name','seven'],'k3':(11,22,33)},44])

d. What type of value corresponds to "k3" in the tu variable? Can it be modified? If you can, please add an element "Seven"

k3 is a tuple and cannot be modified. The following is mandatory modification:

tu =("alex",[11,22,{"k1":'v1',"k2":["age","name"],"k3":(11,22,33)},44])
k3 is the key in the dictionary in the tuple part
tu[1][3]["k3"]=list(tu[1][3]["k3"])
tu[1][3]["k3"].append("seven")
tu[1][3]["k3"]=tuple(tu[1][3]["k3"])print(tu)

**26、 Dictionary ****dic = {'k1': "v1", "k2": "v2", "k3": [11,22,33]}**a. Please cycle through all keys

dic ={'k1':"v1","k2":"v2","k3":[11,22,33]}for key in dic.keys():print(key)
Output: k1
  k2
  k3

b. Please cycle to output all values

dic ={'k1':"v1","k2":"v2","k3":[11,22,33]}for value in dic.values():print(value)
Output: v1
  v2
     [11,22,33]

c. Please output all keys and values in a loop

dic ={'k1':"v1","k2":"v2","k3":[11,22,33]}for i ,j in dic.items():print(i,j)
Output: k1 v1
  k2 v2
  k3 [11,22,33]

d. Please add a key-value pair in the dictionary, "k4": "v4", output the added dictionary

dic ={'k1':"v1","k2":"v2","k3":[11,22,33]}
dic["k4"]="v4"print(dic)
Output:{'k1':'v1','k2':'v2','k3':[11,22,33],'k4':'v4'}

e. Please modify the value of "k1" corresponding to "alex" in the modified dictionary, and output the modified dictionary

dic ={'k1':"v1","k2":"v2","k3":[11,22,33]}
dic["k1"]="alex"print(dic)
Output:{'k1':'alex','k2':'v2','k3':[11,22,33]}

f. Please add an element 44 to the value corresponding to k3, and output the modified dictionary

dic ={'k1':"v1","k2":"v2","k3":[11,22,33]}
dic["k3"].append(44)print(dic)
Output:{'k1':'v1','k2':'v2','k3':[11,22,33,44]}

g. Please insert an element 18 in the first position of the value corresponding to k3, and output the modified dictionary

dic ={'k1':"v1","k2":"v2","k3":[11,22,33]}
dic["k3"].insert(0,18)print(dic)
Output:{'k1':'v1','k2':'v2','k3':[18,11,22,33]}

27、 Conversion****a. Convert the string s = "alex" to a list

s="alex"
s=list(s)print(type(s))
Output:<class'list'>

b. Convert the string s = "alex" to Yuanzu

s="alex"
s=tuple(s)print(type(s))
Output:<class'tuple'>

b. Convert the list li = ["alex", "seven"] into a tuple

li=["alex","seven"]
li=tuple(li)print(type(li))

Output:<class'tuple'>

c. Convert tu = ('Alex', "seven") into a list

tu =('Alex',"seven")
tu=list(tu)print(type(tu))
Output:<class'tuple'>
d.Will list li=["alex","seven"]Converted into a dictionary and the key of the dictionary starts to increase backwards from 10
li =["alex","seven"]
dir={}
a=10for i in li:
 dir[a]=i
 a+=1print(dir)
Output:{10:'alex',11:'seven'}

**28、 Transcoding ****n = "Old Boy"****a. Convert the string into utf-8 encoded bytes, and output, then convert the bytes into utf-8 encoded strings, and then Output **

n="old boys"
n1=n.encode("utf-8")print(n1)
n2=n1.decode("utf-8")print(n2)
Output: b'\xe8\x80\x81\xe7\x94\xb7\xe5\xad\xa9'
 old boys

**a. Convert the string into gbk-encoded bytes, and output, and then convert the bytes into gbk-encoded strings, and then output **

n="old boys"
n1=n.encode("gbk")print(n1)
n2=n1.decode("gbk")print(n2)
Output: b'\xc0\xcf\xc4\xd0\xba\xa2'
 old boys
More coding issues link: http://www.cnblogs.com/yuanchenqi/articles/5956943.html

29、 Find the sum of all numbers within 1-100

sum=0for i inrange(101):
 sum+=i
print(sum)
Output: 5050

30、 The element classification** has the following value set [11,22,33,44,55,66,77,88,99,90], save all values greater than 66 to the first key of the dictionary, which will be less than The value of 66 is saved to the value of the second key. **** means: {'k1': all values greater than 66,'k2': all values less than 66}**

tu=[11,22,33,44,55,66,77,88,99,90]
n1=[]
n2=[]
dir={}for i in tu:if i >66:
  n1.append(i)else:
  n2.append(i)
dir["k1"]=n1
dir["k2"]=n2
print(dir)
Output:{'k1':[77,88,99,90],'k2':[11,22,33,44,55,66]}

31、 Shopping cart **** function requirements: **** requires users to enter total assets, for example: 2000** displays a list of products, allowing users to select products according to the serial number, add to the shopping cart **** purchase, if the total amount of products is greater than The total assets indicates that the account balance is insufficient, otherwise, the purchase is successful. goods = [{"name": "Computer", "price": 1999},{"name": "Mouse", "price": 10}, {"name": "Yacht", "price": 20},{"name": "美女", "price": 998},**]**

goods =[{"name":"computer","price":1999},{"name":"mouse","price":10},{"name":"yacht","price":20},{"name":"beauty","price":998},]
goods_cart=[]while True:
 salary=input("input your salary:")if salary.isdigit():
  salary=int(salary)while True:print("Numbering","commodity","\t","price")for i inrange(len(goods)):print(i+1,"\t",goods[i]["name"],"\t",goods[i]["price"])

   choice=input(">>:").strip()if choice.isdigit():
    choice=int(choice)if choice>0 and choice<=(len(goods)-1):if salary-goods[choice-1]["price"]>=0:
      salary-=goods[choice-1]["price"]
      goods_cart.append(goods[choice])print(goods[choice-1]["name"],"Add to shopping cart and purchase successfully","Remaining balance",salary)else:print("Not enough balance to purchase,Not bad",goods[choice-1]["price"]-salary)if choice=="q":print("The product you bought is",goods_cart,"Left",salary,"yuan")breakelse:print("The product you entered does not exist!")breakprint("Welcome next time!")

Specific notes: link http://www.cnblogs.com/xuyaping/p/6639850.html

Recommended Posts

Python basic knowledge question bank
Basic knowledge of Python (1)
Python crawler basic knowledge points finishing
Python3 basic syntax
Python basic summary
Python knowledge points
Python basic operators
Python basic syntax generator
Python3 supplementary knowledge points
Python basic drawing tutorial (1)
Python advanced knowledge points
Python function basic learning
python_ crawler basic learning
Python basic data types
Basic syntax of Python
Python basic data types
Python basic syntax iteration
Python classic interview question one​
2020--Python grammar common knowledge points
Python basic syntax list production
Python basic drawing tutorial (two)
Python introductory notes [basic grammar (on)]
Python entry notes [basic grammar (below)]
Python file operation basic process analysis
Real zero basic Python development web
​Full analysis of Python module knowledge
Python basic syntax and number types