a python road checkpoints (basic grammar)

1. What is the program? Why programming?

  A: The program is a verb, is equivalent to write programming code, then write the code is for what? That is why the program it is certainly in order to allow the computer to help us do things, the code that the computer can understand language.

 

2. What is the history of programming languages ​​evolution?

  A: The machine language ------> Assembly Language ------> high-level language 

  Machine language: Because only accept the binary code inside the computer, therefore, a binary 0 and 1 command called machine instructions described in the machine language of a collection of machine instructions all computers, machine language belongs to the low-level language.

  Assembly: its essence and machine language is the same, are operating directly on the hardware, but took command of the English abbreviation identifier is easier to recognize and remember.

  High-level language: it is the choice of most programmers, and compared to assembly language, he not only will many related to the synthesis of a single instruction machine instructions, and removed related to the specific operation but has nothing to do with the complete details of the work, mostly relatively high-level language in terms of assembly language, it is not specific to a certain kind of specific language, but includes a number of programming languages. Such as C / C ++, JAVA, PHP, PYTHON belong to high-level language.

  Machine language: the advantage of the lowest speed, the disadvantage is the complexity, the development of low efficiency

  Assembly: the advantage of relatively low-speed, the disadvantage is the complexity, the development of low efficiency

  High-level language: compiled language execution speed, not locale-dependent operation, cross-platform poor

       Cross-platform interpreted better, a code, everywhere, the disadvantage is the efficiency of slow, rely interpreter to run, compared to the machine and assembly language, high-level language more friendly to developers, greatly improving efficiency in the development.

 

3, outlined the difference between compiled and interpreted languages, and list the language you know what belongs compiled, interpreted those belonging

  High-level language program can not be compiled by a computer do not know, have talked about the conversion to be performed in accordance with the conversion method can be divided into two categories, one is to compile categories, one category is explained

  Compile the class : that is, before the application source code program is executed, it will be source code "translated" into object code (machine language), so that the target program can be executed independently from their locale. It is easy to use, high efficiency, but once the application needs to be modified, you must modify the source code, then recompile to generate a new target (* .obj, which is OBJ file) to perform, only the target file without source code modification Very inconvenient.

  Features : No need to re-translation program run after compiling, compiled the results directly on the line. High efficiency of program execution, depending on the compiler, cross-platform rather poor, such as C, C ++, Delphi, etc.

  Advantages: 1, when executing the program, does not require source code, language-independent environment, since the source file is performed by the machine.

     2, execution speed, since program code has been translated into a machine language understood by the computer.

  Disadvantages: 1, each modification of the source code, need to be recompiled to generate machine code files

     2, cross-platform is not good, different operating systems, different calls to the underlying machine instructions, machine code needed to generate different files for different platforms.

  

  Their Interpretation : Similar to perform the way we live in the "simultaneous translation", while the application source code "translated" by the corresponding language interpreter into object code (machine language), while execution, while the translation, the efficiency is relatively low.

  Features : Low efficiency, can not generate a separate executable file, the application can not departing from the interpreter, but this approach more flexible, can dynamically adjust, modify the application. Such as Python, Java, PHP, Ruby and other languages.

  Advantages: 1, the user calls the interpreter implementation and the source file, and can be modified at any time, immediate results, complete source code changes, run directly see the results

     2, while the interpreter to explain the source files into machine instructions, while the CPU to execute, born cross-platform, because the interpreter has already done the interactive processing of different platforms, user-written source code does not need to consider differences platform.

  Disadvantages: 1, plaintext code

     2, low operating efficiency, all the code interpreter is required to explain side edge execution, much slower than compiled.

 

4. What are two ways to execute python scripts that?

  1, the interaction is executed, temporarily run the code entered on the console

  2, file operations, do a good save py file

  The difference is: one is the memory operation, a hard disk operations,

  Memory features are: fast read speed, but power outages lose data

  Hard disk features are: slow, but you can save data

 

5. What are the precautions to declare variables?

  Variables defined rules:

    1, the variable name can be any combination of letters, numbers or underscore

    2, the first character variable names can not be digital

    3, life can not ask the variable name keywords

  Precautions:

    1, the variable name can not be too long

    2, the variable is not up to the meaning of the term

    3, the variable named Chinese, Pinyin

 

 6. What is a constant?

  Constant refers to the amount of change, or not change during program execution in the amount of

  Not a special representative of the constants in python syntax, programmers convention with representatives constant variable name in all caps

 

7, python's single-line and multi-line comments are what?

  # Single line comment Multiline comments "" "

  Code comments principles:

    1, not all add comments, or just need to find it difficult to understand the important part to add a comment to their own

    2, Notes can use Chinese or English, but never Pinyin

 

8, Boolean values ​​What?

  Boolean very simple, two values, one is True (true), a is False (false), the main logic determines

 

9, how to view the variable address in memory?

Here the id

print(id.__doc__)
Return the identity of an object.
This is guaranteed to be unique among simultaneously existing objects.
(CPython uses the object's memory address.)

 

10, write code

  10-1, to achieve the user to enter a user name when the user name is james, and the password is 123456, show successful landing, otherwise the login failed.

= _username "james" 
_password = "123456" 
username = the INPUT ( "Please enter the name >>>") 
password = the INPUT ( "Please enter your password >>>") 
 
IF username and password username == == _ _ password: 
    Print ( " the successful landing ") 
the else: 
    Print (" login failed ")

  10-2, to achieve the user to enter a user name when the user name is james, and repeated three times password is 123456, show successful landing, otherwise failed on landing, the number of failures allowed

= _username "james" 
_password = "123456" 
 
COUNT = 0 
 
the while COUNT <3: 
    username = the INPUT ( "Please enter the name >>>") 
    password = the INPUT ( "Please enter your password >>>") 
    IF username and username == _ == _ password password: 
        Print ( "successful landing") 
        BREAK 
    the else: 
        Print ( "login failed") 
    COUNT = 1 +

  10-3, to achieve the user to enter a user name when the user name is james, or the password is 123456, show successful landing, otherwise failed on landing, the number of failures allowed in triplicate

= _username "james" 
_password = "123456" 
 
COUNT = 0 
 
the while COUNT <3: 
    username = the INPUT ( "Please enter the name >>>") 
    password = the INPUT ( "Please enter your password >>>") 
    IF == _ username or username == _ password password: 
        Print ( "successful landing") 
        BREAK 
    the else: 
        Print ( "login failed") 
    COUNT = 1 +

 

11, write code

a, while loop implemented using a 2-3 + 4-5 + 100 and + 6 ....

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

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

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

C, while loop output 100-50, descending, such as 100,99,98 ..., 50 to re-output the time cycle from 0 to 50, and then ends

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

d, while loop implemented using the output of all odd 1-100

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

e, while loop implemented using the outputs of all the even 1-100

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

 

12, the programming problem: input a year, it is determined whether the leap year and the output

(Note leap year conditions: 1, evenly divisible by four but not divisible by one hundred, 2, can be divisible by four hundred)

Number == 0. 4% IF and Number% Number% 100 = 400 or 0 == 0:! 
    Print ( "% S is a leap"% number) 
the else: 
    Print ( "% S not leap"% number)

 

13, the programming problem: Suppose a regular one-year interest rate of 3.24%, calculate how many years to go through a million year time deposit with interest to double?

money =10000
rate = 0.0324
years =0
while money <20000:
    years+=1
    money  = money*(1+rate)
print(str(years))

 

14. What is the operator?

There are operations that can be performed a variety of computer, can be more than simple addition, subtraction, according to the type of operation can be divided into arithmetic, comparison operations, logical operators, assignment operators, members of the operation, operation status, bit operation, etc.

Following is a brief arithmetic operations, comparison operations, logical operations, assignment operator

 

 

15. What is the loop termination statement?

  If in the course of the cycle, for some reason, you do not want to continue the cycle, how to terminate it off it? This uses a break or continue statement

  end of a break for complete cycle, back out of the loop execution loop

  continue和break有点类似,区别在于continue只是终止本次循环,接着还执行后面的循环,break则完全终止循环

 

16,python中断多重循环的方法exit_flag

常见的方法:
exit_flag = flase
for 循环:
    for 循环:
        if 条件
            exit_flag = true
            break   #跳出里面的循环
        if exit_flag:
            break  #跳出外面的循环

 

17,基本数据类型和扩展数据类型的分类?

基本数据类型:

  可变数据类型:列表,字典,集合

  不可变数据类型:字符串,元组,数字

扩展性数据类型:

  1,namedtuole():生成可以使用名字来访问元素内容的tuple子类

  2,deque:双端队列,可以快速的从另一侧追加和推出对象

  3,counter:计数器,主要用来计数

  4,orderdict:有序字典

  5,defaultdict:带有默认值的字典

 

18,元组的特点和功能

特点:

  不可变,所以又称只读列表

  本身不可变,但是如果元祖中还包含了其他可变元素,这些可变元素可以改变

功能:

  索引

  count

  切片

 

19,简单讲一下hash

  hash,一般翻译做“散列”,也有直接音译为“哈希”的,就是把任意长度的输入,通过散列算法,变化成固定长度的输出,该输出就是散列值,这种转换是一种压缩映射,也就是,散列值的空间通常远小于输入的空间,不同的输入可能散列成相同的输出,所以不可能从散列值来唯一的确定输入值,简单的说就是有一种将任意长度的消息压缩到某一固定长度的函数。

  特性:hash值的计算过程是依据这个值的一些特性计算的,这就要求被hash的值必须固定,因此被hash的值是不可变的。

 

20,为什么使用16进制

  1,计算机硬件是0101二进制,16进制刚好是2的倍数,更容易表达一个命令或者数据,十六进制更简短,因为换算的时候一位16进制数可以顶4位二进制数,也就是一个字节(8位进制可以用两个16进制表示)

  2,最早规定ASCII字符采取的就是8bit(后期扩展了,但是基础单位还是8bit),8bit用两个16进制直接就能表达出来,不管阅读还是存储逗逼其他进制更方便。

  3,计算机中CPU计算也是遵循ASCII字符串,以16,32,64这样的方法在发展,因此数据交换的时候16进制也显得更好

  4,为了统一规范,CPU,内存,硬盘我们看到的都是采取的16进制计算

 

21,字符编码转换总结

python2.x

    内存中字符默认编码是ASCII,默认文件编码也是ASCII

    当声明了文件头的编码后,字符串的编码就按照文件编码来,总之,文件编码是什么,那么python2.x的str就是什么

    python2.x的unicode是一个单独的类型,按u"编码"来表示

    python2.x  str==bytes,bytes直接是按照字符编码存成2进制格式在内存里

python3.x

    字符串都是unicode

    文件编码都默认是utf-8,读到内存会被python解释器自动转成unicode

    bytes和str做了明确的区分

    所有的unicode字符编码后都会编程bytes格式

 

22,请用代码实现,查找列表中元素,移除每个元素的空格,并查找以a或者A开头并且以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,利用for循环和range输出9*9乘法表

for i in range(1,10):
    for j in range(1,i+1):
        print(str(i)+"*"+str(j) +"="+str(i*j),end=' ')
    print( )

 

24,利用for循环和range循环输出:

  1,for循环从大到小输出1-100

  2,for循环从小到大输出100-1

  3,while循环从大到小输出1-100

  4,while循环从小到大输出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 =1
while i<101:
    print(i)
    i+=1
 
i =100
while i>0:
    print(i)
    i-=1

 

25,有两个列表,l1和l2   l1 =[11,22,33]     l2 = [22,33,44]

  1,获取内容相同的元素列表

  2,获取l1中有,l2中没有的元素

  3,获取l2中有,l1中没有的元素

  4,获取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 l1:
   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,列举布尔值为False的所有值

  所有标准对象均可用于布尔测试,同类型的对象之间可以比较大小,每个对象天生具有布尔值,空对象,值为0的任何数字或者Null对象None的布尔值都是False

下面对象的布尔值为False:
        所有值为0的数
        0(整数)
        0(浮点数)
        0L(长整形)
        0.0+0.0j(复数)
        “”(空字符串)
        [](空列表)
        ()(空元组)
        {}(空字典)

  值不是上面列出来的都是True.

 

27,输入商品列表,用户输入序号,显示用户选中的商品,商品=【‘手机’,‘电脑’,‘电视’,‘冰箱’】允许用户添加内容,用户输入序号显示内容

print("输出商品列表,用户输入序号,显示用户选中的商品")
li = ["手机", "电脑", '鼠标垫', '游艇']
for i,j in enumerate(li,1): #自定义列表索引下标,从1开始,将列表索引下标赋值给i,将列表值赋值给j
    print(i,j)#打印出列表的索引下标,和列表的值
a = input("请输入商品序号") #要求用户输入商品序号
if a.isdigit():#判断用户输入的是否是纯数字
    pass
else:
    exit("你输入的不是有效的商品序号")#如果不是纯数字打印提示信息,并且退出程序,不在往下执行
a = int(a) #将用户输入的序号转换成数字类型
b = len(li)#统计li列表的元素个数
if a > 0 and a <= b: #判断
    c = li[a-1]
    print(c)
else:
    print("商品不存在")

 

28,元素分类,有如下集合   [11,22,33,44,55,66,77,88,99],将所有大于66的值保存到第一个key的值中,将所有小于66的值保存到第二个key的值中,{'k1':大于66的值,‘k2’:‘小于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,元素分类,有如下集合   [11,22,33,44,55,66,77,88,99],将所有大于66的值保存到一个列表,小于66的保存到另一个列表

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)
    else:
        c.append(i)
print(b)
print(c)

 

30,查找列表,元组,字典,中元素,移除每个元素的空格,并查找以 a或A开头 并且以 c 结尾的所有元素。

  li = ["alec", " aric", "Alex", "Tony", "rain"]
  tu = ("alec", " aric", "Alex", "Tony", "rain") 
  dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}
print("查找列表中元素,移除每个元素的空格,并查找以 a或A开头 并且以 c 结尾的所有元素。")
li = ["aleb", " aric", "Alex", "Tony", "rain"]
for i in li:
    b = i.strip() #移除循环到数据的两边空格
    #判断b变量里以a或者A开头,并且以c结尾的元素
    #注意:如果一个条件语句里,or(或者),and(并且),都在条件判断里,将前面or部分用括号包起来,当做一个整体,
    #不然判断到前面or部分符合了条件,就不会判断and后面的了,括起来后不管前面符不符合条件,后面的and都要判断的
    if (b.startswith("a") or b.startswith("A")) and b.endswith("c"):
        print(b) #打印出判断到的元素
tu = ("aleb", " aric", "Alex", "Tony", "rain")
for i in tu:
    b = i.strip()
    if (b.startswith('a') or b.startswith("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,写代码:有如下列表,请按照功能要求实现每一功能

  li=['hello','seveb',['mon',['h','key'],'all',123,446]

  1,请根据索引输出'kelly’

  2,请使用索引找到”all“元素,并将其修改为”ALL“,如”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)<br>li[2][index] ="ALL"<br>print(li)

 

32,写代码,要求实现下面每一个功能

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

  1,计算列表长度并输出

  2,列表中追加元素“servn",并输出添加后的列表

  3,请在列表的第一个位置插入元素‘tony’,并输出添加后的列表

  4,请修改列表位置元素‘kelly’,并输出修改后的列表

  5,请在列表删除元素‘eric’,并输出删除后的列表

  6,请删除列表中的第2个元素,并输出删除后的元素的值和删除元素后的列表

  7,请删除列表中的第三个元素,并输出删除后的列表

  8,请删除列表的第2到4个元素,并输出删除元素后的列表

  9,请用for len range输出列表的索引

  10,请使用enumrate输出列表元素和序号

  11,请使用for循环输出列表中的所有元素

li = ['alex','eric','rain']
# 1,计算列表长度并输出
# print(len(li))
# 列表中追加元素“seven”,并输出添加后的列表
# li.append('seven')
# print(li)
# 请在列表的第1个位置插入元素“Tony”,并输出添加后的列表
# li.insert(1,'tony')
# print(li)
#请修改列表第2个位置的元素为“Kelly”,并输出修改后的列表
# li[1] ='kelly'
# print(li)
# 请删除列表中的元素“eric”,并输出修改后的列表
# a =li.pop(2)
# print(li)
# li.remove('eric')
# print(li)
# 请删除列表中的第2个元素,并输出删除元素后的列表
# b =li.pop(1)
# print(b)
# print(li)
# 请删除列表中的第2至4个元素,并输出删除元素后的列表
# c = li[2:4]
# d = set(li)-set(c)
# # print(list(d))
# del li[1:4]
# print(li)
# 请将列表所有的元素反转,并输出反转后的列表
# e = li.reverse()
# print(li)
# 请使用for、len、range输出列表的索引
# for i in range(len(li)):
#     print(i)
# 请使用enumrate输出列表元素和序号(序号从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,写代码,有如下元组,请按照功能要求实现每一个功能

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

  1,计算元组的长度并输出

  2,获取元祖的第二个元素,并输出

  3,获取元祖的第1-2个元素,并输出

  4,请用for输出元祖的元素

  5,请使用for,len,range输出元组的索引

  6,请使用enumerate输出元组元素和序号,(从10开始)

tu = ('alex','eric','rain')
#   1,计算元组的长度并输出
print(len(tu))
#   2,获取元祖的第二个元素,并输出
print(tu[1])
#   3,获取元祖的第1-2个元素,并输出
print(tu[0:2])
#   4,请用for输出元祖的元素
for i in tu:
    print(i)
#   5,请使用for,len,range输出元组的索引
for i in range(len(tu)):
    print(i)
#   6,请使用enumerate输出元组元素和序号,(从10开始)
for index,i in enumerate(tu,10):
    print(index,i)

 

34,有如下变量,请实现要求的功能

  tu=("alex",[11,22,{"k1":'v1',"k2":["age","name"],"k3":(11,22,33)},44])

  a.讲述元祖的特性
  答:元组具有列表的全部特性,不同的是,元组的元素不能修改

 

  b.请问tu变量中的第一个元素“alex”是否可被修改?
  答:不能


  c.请问tu变量中的"k2"对应的值是什么类型?是否可以被修改?如果可以,请在其中添加一个元素“Seven”

  答:列表 ,可以

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

  d.请问tu变量中的"k3"对应的值是什么类型?是否可以被修改?如果可以,请在其中添加一个元素“Seven”

  答: 元组,不能

 

35,练习字典

  dic={'k1':"v1","k2":"v2","k3":[11,22,33]}

  a.请循环输出所有的key

  b.请循环输出所有的value

  c.请循环输出所有的key和value

  d.请在字典中添加一个键值对,"k4":"v4",输出添加后的字典

  e.请在修改字典中“k1”对应的值为“alex”,输出修改后的字典

  f.请在k3对应的值中追加一个元素44,输出修改后的字典

  g.请在k3对应的值的第1个位置插入个元素18,输出修改后的字典

dic={'k1':"v1","k2":"v2","k3":[11,22,33]}
#   a.请循环输出所有的key
for i in dic :
    print(i)
for i in dic.keys():
    print(i)
#   b.请循环输出所有的value
for i in dic.values():
    print(i)
#  c.请循环输出所有的key和value
for i,j in dic.items():
    print(i,j)
#   d.请在字典中添加一个键值对,"k4":"v4",输出添加后的字典
dic2 = {'k4':'v4'}
dic.update(dic2)
print(dic)
dic['k4'] = 'v4'
print(dic)
 
#   e.请在修改字典中“k1”对应的值为“alex”,输出修改后的字典
dic['k1'] ='alex'
print(dic)
#   f.请在k3对应的值中追加一个元素44,输出修改后的字典
dic['k3'].append(44)
print(dic)
#   g.请在k3对应的值的第1个位置插入个元素18,输出修改后的字典
dic['k3'].insert(0,18)
print(dic)

Guess you like

Origin www.cnblogs.com/tu240302975/p/12328150.html