python之基础训练题

关于字符串,列表,元组,字典的基础练习题

最近算是学完了python基础数据类型这一部分,做了一些基础练习题,相信勤能补拙吧

1.)循环提示输入用户名,密码,邮箱(要求输入长度不超过20个字符 若超过就只有前20个有效,输入Q或q 表示停止,输出表格形式

                                                                                     
flag = True                                                                                      
d = ''                                                                                           
while flag:                                                                                      
print('请依次输入用户名,密码,邮箱')                                                                      
a = input('用户名')[0:20]                                                                       
b = input('密码')[0:20]                                                                        
c = input('邮箱')[0:20]                                                                        
s1 = '{name}\t{password}\t{email}\n'                                                         
a = s1.format(name=a, password=b, email=c)                                                   
d += a                                                                                       
flag = input('除q外任意键继续')                                                                     
if flag == 'Q' or flag == 'q':                                                               
    p = 'admin\tpassword\temail'                                                             
    print(p.expandtabs(10) + '\n', d.expandtabs(10))                                         
    flag = False                                                                             

2. )将字符串对应的索引打印出来

test = '人生苦短我用派森'                                                                                
for i in range(0, len(test)):                                                                    
     print(i, test[i])                             

3. )制作随机验证码不区分大小写 流程:用户执行程序-给用户显示需要输出的验证码-用户输入 判断(输不对一直输)

 def check_code():                                                                                
     import random                                                                                
     checkcode = ''                                                                               
     for i in range(4):                                                                           
         current = random.randrange(0, 4)                                                         
         if current != i:                                                                         
             temp = chr(random.randint(65, 90))                                                   
         else:                                                                                    
             temp = random.randint(0, 9)                                                          
         checkcode += str(temp)                                                                   
     return checkcode                                                                             
                                                                                                  
                                                                                                  
 code = check_code()                                                                              
 wh = True                                                                                        
 while wh:                                                                                        
     print('请输入验证码', code)                                                                        
     incode = input().upper()                                                                     
     if str(incode) == str(code):                                                                 
         print('输入正确', code)                                                                      
         wh = False                                                             

3. )敏感词过滤:

out = input('>>>请输入:')                                                                           
output = out.replace('傻逼', '***')                                                                
output1 = output.replace('王八蛋', '***')                                                           
print(output1)                                                                  

4. )用下划线将列表的每一个元素拼接成字符串

 l = ['alex', 'eric', 'rain']                                                                     
 t = '_'.join(l)                                                                                  
 print(t)                                                                                         
                                                                                    

5. )实现整数加法计算器; 1+6 9+4

 comtent = input('请输入:')                                                                          
 c1, c2 = comtent.split('+')                                                                      
 print(int(c1) + int(c2))                                                                         

6.)计算输入的内容中有多少字母和十进制小数

 v = 0                                                                                            
 v1 = 0                                                                                           
 com = input('请输入a:')                                                                             
 for i in com:                                                                                    
     if i.isdecimal():                                                                            
         v += 1                                                                                   
     elif i.isalpha():                                                                            
         v1 += 1                                                                                  
 print(com, '数字有' + str(v), '字母有' + str(v1))           

7. 输入姓名,地点,爱好, 任意输出 :敬爱的*******最喜欢在***地方干 ***

 s = input('输入格式:姓名,地点,爱好')                                                                       
 p1, p2, p3 = s.split(',')                                                                        
 s1 = '敬爱的{name},最喜欢在{address}干{somthing}'                                                        
 a = s1.format(name=p1, address=p2, somthing=p3)                                                  
 print(a)                                                                                        

7. )用户交互显示类似省市县N级联动的选择 ; a允许用户添加内容;b允许用户选择查看某一个级别内容

# 先创建一个字典接收省市县;                                                                                    
dic = {'k0': ['A', 'B'],                                                                           
       'k1': {'A': ['A1', 'A2', ], 'B': ['B1', 'B2']},                                             
       'k2': {'A1': ['A11', 'A12'], 'A2': ['A21', 'A22'],                                          
              'B1': ['B11', 'B12'], 'B2': ['B21', 'B22']}}                                         
x = input('欢迎查询省市县:k0-省,k1-市,k2-县')                                                                
if x == 'k0':                                                                                      
    x1 = dic[str(x)]                                                                               
    print(x1)                                                                                      
    print('是否添加省份?确认y/离开n')                                                                        
    y1 = input()                                                                                   
    if y1 == 'y':                                                                                  
        y2 = input('请输入添加的省份:')                                                                    
        dic.update(k0=y2)                                                                          
        print('添加成功', dic['k0'])                                                                   
    else:                                                                                          
        print('欢迎下次使用')                                                                            
elif x == 'k1':                                                                                    
    x2 = dic[str(x)]                                                                               
    print(x2)                                                                                      
    print('是否添加市区?确认y/离开n')                                                                        
    y1 = input()                                                                                   
    if y1 == 'y':                                                                                  
        y2 = input('请输入添加的市区:')                                                                    
        dic.update(k1=y2)                                                                          
        print('添加成功', dic['k1'])                                                                   
    else:                                                                                          
        print('欢迎下次使用')                                                                            
elif x == 'k2':                                                                                    
    x3 = dic[str(x)]                                                                               
    print(x3)                                                                                      
    print('是否添加县城?确认y/离开n')                                                                        
    y1 = input()                                                                                   
    if y1 == 'y':                                                                                  
        y2 = input('请输入添加的县城:')                                                                    
        dic.update(k3=y2)                                                                          
        print('添加成功', dic['k3'])                                                                   
    else:                                                                                          
        print('欢迎下次使用')                                                                            
else:                                                                                              
    print('输入错误')                                                                                  
                                                                                              

8.)元素分类:如有下值集合[11,22,33,44,55,66,77,88,99,90], 将所有大于66的值保存至字典的第一个key中, 将小于66的值保存到第二个key中;例:{‘k1’:所有大于66的值,‘k2’:所有小于66的值}

                                                                                                   
list1 = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]                                                   
# 创建空字典                                                                                            
dic = {}                                                                                           
# 创建两个空列表接收符合条件的元素                                                                                 
a = []                                                                                             
b = []                                                                                             
for item in list1:                                                                                 
    if item > 66:                                                                                  
        a.insert(0, item)  # 将符合条件的元素添加到a列表                                                        
        dic.setdefault('k1', a)  # 将列表中符合条件的元素添加到字典                                                
    elif item < 66:                                                                                
        b.insert(0, item)  # 将符合条件的元素添加到a列表                                                        
        dic.setdefault('k2', b)  # 将列表中符合条件的元素添加到字典                                                
 print(dic)  # {'k2': [55, 44, 33, 22, 11], 'k1': [90, 99, 88, 77]}                               

9.)输出商品列表,用户输入序号,显示用户选中的商品 ;商品列表[手机,电脑,鼠标垫,游艇] ; a允许用户添加商品;b用户输入序号显示内容

product_list = ['手机', '电脑', '鼠标垫', '游艇']                                                           
                                                                                                   
print('当前商品有:', product_list)  # 交互提示                                                              
flag = True                                                                                        
while flag:                                                                                        
    a = int(input('请输入序号查询商品!'))                                                                   
    if a >= len(product_list):                                                                     
        print('该序号不存在,请重新输入!\n')                                                                   
    elif a <= len(product_list):                                                                   
        b = product_list[a]  # 返回序号对应的商品                                                           
        print('您当前查询的商品为:', b)                                                                     
        flag = False                                                                               
        print('是否添加商品?输入1确认,输入0结束\n')                                                              
        x = input()                                                                                
        if int(x) == 0:                                                                            
            print('感谢下次使用!')                                                                       
        elif int(x) == 1:                                                                          
            y = input('请输入你想添加的商品...\n')                                                           
            product_list.append(y)                                                                 
            print(product_list, '\n商品添加成功')                                                        
                                                                                                   

10.)有两个列表: list1 = [11,22,33]; list2 = [22,33,44] ;a获取内容相同的元素列表, b获取1/2中有2/1中没有的元素列表 , c 获取两者中内容都不同的元素

# 创建列表:                                                                                            
list1 = [11, 22, 33]                                                                               
list2 = [22, 33, 44]                                                                               
for item1 in list1:                                                                                
    if item1 in list2:  # a获取内容相同的元素列表,                                                            
        pass  # print('相同元素', item1)                                                               
    elif item1 not in list2:  # b获取1中有2中没有的元素列表                                                    
        # print('list1中有list2中没有的元素', item1)                                                       
        # print('两列表中不相同的元素', item1)                                                               
        pass                                                                                       
for item2 in list2:                                                                                
    if item2 not in list1:                                                                         
        # print('list2中有list1中没有的元素', item2)                                                       
        # print('两列表中不相同的元素', item2)                                                               
        pass                                                                                     

11.)有1-8,8个数字可组成多少个互不相同且无重复的两位数

# 定义一个计数器                                                                                          
count = 0                                                                                          
for item1 in range(1, 9):  # 遍历十位数                                                                 
    for item2 in range(1, 9):  # 遍历个位数                                                             
        if item2 != item1:  # 判断不重复得数                                                              
            count += 1 
print(count)                                                                                     
                                                                                        

12.)打印99乘法表:

for v1 in range(1, 10):                                                                            
    for v2 in range(1, v1 + 1):                                                                    
        a = v1 * v2                                                                                
        print(str(v1) + '*' + str(v2) + '=' + str(a), end=' ')  
    print()                      # 美化输出格式                                                        
                                                       

13.)自动计算方案: 公鸡5元一个,母鸡3元一个,小鸡一元三个,用100元买100只鸡, 要求公鸡,母鸡,小鸡都要有,且各买多少只恰好100元

# 公鸡x,母鸡y,小鸡z                                                                                      
x1 = 100 // 5                                                                                      
y1 = 100 // 3                                                                                      
z1 = 100                                                                                           
for x in range(1, x1):                                                                             
    for y in range(1, y1):                                                                         
        for z in range(1, z1):                                                                     
            if (x + y + z) == 100 and (5 * x) + (3 * y) + (z / 3) == 100:                          
                pass  # print(x, y, z)                                        

14.)代码实现利用下划线将列表的每一个元素拼接成字符串

list3 = ['life', 'short', 'i', 'python', 123]                                                      
s = ''                                                                                             
for item in list3:                                                                                 
    s += ('_' + str(item))                                                                         
    pass  # print(s)         
    
    ============  join方法===========                                                                    
# list3[4] = str(list3[4])                                                                         
# a = '_'.join(list3)                                                                              
# print(a)                                        

15. )1。计算元组长度并输出,2。获取元组第二个元素并输出,3。获取元组第一二个元素并输出, 4。for 循环遍历输出元组元素,5。用for,len,range输出元组的索引 , 6。使用enumerate输出元组元素和序号(从10开始)

    
tuple1 = ('life', 'python', 'short')                                                               
t1 = len(tuple1)                                                                                   
t2 = tuple1[1]                                                                                     
t3 = tuple1[1:]  # t3 = tuple1[0:2]                                                                
for item in tuple1:                                                                                
    pass  # print(item)                                                                            
for index in range(0, len(tuple1)):                                                                
    pass  # print(index)                                                                           
for item, index in enumerate(tuple1, 10):  # 可指定起始位置的创建新列                                          
    pass  # print(item,index)                                                                      
                                                                          

16.)有以下变量,实现要求的功能:1讲述元组的特性2,元组中第一个元素’life’是否可被修改;3’k2’对应什么类型,是否可被修改,可则添加元素’python’ 4’ k3’对应什么类型,是否可被修改,可则添加元素’python’

tuple2 = ('life', [11, 22, {'k1': 'v1',                                                            
                            'k2': ['hello', 'world'], 'k3': (11, 22, 33)}, 44])                    
# 1。元组不可变,但可视情况修改二级元素,可通过索引下标找元素,有序                                                                
# 2。第一个元素不可被修改,(但是可将元组转换类型后修改)                                                                     
# 3。k2对应列表类型,可修改                                                                                   
tuple2[1][2]['k2'].append('python')  # 添加元素'python'                                                
# 4。k3对应元组类型,不可修改                                                                                  

17.) 布尔值为False的所有值

空的(列表,字符串,元组,字典),数值型为0,空值None         

18.) 有以下列表,要求找到任意两个元素相加能够等于9的合集;返回对应的索引:[(0,1),(4,5)]

nums = [2, 7, 11, 15, 1, 8, 4, 6, 5, 3]                                                            
list4 = []                                                                                         
for item in nums:                                                                                  
    for item1 in nums:                                                                             
        a = item + item1                                                                           
        if a == 9:                                                                                 
            list4.append((nums.index(item), nums.index(item1)))                                    
 print(list4)                                                                                     
                                                                                                   

19.) 计算列表长度并输出;列表中追加元素’10011’,并输出添加后的列表; 1 列表第一个位置添加’short’,输出添加后的列表; 2修改列表中第二个位置元素为’goodbye’,输出修改后的列表; 3删除列表中元素’life’,并输出修改后的列表 ; 4删除列表中第二个元素,并输出被删除的元素和删除后的列表 ;5删除列表中第三个元素,并输出修改后的列表 ;6将所有元素反转,输出反转后的列表;7使用for,len,range 输出列表的索引 ;8使用enumerate输出列表元素和序号 ;9for循环输出列表所有元素 ;10删除列表中第二到四个元素,输出删除后的列表

list5 = ['hello', 'life', 'world', 'python', 'hash', 'use']                                        
l1 = len(list5)  # 4                                                                               
l2 = list5.append('10011')  # ['hello', 'life', 'world', 'python', '10011']                        
l3 = list5.insert(0, 'short')  # ['short', 'hello', 'life', 'world', 'python', '10011']            
l4 = list5[1] = 'goodbye'  # ['short', 'goodbye', 'life', 'world', 'python', '10011']              
l5 = list5.remove('life')  # ['short', 'goodbye', 'world', 'python', '10011']                      
l6 = list5.pop(2)  # print(list5,l6)['short', 'goodbye', 'python', '10011'] world                  
l7 = list5.pop(2)  # ['short', 'goodbye', '10011']                                                 
l9 = list5.reverse()  # ['10011', 'goodbye', 'short']                                              
for item in range(len(list5)):                                                                     
    pass  # print(item)  # 0 1 2                                                                   
for item in enumerate(list5, 100):                                                                 
    pass  # print(item,end=' ')     # (100, '10011') (101, 'goodbye') (102, 'short')               
for item in list5:                                                                                 
    pass  # print(item,end=' ')     # 10011 goodbye short                                          
del list5[1:4]  # ['hello', 'hash', 'use']                                                         

20.)分页显示内容:

通过for循环创建301条数据,数据类型不限

'admin-1 admin1@126.com password1

'admin-2 admin2@126.com password2

'admin-3 admin3@126.com password3

提示用户输入页码,当输入指定页码,输出指定数据

每页 10 条数据 ,非十进制数字提示输入错误

date = 'name:admin-{i}  email:admin{i}@126.com  password:pasword{i}'                               
date_list = []                                                                                     
for item in range(1, 302):                                                                         
    dates = date.format(i=item)                                                                    
    date_list.append(dates)                                                                        
number = input('请输入查询的页码(1-31)')                                                                   
if number.isdecimal():                                                                             
    if int(number) == 1:                                                                           
        n1 = date_list[0:int(number) * 10]                                                         
        for item in n1:                                                                            
            print(item)                                                                            
    elif int(number) > 1:                                                                          
        n2 = date_list[int(number) * 10:(int(number) + 1) * 10]                                    
        if n2 not in date_list:                                                                    
            print('该页码无数据')                                                                        
        for item in n2:                                                                            
            print(item)                                                                            
else:                                                                                              
    print('输入错误')                                                                                  

以上20道练习题基本上包容了前面我们介绍的字符串,列表,元组,字典的基本用法,由于个人能力问题,部分代码可能不太简练,望各位前辈多多指教

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值