python模块1练习题

1、 执行 Python 脚本的两种方式

1)/usr/bin/python3  xx.py
2)python3 xx.py  #注xx.py需要在内容里面调用由什么解释器执行

2、 简述位、字节的关系

1Byte = 8bit
1bit 表示某个二进制 0 1

3、 简述 ascii、unicode、utf-8、gbk 的关系

最初计算机是由美国发明的,计算机需要一套相应的字符编码集ascii,来表示英文字符
后来中国也表示也用来计算机,也需要一套字符编码集来表示汉字字符,也就是gbk
由于各国需要用计算机都需要一套相应的字符编码,来表示自已国家的字符,
于是就出现统一的字符编码的集也就是unicode,所有的字符都表示两个字节,
原来英文字符只占用一个字节,存放英文字符文档,会浪费一倍的空间,美国肯定不会同意
于是就出现了utf-8编码,可变长的字符编码,英文字符编码表示1个字节,汉字表示3个字节
这下美国就开兴了哈!

4、 请写出 “你好” 分别用 utf-8 和 gbk 编码所占的位数

你好  在utf-8中一个中文字符3个字节(Byte)  1字节 = 8位(bit) 你好就在utf-8表示24位
你好  在gbk中一个中文字符用2个字节(Byte)  1字节 = 8位(bit) 你好就在gbk中表示16位

5、 Pyhton 单行注释和多行注释分别用什么?

单行注释:用 #注释内容
多行注释:用'''注释内容'''    或者   """注释内容"""

6、 声明变量注意事项有那些?

1 变量名不能以数字开头
2 变量名只能是数字,下划线,英文字母的组合
3 变量名不能有特殊符号
4 某些特定的字符不能用做变量名

7、 如何查看变量在内存中的地址?

id(变量名)

8、 执行 Python 程序时,自动生成的  .pyc文件的作用是什么?

当执行xx.py的python会 把编译的结果会保存在位于内存中的Pycodeobject中,
python程序运行结束,python解释器则将PyCodeObject写回到pyc文件中。
当python再次执行xx.py时,首先程序会在硬盘中寻找pyc文件,直接载入,否则就重复上面的
过程
.pyc文件在_pycache_

注:自已理解,我也不是很了解

9、写代码

a.实现用户输入用户名和密码,当用户名为seven且密码为123时,
显示登陆成功,否则登陆失败!

代码如下:

user  =  "seven"
passwd = 123
username = input("please the enter user:")
password = int(input("please the enter passwd:"))
if username == user and password == passwd:
    print("logon successfull")
else:
    print("logon failed")
注意:input()输入的任何内容都是字符串
View Code

b.实现用户输入用户名和密码,当用户名为 seven且密码为 123 时,
显示登陆成功,否则登陆失败,失败时允许重复输入三次

代码如下

user  =  "seven"
passwd =  123
for i in range(3):
    username = input("please the enter user:")
    password = input("please the enter passwd:")
    if password.isdigit():
        password = int(password)
        if username == user and passwd == password:
            print("logon successfull")
            break
        else:
            print("logon failed")
    else:
        print("logon failed")
View Code

c.实现用户输入用户名和密码,当用户名为 seven 或 alex 且密码为 123 时,
显示登陆成功,否则登陆失败,失败时允许重复输入三次

代码如下:

user  =  ["seven","alex"]
passwd =  123
for i in range(3):
    username = input("please the enter user:")
    password = input("please the enter passwd:")
    if password.isdigit():
        password = int(password)
        if (username in user)  and passwd == password:
            print("logon successfull")
            break
        else:
            print("logon failed")
    else:
        print("logon failed")
View Code

10、写代码

a.使用 while 循环实现输出 2-3+4­-5+6 ...+100 的和  

代码如下:

even = 0
count = 1
while count<100:
    count+=1
    #方法1:得出偶数-奇数+偶数-奇数...
    #方法2:求出所有的偶数减去所有的奇数和 (跟小学的换位运算类似)
    if count % 2 == 0:
        print("2-100的偶数",count)
        even += count 
    else:
        print("2-100的奇数",count)
        even -= count 
print(even) #得出的结果
View Code

b.使用 for 循环和 range 实现输出1-2+3-4+5-6....-98+99  的和

代码如下:

uneven = 0  
for i in range(1,100):
    #方法1:得出的奇数-偶数+奇数-偶数....
    #方法2:求出奇数和,求出偶数和,用奇数和减偶数和
    if i % 2 == 1:
        print("1-99的奇数",i)
        uneven += i
    else:
        print("1-99的偶数",i)
        uneven -= i
print(uneven)   #得出结果
View Code

c.使用 while 循环实现输出1,2,3,4,5,7,8,9,11,12

代码如下:

count = 0
while count <12:
    count += 1
    if count == 6:
        continue
    elif count ==10:
        continue
    print(count)
View Code

d.使用 while 循环实现输出 1-100 内的所有奇数

代码如下:

count = 0
while count < 100:
    count += 1
    if count % 2 == 1:
        print("1-100的奇数",count)
View Code

e. 使用 while 循环实现输出1-100内的所有偶数

代码如下:

count = 0
while count < 100:
    count += 1
    if count % 2 == 0:
        print("1-100的偶数",count)
View Code

11、分别书写数字5,10,32,7的二进制表示

在python解释器中执行bin(number),把某个数字转换成二进制
二进制的表示:0b (binary)
bin(5)    #0b101
bin(10)  #0b1010
bin(32)  #0b100000
bin(7)    #0b111
View Code

12、简述对象和 类的关系(可用比喻的手法)

类:用来描述具有相同属性和方法的对象集合,
它定义每个对象的属性所共有的属性和方法,对象是类的实例
对象:通过类定义的数据结构实例

假如:人是一个种类,我们自已本身就是类的对象
类是一张图纸(该图纸上画了建筑的模型,以及怎样实现),实际高楼大夏就是图纸
实现的对象,
类是抽象的,对象是实际存在的。

13、现有如下两个变量,请简述 n1 和 n2是什么关系?

n1=123
n2=123 

n1和n2关系是一样 ,我们可以用id(n1),id(n2)在内存中的地址的表示

14、现有如下两个变量,请简述 n1 和 n2是什么关系?

n1 = 123456
n2 = 123456

n1和n2虽然在值是一样的,在内存地址表示中是不一样的

注:
(在python内部中,内存还有一个(小数字池,字符串池)缓存池,对于经常用的,
在python内部编译有一个优化,在这个缓存池,如果重复使用,都是使用同一内存缓存池的内存(地址)空间
如果大于这个缓存池,则会在内存独立开辟新的一个内存(地址)空间
例如
数字的缓存池 -5 至 256
可以用不相同的变量名,相同的值,用id(变量名),看它们的内存地址)

15、现有如下两个变量,请简述 n1 和 n2 是什么关系?
n1 = 123456
n2 = n1

n2 是 n1 值的引用   它们在内存的地址是一样和内容也是一样的,只是不同命名
变量的赋值:
赋值不会开辟新的内存空间,它只是复制了新对象的引用,如果n1的值发生改变,
n2还是原来的改变之前值

16、如有一下变量 n1 =5,请使用 int 的提供的方法,
得到该变量最少可以用多少个二进制位表示?

n1= 5
print(n1.bit_length())
#结果
3

 17、布尔值分别有什么?

True  False

18、阅读代码,请写出执行结果
a = "alex"
b = a.capitalize()
print(a)
print(b)
请写出输出结果:

alex    #a
Alex    #b

19、写代码,有如下变量,请按照要求实现每个功能
name = " aleX"

a. 移除 name 变量对应的值两边的空格,并输入移除有的内容

print(name.strip())
#结果
aleX
View Code

b.判断 name 变量对应的值是否以 "al" 开头,并输出结果

print(name.startswith("al"))
#结果
False
View Code

c.判断 name 变量对应的值是否以 "X" 结尾,并输出结果

print(name.endswith("X"))
#结果
True
View Code

d.将 name 变量对应的值中的 “ l” 替换为 “ p”,并输出结果

print(name.replace("l","p"))
#结果
    apeX
View Code

e.将 name 变量对应的值根据 “ l” 分割,并输出结果。

print(name.split("l"))
#结果
['\ta', 'eX']  #\t 表示使用了tab
View Code

f.请问,上一题 e分割之后得到值是什么类型?

print(type(name.split("l")))
#结果
<class 'list'> #列表
View Code

g.将 name 变量对应的值变大写,并输出结果

print(name.upper())
    ALEX
View Code

h.将 name 变量对应的值变小写,并输出结果

print(name.lower())
#结果
    alex
    
View Code

i.请输出 name 变量对应的值的第 2 个字符?

print(name[2])
#结果
l
View Code

j. 请输出 name 变量对应的值的前 3 个字符?

print(name[:3])
#结果
    al
View Code

k. 请输出 name 变量对应的值的后 2 个字符?

print(name[-2:])
#结果
eX
View Code

l.请输出 name 变量对应的值中 “ e” 所在索引位置?

print(name.index('e'))
#结果
3
View Code

 20、字符串是否可迭代?如可以请使用 for 循环每一个元素?

字符串可以迭代
代码如下:
hobby = "一条龙"
for i in hobby:
    print(i)
显示结果如下:
一
条
龙
View Code

21、请用代码实现:利用下划线将列表的每一个元素拼接成字符串,
li = ['alex', 'eric', 'rain']

print("_".join(li))
#结果
alex_eric_rain
View Code

22、写代码,有如下列表,按照要求实现每一个功能

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

a.计算列表长度并输出

print(len(li))
#结果
3
View Code

b.列表中追加元素 “seven”,并输出添加后的列表

li.append("seven")
print(li)
#结果
['alex', 'eric', 'rain', 'seven']
View Code

c.请在列表的第1个位置插入元素 “Tony”,并输出添加后的列表

li.insert(0,"Tony")
print(li)
#结果
['Tony', 'alex', 'eric', 'rain']
View Code

d.请修改列表第2个位置的元素为 “Kelly”,并输出修改后的列表

li[1] = "Kelly"
print(li)
#结果
['alex', 'Kelly', 'rain']
View Code

e.请删除列表中的元素 “eric”,并输出修改后的列表

第一种:得出“eric”索引,通过索引来删除该值
第二种:直接删除"eric"
1)
del li[1];print(li)   #结果['alex', 'rain']   
li.pop(1);print(li)   #结果['alex', 'rain']
2)
li.remove("eric")
print(li)
#结果
['alex', 'rain']     
View Code

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

print(li.pop(1));print(li)
#结果
eric
['alex', 'rain']
View Code

g.请删除列表中的第3个元素,并输出删除元素后的列表

print(li.pop(2));print(li)
#结果
rain
['alex', 'eric']
View Code

h.请删除列表中的第2至4个元素并输出删除元素后的列表

del li[1:3]
print(li)
#结果
['alex']
View Code

i.请将列表所有的元素反转,并输出反转后的列表

li.reverse()
print(li)
#结果
['rain', 'eric', 'alex']
View Code

j.请使用 for、len、range 输出列表的索引

#3种方法,建议用第三种
1)for
for i in li:
    #list.index()列表有相同元素的,只是的获取(相同元素中的第一个元素)的索引
    print(li.index(i),i)  #如果列表内有相同的元素,不建议使用此方法
#结果
0 alex
1 eric
2 rain

2)len
zero = []
for i in li:
    print(len(zero),i)
    zero.append(i)
#结果
0 alex
1 eric
2 rain

3)range
for i in range(len(li)):
    print(i,li[i])
#结果
0 alex
1 eric
2 rain
View Code

 k.请使用 enumrate 输出列表元素和序号(序号从 100 开始)

for index,i in enumerate(li,start=100):
    print(index,i)
#结果
100 alex
101 eric
102 rain
View Code

l.请使用 for 循环输出列表的所有元素

for i in li:
    print(i)
#结果
alex
eric
rain
View Code

23、写代码,有如下列表,请按照功能要求实现每一个功能
li=["hello",'seven',["mon",["h","kelly"],'all'],123,446]

a. 请输出 “Kelly”

print(li[2][1][1])
#结果
kelly
View Code

b.请使用索引找到 'all'元素并将其修改为 “ALL”

li[2][2] = "ALL"
print(li)
#结果
['hello', 'seven', ['mon', ['h', 'kelly'], 'ALL'], 123, 446]
View Code

24、写代码,有如下元组,按照要求实现每一个功能
tu=('alex','eric','rain')

a.计算元组长度并输出

print(len(tu))
#结果
3
View Code

b.获取元组的第2个元素,并输出

print(tu[1])
#结果
eric
View Code

c.获取元组的第 1-2个元素,并输出

print(tu[0:2])
#结果
('alex', 'eric')
View Code

d.请使用 for 输出元组的元素

for i in tu:
    print(i)
#结果
alex
eric
rain
View Code

e.请使用 for、len、range 输出元组的索引

#跟22题j列表用法类似
for i in range(len(tu)):
    print(i,tu[i])
#结果
0 alex
1 eric
2 rain
View Code

f.请使用 enumrate 输出元祖元素和序号(序号从 10 开始)

for index,i in enumerate(tu,start=10):
    print(index,i)
#结果
10 alex
11 eric
12 rain
View Code

25、有如下变量,请实现要求的功能
tu=("alex",[11,22,{"k1":'v1',"k2":["age","name"],"k3":(11,22,33)},44])

a.讲述元祖的特性

元祖和列表类似都是有序的从0开始
不同的是元祖的元素是不能修改的

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

不能修改

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

print(type(tu[1][2]["k2"]))
#结果
<class 'list'>
列表类型可以修改
tu[1][2]["k2"].append("seven")
print(tu)
#结果
('alex', [11, 22, {'k2': ['age', 'name', 'seven'], 'k3': (11, 22, 33), 'k1': 'v1'}, 44])
注:表面上看,tuple的元素确实变了,但其实变的不是tuple的元素,而是list的元素。
tuple一开始指向的list并没有改成别的list,所以,tuple所谓的“不变”是说,
tuple的每个元素,指向永远不变。但指向的这个list本身是可变的!
View Code

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

print(type(tu[1][2]["k3"]))
#结果
<class 'tuple'>
#对应值是元祖,不能修改
View Code

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

a.请循环输出所有的 key

for i in dic:
    print(i)
#结果
k1
k3
k2
注:字典是无序的
View Code

b.请循环输出所有的value

for i in dic:
    print(dic[i])
#结果
[11, 22, 33]
v2
v1
View Code

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

for i in dic:
    print(i,dic[i])
#结果
k2 v2
k3 [11, 22, 33]
k1 v1
View Code

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

dic["k4"] = "v4"
print(dic)
#结果
{'k4': 'v4', 'k2': 'v2', 'k3': [11, 22, 33], 'k1': 'v1'}
View Code

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

dic['k1'] = "alex"
print(dic)
#结果
{'k3': [11, 22, 33], 'k1': 'alex', 'k2': 'v2'}
View Code

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

dic["k3"].append(44)
print(dic)
#结果
{'k2': 'v2', 'k3': [11, 22, 33, 44], 'k1': 'v1'}
View Code

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

dic["k3"].insert(0,18)
print(dic)
#结果
{'k1': 'v1', 'k2': 'v2', 'k3': [18, 11, 22, 33]}
View Code

 27、转换

a.将字符串 s="alex" 转换成列表

print(list(s))
#结果
['a', 'l', 'e', 'x']
View Code

b.将字符串 s="alex" 转换成元祖

print(tuple(s))
#结果
('a', 'l', 'e', 'x')
View Code

c.将列表 li =["alex","seven"]转换成元组

print(tuple(li))
#结果
('alex', 'seven')
View Code

d.将元祖 tu =('Alex',"seven")转换成列表

print(list(tu))
#结果
['Alex', 'seven']
View Code

e.将列表 li=["alex","seven"]转换成字典且字典的key按照10开始向后递增

dic1 = {}
for key,value in enumerate(li,start=10):
    dic1[key] = value
print(dic1)
#结果
{10: 'alex', 11: 'seven'}
View Code

 28、转码

n="老男孩"

a.将字符串转换成 utf-8 编码的字节,并输出,然后将该字节再转换成 utf-8 编码字符串,再输出

print(n.encode("utf-8"))
#结果
b'\xe8\x80\x81\xe7\x94\xb7\xe5\xad\xa9'

print(n.encode("utf-8").decode("utf-8"))
#结果
老男孩
View Code

b.将字符串转换成 gbk 编码的字节,并输出,然后将该字节再转换成 gbk 编码字符串,再输出

print(n.encode("gbk"))
#结果
b'\xc0\xcf\xc4\xd0\xba\xa2'

print(n.encode("gbk").decode("gbk"))
#结果
老男孩
View Code

 29、求1-100内的所有数的和

#3种方法
1)
print(sum(range(1,101)))
#结果
5050

2)
SUM = 0
for i in range(1,101):
    SUM += i
print(SUM)
#结果
5050

3)
SUM = 0
count = 1
while count <= 100:
    SUM += count
    count += 1
print(SUM)
#结果
5050
View Code

30、元素分类

有如下值集合 [11,22,33,44,55,66,77,88,99,90],
将所有大于66的值保存至字典的第一个 key中,
将小于66的值保存至第二个 key 的值中。

即:{'k1':大于 66 的所有值,'k2':小于66 的所有值}

dic = {"k1":[],
       "k2":[]}
aa = set([11,22,33,44,55,66,77,88,99,90])
for i in aa:
    if i>= 66:
        dic["k1"].append(i)
    else:
        dic["k2"].append(i)
print(dic)
结果
{'k1': [66, 99, 77, 88, 90], 'k2': [33, 11, 44, 22, 55]}
View Code

31、购物车
功能要求:
要求用户输入总资产,例如: 2000
显示商品列表,让用户根据序号选择商品,加入购物车
购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
goods = [
{"name":"电脑","price":1999},
{"name":"鼠标","price":10},
{"name":"游艇","price":20},
{"name":"美女","price":98},
]

shop_cart = []
goods    =    [
{"name":"电脑","price":1999},
{"name":"鼠标","price":10},
{"name":"游艇","price":20},
{"name":"美女","price":98},
]
while True:
    salary = input("请输入用户余额[quit]:")
    if salary.isdigit():
        salary = int(salary)
        break
    elif salary == "quit":
        exit("不想购买")
    else:
        print("please the enter number")
while True:
    print("shop list".center(50, '*'))
    for index,i in enumerate(goods):
        print(index,i)
    choose_number = input("请输入购买商品编号[quit]:")
    if choose_number.isdigit():
        choose_number = int(choose_number)
        product_list = []
        if 0 <= choose_number <= len(goods):
            product_list.append(goods[choose_number])
            if salary >= product_list[0]["price"]:
              shop_cart.append(goods[choose_number])
              salary -= product_list[0]['price']
              print("当前购买的商品",product_list,"当前用户余额\033[1;31m{salary}\033[0m".format(salary=salary))
            else:
                print("余额不足")
        else:
            print("无效的商品编号")
    elif choose_number.lower() == 'quit':

        print("购买的商品".center(50,"*"))
        for y in shop_cart:
            print(y)
        exit()
    else:
        print("无效的输入")
#注:简易的购物车,还能继续优化
View Code

注:请各位大神指点,如有错误,请指出错误地方,我会修改!!

1、 执行 Python 脚本的两种方式

1)/usr/bin/python3  xx.py
2)python3 xx.py  #注xx.py需要在内容里面调用由什么解释器执行

2、 简述位、字节的关系

1Byte = 8bit
1bit 表示某个二进制 0 1

3、 简述 ascii、unicode、utf-8、gbk 的关系

最初计算机是由美国发明的,计算机需要一套相应的字符编码集ascii,来表示英文字符
后来中国也表示也用来计算机,也需要一套字符编码集来表示汉字字符,也就是gbk
由于各国需要用计算机都需要一套相应的字符编码,来表示自已国家的字符,
于是就出现统一的字符编码的集也就是unicode,所有的字符都表示两个字节,
原来英文字符只占用一个字节,存放英文字符文档,会浪费一倍的空间,美国肯定不会同意
于是就出现了utf-8编码,可变长的字符编码,英文字符编码表示1个字节,汉字表示3个字节
这下美国就开兴了哈!

4、 请写出 “你好” 分别用 utf-8 和 gbk 编码所占的位数

你好  在utf-8中一个中文字符3个字节(Byte)  1字节 = 8位(bit) 你好就在utf-8表示24位
你好  在gbk中一个中文字符用2个字节(Byte)  1字节 = 8位(bit) 你好就在gbk中表示16位

5、 Pyhton 单行注释和多行注释分别用什么?

单行注释:用 #注释内容
多行注释:用'''注释内容'''    或者   """注释内容"""

6、 声明变量注意事项有那些?

1 变量名不能以数字开头
2 变量名只能是数字,下划线,英文字母的组合
3 变量名不能有特殊符号
4 某些特定的字符不能用做变量名

7、 如何查看变量在内存中的地址?

id(变量名)

8、 执行 Python 程序时,自动生成的  .pyc文件的作用是什么?

当执行xx.py的python会 把编译的结果会保存在位于内存中的Pycodeobject中,
python程序运行结束,python解释器则将PyCodeObject写回到pyc文件中。
当python再次执行xx.py时,首先程序会在硬盘中寻找pyc文件,直接载入,否则就重复上面的
过程
.pyc文件在_pycache_

注:自已理解,我也不是很了解

9、写代码

a.实现用户输入用户名和密码,当用户名为seven且密码为123时,
显示登陆成功,否则登陆失败!

代码如下:

user  =  "seven"
passwd = 123
username = input("please the enter user:")
password = int(input("please the enter passwd:"))
if username == user and password == passwd:
    print("logon successfull")
else:
    print("logon failed")
注意:input()输入的任何内容都是字符串
View Code

b.实现用户输入用户名和密码,当用户名为 seven且密码为 123 时,
显示登陆成功,否则登陆失败,失败时允许重复输入三次

代码如下

user  =  "seven"
passwd =  123
for i in range(3):
    username = input("please the enter user:")
    password = input("please the enter passwd:")
    if password.isdigit():
        password = int(password)
        if username == user and passwd == password:
            print("logon successfull")
            break
        else:
            print("logon failed")
    else:
        print("logon failed")
View Code

c.实现用户输入用户名和密码,当用户名为 seven 或 alex 且密码为 123 时,
显示登陆成功,否则登陆失败,失败时允许重复输入三次

代码如下:

user  =  ["seven","alex"]
passwd =  123
for i in range(3):
    username = input("please the enter user:")
    password = input("please the enter passwd:")
    if password.isdigit():
        password = int(password)
        if (username in user)  and passwd == password:
            print("logon successfull")
            break
        else:
            print("logon failed")
    else:
        print("logon failed")
View Code

10、写代码

a.使用 while 循环实现输出 2-3+4­-5+6 ...+100 的和  

代码如下:

even = 0
count = 1
while count<100:
    count+=1
    #方法1:得出偶数-奇数+偶数-奇数...
    #方法2:求出所有的偶数减去所有的奇数和 (跟小学的换位运算类似)
    if count % 2 == 0:
        print("2-100的偶数",count)
        even += count 
    else:
        print("2-100的奇数",count)
        even -= count 
print(even) #得出的结果
View Code

b.使用 for 循环和 range 实现输出1-2+3-4+5-6....-98+99  的和

代码如下:

uneven = 0  
for i in range(1,100):
    #方法1:得出的奇数-偶数+奇数-偶数....
    #方法2:求出奇数和,求出偶数和,用奇数和减偶数和
    if i % 2 == 1:
        print("1-99的奇数",i)
        uneven += i
    else:
        print("1-99的偶数",i)
        uneven -= i
print(uneven)   #得出结果
View Code

c.使用 while 循环实现输出1,2,3,4,5,7,8,9,11,12

代码如下:

count = 0
while count <12:
    count += 1
    if count == 6:
        continue
    elif count ==10:
        continue
    print(count)
View Code

d.使用 while 循环实现输出 1-100 内的所有奇数

代码如下:

count = 0
while count < 100:
    count += 1
    if count % 2 == 1:
        print("1-100的奇数",count)
View Code

e. 使用 while 循环实现输出1-100内的所有偶数

代码如下:

count = 0
while count < 100:
    count += 1
    if count % 2 == 0:
        print("1-100的偶数",count)
View Code

11、分别书写数字5,10,32,7的二进制表示

在python解释器中执行bin(number),把某个数字转换成二进制
二进制的表示:0b (binary)
bin(5)    #0b101
bin(10)  #0b1010
bin(32)  #0b100000
bin(7)    #0b111
View Code

12、简述对象和 类的关系(可用比喻的手法)

类:用来描述具有相同属性和方法的对象集合,
它定义每个对象的属性所共有的属性和方法,对象是类的实例
对象:通过类定义的数据结构实例

假如:人是一个种类,我们自已本身就是类的对象
类是一张图纸(该图纸上画了建筑的模型,以及怎样实现),实际高楼大夏就是图纸
实现的对象,
类是抽象的,对象是实际存在的。

13、现有如下两个变量,请简述 n1 和 n2是什么关系?

n1=123
n2=123 

n1和n2关系是一样 ,我们可以用id(n1),id(n2)在内存中的地址的表示

14、现有如下两个变量,请简述 n1 和 n2是什么关系?

n1 = 123456
n2 = 123456

n1和n2虽然在值是一样的,在内存地址表示中是不一样的

注:
(在python内部中,内存还有一个(小数字池,字符串池)缓存池,对于经常用的,
在python内部编译有一个优化,在这个缓存池,如果重复使用,都是使用同一内存缓存池的内存(地址)空间
如果大于这个缓存池,则会在内存独立开辟新的一个内存(地址)空间
例如
数字的缓存池 -5 至 256
可以用不相同的变量名,相同的值,用id(变量名),看它们的内存地址)

15、现有如下两个变量,请简述 n1 和 n2 是什么关系?
n1 = 123456
n2 = n1

n2 是 n1 值的引用   它们在内存的地址是一样和内容也是一样的,只是不同命名
变量的赋值:
赋值不会开辟新的内存空间,它只是复制了新对象的引用,如果n1的值发生改变,
n2还是原来的改变之前值

16、如有一下变量 n1 =5,请使用 int 的提供的方法,
得到该变量最少可以用多少个二进制位表示?

n1= 5
print(n1.bit_length())
#结果
3

 17、布尔值分别有什么?

True  False

18、阅读代码,请写出执行结果
a = "alex"
b = a.capitalize()
print(a)
print(b)
请写出输出结果:

alex    #a
Alex    #b

19、写代码,有如下变量,请按照要求实现每个功能
name = " aleX"

a. 移除 name 变量对应的值两边的空格,并输入移除有的内容

print(name.strip())
#结果
aleX
View Code

b.判断 name 变量对应的值是否以 "al" 开头,并输出结果

print(name.startswith("al"))
#结果
False
View Code

c.判断 name 变量对应的值是否以 "X" 结尾,并输出结果

print(name.endswith("X"))
#结果
True
View Code

d.将 name 变量对应的值中的 “ l” 替换为 “ p”,并输出结果

print(name.replace("l","p"))
#结果
    apeX
View Code

e.将 name 变量对应的值根据 “ l” 分割,并输出结果。

print(name.split("l"))
#结果
['\ta', 'eX']  #\t 表示使用了tab
View Code

f.请问,上一题 e分割之后得到值是什么类型?

print(type(name.split("l")))
#结果
<class 'list'> #列表
View Code

g.将 name 变量对应的值变大写,并输出结果

print(name.upper())
    ALEX
View Code

h.将 name 变量对应的值变小写,并输出结果

print(name.lower())
#结果
    alex
    
View Code

i.请输出 name 变量对应的值的第 2 个字符?

print(name[2])
#结果
l
View Code

j. 请输出 name 变量对应的值的前 3 个字符?

print(name[:3])
#结果
    al
View Code

k. 请输出 name 变量对应的值的后 2 个字符?

print(name[-2:])
#结果
eX
View Code

l.请输出 name 变量对应的值中 “ e” 所在索引位置?

print(name.index('e'))
#结果
3
View Code

 20、字符串是否可迭代?如可以请使用 for 循环每一个元素?

字符串可以迭代
代码如下:
hobby = "一条龙"
for i in hobby:
    print(i)
显示结果如下:
一
条
龙
View Code

21、请用代码实现:利用下划线将列表的每一个元素拼接成字符串,
li = ['alex', 'eric', 'rain']

print("_".join(li))
#结果
alex_eric_rain
View Code

22、写代码,有如下列表,按照要求实现每一个功能

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

a.计算列表长度并输出

print(len(li))
#结果
3
View Code

b.列表中追加元素 “seven”,并输出添加后的列表

li.append("seven")
print(li)
#结果
['alex', 'eric', 'rain', 'seven']
View Code

c.请在列表的第1个位置插入元素 “Tony”,并输出添加后的列表

li.insert(0,"Tony")
print(li)
#结果
['Tony', 'alex', 'eric', 'rain']
View Code

d.请修改列表第2个位置的元素为 “Kelly”,并输出修改后的列表

li[1] = "Kelly"
print(li)
#结果
['alex', 'Kelly', 'rain']
View Code

e.请删除列表中的元素 “eric”,并输出修改后的列表

第一种:得出“eric”索引,通过索引来删除该值
第二种:直接删除"eric"
1)
del li[1];print(li)   #结果['alex', 'rain']   
li.pop(1);print(li)   #结果['alex', 'rain']
2)
li.remove("eric")
print(li)
#结果
['alex', 'rain']     
View Code

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

print(li.pop(1));print(li)
#结果
eric
['alex', 'rain']
View Code

g.请删除列表中的第3个元素,并输出删除元素后的列表

print(li.pop(2));print(li)
#结果
rain
['alex', 'eric']
View Code

h.请删除列表中的第2至4个元素并输出删除元素后的列表

del li[1:3]
print(li)
#结果
['alex']
View Code

i.请将列表所有的元素反转,并输出反转后的列表

li.reverse()
print(li)
#结果
['rain', 'eric', 'alex']
View Code

j.请使用 for、len、range 输出列表的索引

#3种方法,建议用第三种
1)for
for i in li:
    #list.index()列表有相同元素的,只是的获取(相同元素中的第一个元素)的索引
    print(li.index(i),i)  #如果列表内有相同的元素,不建议使用此方法
#结果
0 alex
1 eric
2 rain

2)len
zero = []
for i in li:
    print(len(zero),i)
    zero.append(i)
#结果
0 alex
1 eric
2 rain

3)range
for i in range(len(li)):
    print(i,li[i])
#结果
0 alex
1 eric
2 rain
View Code

 k.请使用 enumrate 输出列表元素和序号(序号从 100 开始)

for index,i in enumerate(li,start=100):
    print(index,i)
#结果
100 alex
101 eric
102 rain
View Code

l.请使用 for 循环输出列表的所有元素

for i in li:
    print(i)
#结果
alex
eric
rain
View Code

23、写代码,有如下列表,请按照功能要求实现每一个功能
li=["hello",'seven',["mon",["h","kelly"],'all'],123,446]

a. 请输出 “Kelly”

print(li[2][1][1])
#结果
kelly
View Code

b.请使用索引找到 'all'元素并将其修改为 “ALL”

li[2][2] = "ALL"
print(li)
#结果
['hello', 'seven', ['mon', ['h', 'kelly'], 'ALL'], 123, 446]
View Code

24、写代码,有如下元组,按照要求实现每一个功能
tu=('alex','eric','rain')

a.计算元组长度并输出

print(len(tu))
#结果
3
View Code

b.获取元组的第2个元素,并输出

print(tu[1])
#结果
eric
View Code

c.获取元组的第 1-2个元素,并输出

print(tu[0:2])
#结果
('alex', 'eric')
View Code

d.请使用 for 输出元组的元素

for i in tu:
    print(i)
#结果
alex
eric
rain
View Code

e.请使用 for、len、range 输出元组的索引

#跟22题j列表用法类似
for i in range(len(tu)):
    print(i,tu[i])
#结果
0 alex
1 eric
2 rain
View Code

f.请使用 enumrate 输出元祖元素和序号(序号从 10 开始)

for index,i in enumerate(tu,start=10):
    print(index,i)
#结果
10 alex
11 eric
12 rain
View Code

25、有如下变量,请实现要求的功能
tu=("alex",[11,22,{"k1":'v1',"k2":["age","name"],"k3":(11,22,33)},44])

a.讲述元祖的特性

元祖和列表类似都是有序的从0开始
不同的是元祖的元素是不能修改的

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

不能修改

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

print(type(tu[1][2]["k2"]))
#结果
<class 'list'>
列表类型可以修改
tu[1][2]["k2"].append("seven")
print(tu)
#结果
('alex', [11, 22, {'k2': ['age', 'name', 'seven'], 'k3': (11, 22, 33), 'k1': 'v1'}, 44])
注:表面上看,tuple的元素确实变了,但其实变的不是tuple的元素,而是list的元素。
tuple一开始指向的list并没有改成别的list,所以,tuple所谓的“不变”是说,
tuple的每个元素,指向永远不变。但指向的这个list本身是可变的!
View Code

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

print(type(tu[1][2]["k3"]))
#结果
<class 'tuple'>
#对应值是元祖,不能修改
View Code

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

a.请循环输出所有的 key

for i in dic:
    print(i)
#结果
k1
k3
k2
注:字典是无序的
View Code

b.请循环输出所有的value

for i in dic:
    print(dic[i])
#结果
[11, 22, 33]
v2
v1
View Code

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

for i in dic:
    print(i,dic[i])
#结果
k2 v2
k3 [11, 22, 33]
k1 v1
View Code

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

dic["k4"] = "v4"
print(dic)
#结果
{'k4': 'v4', 'k2': 'v2', 'k3': [11, 22, 33], 'k1': 'v1'}
View Code

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

dic['k1'] = "alex"
print(dic)
#结果
{'k3': [11, 22, 33], 'k1': 'alex', 'k2': 'v2'}
View Code

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

dic["k3"].append(44)
print(dic)
#结果
{'k2': 'v2', 'k3': [11, 22, 33, 44], 'k1': 'v1'}
View Code

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

dic["k3"].insert(0,18)
print(dic)
#结果
{'k1': 'v1', 'k2': 'v2', 'k3': [18, 11, 22, 33]}
View Code

 27、转换

a.将字符串 s="alex" 转换成列表

print(list(s))
#结果
['a', 'l', 'e', 'x']
View Code

b.将字符串 s="alex" 转换成元祖

print(tuple(s))
#结果
('a', 'l', 'e', 'x')
View Code

c.将列表 li =["alex","seven"]转换成元组

print(tuple(li))
#结果
('alex', 'seven')
View Code

d.将元祖 tu =('Alex',"seven")转换成列表

print(list(tu))
#结果
['Alex', 'seven']
View Code

e.将列表 li=["alex","seven"]转换成字典且字典的key按照10开始向后递增

dic1 = {}
for key,value in enumerate(li,start=10):
    dic1[key] = value
print(dic1)
#结果
{10: 'alex', 11: 'seven'}
View Code

 28、转码

n="老男孩"

a.将字符串转换成 utf-8 编码的字节,并输出,然后将该字节再转换成 utf-8 编码字符串,再输出

print(n.encode("utf-8"))
#结果
b'\xe8\x80\x81\xe7\x94\xb7\xe5\xad\xa9'

print(n.encode("utf-8").decode("utf-8"))
#结果
老男孩
View Code

b.将字符串转换成 gbk 编码的字节,并输出,然后将该字节再转换成 gbk 编码字符串,再输出

print(n.encode("gbk"))
#结果
b'\xc0\xcf\xc4\xd0\xba\xa2'

print(n.encode("gbk").decode("gbk"))
#结果
老男孩
View Code

 29、求1-100内的所有数的和

#3种方法
1)
print(sum(range(1,101)))
#结果
5050

2)
SUM = 0
for i in range(1,101):
    SUM += i
print(SUM)
#结果
5050

3)
SUM = 0
count = 1
while count <= 100:
    SUM += count
    count += 1
print(SUM)
#结果
5050
View Code

30、元素分类

有如下值集合 [11,22,33,44,55,66,77,88,99,90],
将所有大于66的值保存至字典的第一个 key中,
将小于66的值保存至第二个 key 的值中。

即:{'k1':大于 66 的所有值,'k2':小于66 的所有值}

dic = {"k1":[],
       "k2":[]}
aa = set([11,22,33,44,55,66,77,88,99,90])
for i in aa:
    if i>= 66:
        dic["k1"].append(i)
    else:
        dic["k2"].append(i)
print(dic)
结果
{'k1': [66, 99, 77, 88, 90], 'k2': [33, 11, 44, 22, 55]}
View Code

31、购物车
功能要求:
要求用户输入总资产,例如: 2000
显示商品列表,让用户根据序号选择商品,加入购物车
购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
goods = [
{"name":"电脑","price":1999},
{"name":"鼠标","price":10},
{"name":"游艇","price":20},
{"name":"美女","price":98},
]

shop_cart = []
goods    =    [
{"name":"电脑","price":1999},
{"name":"鼠标","price":10},
{"name":"游艇","price":20},
{"name":"美女","price":98},
]
while True:
    salary = input("请输入用户余额[quit]:")
    if salary.isdigit():
        salary = int(salary)
        break
    elif salary == "quit":
        exit("不想购买")
    else:
        print("please the enter number")
while True:
    print("shop list".center(50, '*'))
    for index,i in enumerate(goods):
        print(index,i)
    choose_number = input("请输入购买商品编号[quit]:")
    if choose_number.isdigit():
        choose_number = int(choose_number)
        product_list = []
        if 0 <= choose_number <= len(goods):
            product_list.append(goods[choose_number])
            if salary >= product_list[0]["price"]:
              shop_cart.append(goods[choose_number])
              salary -= product_list[0]['price']
              print("当前购买的商品",product_list,"当前用户余额\033[1;31m{salary}\033[0m".format(salary=salary))
            else:
                print("余额不足")
        else:
            print("无效的商品编号")
    elif choose_number.lower() == 'quit':

        print("购买的商品".center(50,"*"))
        for y in shop_cart:
            print(y)
        exit()
    else:
        print("无效的输入")
#注:简易的购物车,还能继续优化
View Code

注:请各位大神指点,如有错误,请指出错误地方,我会修改!!

猜你喜欢

转载自www.cnblogs.com/bubu99/p/10166602.html