1-Python - 疯狂练习题

Python基础

  • 简述变量命名规范
    • 变量名是由字母,数字,下划线组成
    • 变量名不能以数字开头
    • 禁止使用python中的关键词
    • 变量名要区分大小写,
    • 变量名不能使用中文和拼音
    • 变量名要有意义
    • 推荐写法:驼峰体(UserName或者userName)或下划线(user_name)
  • name = input(“>>>”) name变量是什么数据类型
name = input(">>")
print(type(name))   # str
  • if条件语句的基本结构
if
if/if
if/else
if/elif
if/elif/elif
if/elif/.../else
if 嵌套
  • 用print打印出下面内容:
⽂能提笔安天下, 
武能上⻢定乾坤. 
⼼存谋略何⼈胜, 
古今英雄唯是君.
print('''
⽂能提笔安天下, 
武能上⻢定乾坤. 
⼼存谋略何⼈胜, 
古今英雄唯是
''')
print("⽂能提笔安天下,\n武能上⻢定乾坤.\n⼼存谋略何⼈胜,\n古今英雄唯是君.")
  • 利用if语句写出猜大小的游戏:设定一个理想数字比如:66,让用户输入数字,如果比66大,则显示猜测的结果大了;如果比66小,则显示猜测的结果小了;只有等于66,显示猜测结果正确:
a = input('请输入数字')
if int(a) > 66:
    print('大了')
if int(a) < 66:
    print('小了')
elif int(a) = 66:
    print('对了') 
  • 提⽰⽤户输入他的年龄, 程序进⾏判断:如果⼩于10, 提⽰⼩屁孩, 如果⼤于10, ⼩于 20, 提⽰青春期叛逆的⼩屁孩. 如果⼤于20, ⼩于30. 提⽰开始定性, 开始混社会的⼩ 屁孩⼉, 如果⼤于30, ⼩于40. 提⽰看老⼤不⼩了, 赶紧结婚⼩屁孩⼉. 如果⼤于40, ⼩ 于50. 提⽰家⾥有个不听话的⼩屁孩⼉. 如果⼤于50, ⼩于60. 提⽰⾃⼰⻢上变成不听 话的老屁孩⼉.如果⼤于60, ⼩于70. 提⽰活着还不错的老屁孩⼉. 如果⼤于70, ⼩于 90. 提⽰⼈⽣就快结束了的⼀个老屁孩⼉. 如果⼤于90以上. 提⽰. 再⻅了这个世界.
s = input('请输入年龄')
s1 = int(s1)
if s1 < 10:
    print('小屁孩') 
elif 10 < s1 < 20:
    print('青春叛逆的小屁孩')
elif 20 < s1 < 30:
    print('开始定性,开始混社会的小屁孩')
elif 30 < s1 < 40:
    print('老大不小了,赶紧结婚小屁孩') 
elif 40 < s1 < 50:
    print('青春叛逆的小屁孩')
elif 50 < s1 < 60:
    print('开始定性,开始混社会的小屁孩')
elif 60 < s1 < 70:
    print('老大不小了,赶 
elif 70 < s1 < 80:
    print('青春叛逆的小屁孩')
elif 80 < s1 < 90:
    print('开始定性,开始混社会的小屁孩')
  • 判断下面print的输出结果:
print(1 > 1 or 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6)  # True
print(not 2 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6)  # False

  • 打印菱形小星星
"""
     *
    ***
   *****
  *******
 *********
***********
 *********
  *******
   *****
    ***
     *
"""
count = 1
range_num = 13
for i in range(1, range_num):
    if range_num / 2 > i:  # 当宽的一半小于 i 说明要从小到大,每次加两个*
        sign = "*" * count
        print(sign.center(range_num, ' '), '-----', 'count == ', count, 'i == ', i, '半数: ', range_num / 2)
        count += 2
    else:
        sign = "*" * count
        print(sign.center(range_num, ' '), '+++++++', 'count == ', count, 'i == ', i, '半数: ', range_num / 2)
        count -= 2
  • 三级菜单
需求

需求:
可依次选择进入各子菜单
可从任意一层往回退到上一层
可从任意一层退出程序
所需新知识点:列表、字典
基础需求:80%

  1. 可依次选择进入各子菜单
  2. 可从任意一层往回退到上一层
  3. 可从任意一层退出程序
    所需新知识点:列表、字典

升级需求:10%

  1. 使用一个while循环,且整体代码量不超过15行
    编码规范需求:10%
    思路:
    字典查询 列表循环
    while 循环 加 if 判断
    for 循环打印结果
基础版

menu = {
    '北京':{
        '海淀':{
            '五道口':{
                'soho':{},
                '网易':{},
                'google':{}
            },
            '中关村':{
                '爱奇艺':{},
                '汽车之家':{},
                'youku':{},
            },
            '上地':{
                '百度':{},
            },
        },
        '昌平':{
            '沙河':{
                '老男孩':{},
                '北航':{},
            },
            '天通苑':{},
            '回龙观':{},
        },
        '朝阳':{},
        '东城':{},
    },
    '上海':{
        '闵行':{
            "人民广场":{
                '炸鸡店':{}
            }
        },
        '闸北':{
            '火车战':{
                '携程':{}
            }
        },
        '浦东':{},
    },
    '山东':{},
}


exit_flag = False
while not exit_flag:
    for key in menu:
        print(key)

    choice = input(">:").strip()
    if len(choice) == 0 : continue
    if choice == 'q':
        exit_flag = True
        continue
    if choice in menu: #省存在,进入此省下一级
        while not exit_flag:
            next_layer = menu[choice]
            for key2 in next_layer:
                print(key2)
            choice2 = input(">>:").strip()
            if len(choice2) == 0: continue
            if choice2 == 'b': break
            if choice2 == 'q':
                exit_flag = True
                continue
            if choice2 in next_layer: #再进入下一层
                while not exit_flag:
                    next_layer2 = next_layer[choice2]
                    for key3 in next_layer2:
                        print(key3)
                    choice3 = input(">>>:").strip()
                    if len(choice3) == 0: continue
                    if choice3 == 'b': break
                    if choice3 == 'q':
                        exit_flag = True
                        continue

                    if choice3 in next_layer2:
                        while not exit_flag:
                            next_layer3 = next_layer2[choice3]
                            for key4 in next_layer3:
                                print(key4)

                            choice4 = input(">>>>:").strip()
                            if choice4 == 'b':break
                            if choice4 == 'q':
                                exit_flag = True
                                continue
进阶版
menu = {
    '北京':{
        '海淀':{
            '五道口':{
                'soho':{},
                '网易':{},
                'google':{}
            },
            '中关村':{
                '爱奇艺':{},
                '汽车之家':{},
                'youku':{},
            },
            '上地':{
                '百度':{},
            },
        },
        '昌平':{
            '沙河':{
                '老男孩':{},
                '北航':{},
            },
            '天通苑':{},
            '回龙观':{},
        },
        '朝阳':{},
        '东城':{},
    },
    '上海':{
        '闵行':{
            "人民广场":{
                '炸鸡店':{}
            }
        },
        '闸北':{
            '火车战':{
                '携程':{}
            }
        },
        '浦东':{},
    },
    '山东':{},
}
last_layers =  [  menu  ]  #上一层

current_layer = menu  #当前层

while True:
    for key in current_layer:
        print(key)
    choice = input(">>:").strip()
    if len(choice)==0:continue
    if choice in current_layer: #进入下一层
        last_layers.append(current_layer) #当前层添加到列表
        current_layer = current_layer[choice] #北京
    if choice == "b":
        if last_layers:
            current_layer = last_layers[-1] #取到上一层,赋值给current_layer
            last_layers.pop()
    if choice == 'q':
        break

函数

  • 编写认证功能的装饰器,为多个函数加上认证的功能(用户名和密码),要求只需要登录成功一次,后续的函数都能自动登录成功:
"""
认证功能的装饰器
"""

certificate_dict = {}

def cert(func):
    def wrapper(*args, **kwargs):
        if certificate_dict.get('status', False):
            print('[{}] 自动登录成功'.format(certificate_dict['user_name']))
            return func(*args, **kwargs)
        else:
            user, pwd = input("user: ").strip(), input("pwd: ").strip()
            if user.lower() == 'zhangkai' and pwd == '123':  # 这里可以将用户名和密码写在文件中
                print("[{}]登录成功".format(user))
                certificate_dict['user_name'] = user
                certificate_dict['status'] = True
                return func(*args, **kwargs)

    return wrapper

@cert
def login():
    print('login function')

@cert
def index():
    print('index page')

@cert
def back():
    print('back page')

if __name__ == '__main__':
    login()
    index()
    back()
  • 计算1!+2!+3!+10!的阶乘结果:
def foo1(n):
    num, count = 1, 0
    for i in range(1, n + 1):
        num *= i
        count += num

    return count


def foo2(n):
    count = 0
    for i in range(1, n + 1):
        tmp = 1
        for k in range(1, i + 1):
            tmp *= k
        count += tmp

    return count


if __name__ == '__main__':
    print(foo1(10))  # 4037913
    print(foo2(10))  # 4037913
  • 使用函数完成三次登录,要求是用户名和密码都保存在一个info.txt中,且info.txt文件中存储有多个用户名和和密码,每个用户名和密码占用一行。三次登录失败即退出程序:
"""
# info.txt

zhangkai|123
likai|234
wangkai|345
"""

PATH = r'./info.txt'

def read_file(path):
	with open(path, 'r', encoding='utf-8') as f:
		l = []
		for i in f:
			name, pwd = i.strip().split("|")
			l.append({"user": name, "pwd": pwd})
		return l

def login():
	user_list = read_file(PATH)
	count = 1
	while count <= 3:
		user = input('user: ').strip()
		pwd = input('pwd: ').strip()
		for i in user_list:
			if user == i['user'] and pwd == i['pwd']:
				print('login successful')
				break
		else:
			print('login error')
			count += 1
if __name__ == '__main__':
	login()
  • 递归统计指定目录下的文件个数:
import os

def foo(path):
    if os.path.isdir(path):
        total = 0
        for line in os.listdir(path):
            tmp_path = os.path.join(path, line)
            if os.path.isdir(tmp_path):
                total += foo(tmp_path)
            else:
                total += 1
        return total
    else:
        exit('给定的路径不是目录')

if __name__ == '__main__':
    print(foo(r"D:\tmp"))
  • 使用相关模块生成6为的验证码,验证码内容包括随机数字、随机小写字符、随机大写字符:
import random
import string

# 法1
def code(n=6):
    end = ''
    for i in range(n):
        num = str(random.randint(0,9))
        alpha_up = chr(random.randint(65,90))
        alpha_low = chr(random.randint(97,122))
        aim = random.choice([num,alpha_up,alpha_low])
        end += aim
    return end
print(code(8)) # 传几位就生成几位验证码

# 法2
def foo(n):
    return ''.join(random.sample(string.digits + string.ascii_lowercase + string.ascii_uppercase, n))

print(foo(6))
  • 用map来处理列表,把列表中所有人都变成xx_666,如张开_666, name = ["张开", "李开", "王开", "赵开"]:
name = ["张开", "李开", "王开", "赵开"]
print(list(map(lambda x: x + '_666', name)))
"""
['张开_666', '李开_666', '王开_666', '赵开_666']
"""
  • 使用map来处理列表,将列表中每个人的名字都编程以xx_666,如张开_666tmp_list = [{'name': '张开'}, {'name': '李开'}, {'name': '王开'}, {'name': '赵开'}]:
tmp_list = [{'name': '张开'}, {'name': '李开'}, {'name': '王开'}, {'name': '赵开'}]
print(list(map(lambda x: x['name'] + '_666', tmp_list)))
"""
['张开_666', '李开_666', '王开_666', '赵开_666']
"""
  • 将下面的列表内的元素以age升序排序:
tmp_list = [
    {'name': '张开', 'age': 18}, {'name': '李开', 'age': 8},
    {'name': '王开', 'age': 32}, {'name': '赵开', 'age': 25}
]
tmp_list.sort(key=lambda x: x['age'], reverse=False)
print(tmp_list)
"""
[{'name': '李开', 'age': 8}, {'name': '张开', 'age': 18}, {'name': '赵开', 'age': 25}, {'name': '王开', 'age': 32}]
"""
  • 文件操作,使用Python将图片新建一个副本,比如有a.jpg,使用Python得到副本b.jpg:
with open('a.jpg', 'rb') as rf:
      with open('b.jpg', 'wb') as wf:
            wf.write(rf.read())
  • 实现一个统计函数执行时间的装饰器
import time
import random

def timmer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        res = func(*args, **kwargs)
        print('{} running: {}'.format(func.__name__, time.time() - start))
        return res

    return wrapper

@timmer
def foo():
    time.sleep(random.random())

foo()
  • 写函数,接收两个数字参数,将较小的数字返回:
def foo(x, y):

	return y if x > y else x
print(foo(3, 6))
print(foo(6, 3))

模块与包

  • 获取当前的字符串时间(2020-12-24 11:06:14),获取三天后的字符串时间(2020-12-24 11:06:14):
import time

# 一天的时间戳时间
one_day_time = 24 * 60 * 60

# 当前时间戳时间  --> 结构化时间 --> 字符串时间
now_timestamp_time = time.time()
now_struct_time = time.localtime(now_timestamp_time)
now_format_time = time.strftime('%Y-%m-%d %H:%M:%S', now_struct_time)
print(now_format_time)  # 2020-12-24 11:06:14

# 三天后的字符串时间:当前时间戳时间 + 3天时间戳时间 --> 结构化时间 --> 字符串时间
after_three_days_timestamp_time = now_timestamp_time + one_day_time * 3
after_three_days_struct_time = time.localtime(after_three_days_timestamp_time)
after_three_days_format_time = time.strftime('%Y-%m-%d %H:%M:%S', after_three_days_struct_time)
print(after_three_days_format_time)  # 2020-12-27 11:06:14

import datetime

after_three_days_struct_time = datetime.datetime.now() + datetime.timedelta(days=3)
after_three_days_format_time = after_three_days_struct_time.strftime("%Y-%m-%d %H:%M:%S")
print(after_three_days_format_time)
  • 请将时间'2018-11-11 11:11:11'转换成时间戳时间
import time
''''
思路:字符串时间 --> 结构化时间 --> 时间戳时间
'''
t = "2018-11-11 11:11:11"
strpt_time = time.strptime(t, '%Y-%m-%d %H:%M:%S')
print(time.mktime(strpt_time))  # 1541905871.0
  • 如何获取当前脚本的绝对路径和父级路径:
import os
print(os.path.abspath(__file__))
print(os.path.dirname(os.path.abspath(__file__)))
  • 回答:
# 什么是可迭代对象?什么是迭代器?可迭代对象和迭代器的区别是什么?什么是生成器,如何得到一个生成器
# 如果一个对象具有__iter__方法,则称为可迭代对象
# 可迭代对象执行__iter__方法返回的结果称为迭代器
# 可迭代对象只有__iter__方法,而迭代器则有__iter__、__next__两个方法。
# 函数体内包含有yield关键字,那么该函数被称为生成器函数,而该函数执行的结果(返回值generator_obj)为生成器
# https://www.cnblogs.com/Neeo/articles/13200309.html
# https://www.cnblogs.com/Neeo/articles/13200313.html
  • 写函数,完成给一个列表去重的功能(不能使用set集合),tmp_list = [1, 2, 2, 1, 3, 4, 5, 6]
def foo(l):
    tmp_list = []
    for i in l:
        if i not in tmp_list:
            tmp_list.append(i)
    return tmp_list

print(foo([1, 2, 2, 1, 3, 4, 5, 6]))  # [1, 2, 3, 4, 5, 6]

异常处理

面向对象

Others

  • 求最大可能,也称为求一个集合的所有的子集:
def PowerSetsBinary(items):
    #generate all combination of N items
    N = len(items)
    #enumerate the 2**N possible combinations
    for i in range(2**N):
        combo = []
        for j in range(N):
            #test jth bit of integer i
            if(i >> j ) % 2 == 1:
                combo.append(items[j])
        yield combo
for i in PowerSetsBinary('123'):
    print(i)

'''
[]
['1']
['2']
['1', '2']
['3']
['1', '3']
['2', '3']
['1', '2', '3']
'''
  • Python生成目录树代码,用Python实现类似Windows下的tree命令,获取目录树结构:
import os
import os.path

BRANCH = '├─'
LAST_BRANCH = '└─'
TAB = '│  '
EMPTY_TAB = '   '


def get_dir_list(path, placeholder=''):
    folder_list = [folder for folder in os.listdir(path) if os.path.isdir(os.path.join(path, folder))]
    file_list = [file for file in os.listdir(path) if os.path.isfile(os.path.join(path, file))]
    result = ''
    for folder in folder_list[:-1]:
        result += placeholder + BRANCH + folder + '\n'
        result += get_dir_list(os.path.join(path, folder), placeholder + TAB)
    if folder_list:
        result += placeholder + (BRANCH if file_list else LAST_BRANCH) + folder_list[-1] + '\n'
        result += get_dir_list(os.path.join(path, folder_list[-1]), placeholder + (TAB if file_list else EMPTY_TAB))
    for file in file_list[:-1]:
        result += placeholder + BRANCH + file + '\n'
    if file_list:
        result += placeholder + LAST_BRANCH + file_list[-1] + '\n'
    return result


if __name__ == '__main__':
    print(os.path.dirname(os.getcwd()))
    print(get_dir_list(os.path.dirname(os.getcwd())))
  • 打印斐波那契数列,斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13,特别指出:第0项是0,第1项是第一个1。从第三项开始,每一项都等于前两项之和。
代码示例
# 1. 利用for循环动态输入一个动态的数列,如输入5,>>> [0, 1, 1, 2, 3]
num = int(input('>>>:'))
fibonacci = [0, 1]
for i in range(num - 2):
    fibonacci.append(fibonacci[-2] + fibonacci[-1])
print(fibonacci)

# 2. 使用函数的方式
def fibonacci(num):
    result = [0, 1]
    for i in range(num-2):
        result.append(result[-2] + result[-1])
    return result
print(fibonacci(11))

# 3. 递归版本
def r_fibonacci(num):
    """递归版本 """
    if num < 2:
        return num
    return r_fibonacci(num - 1) + r_fibonacci(num - 2)
 
# print(r_fibonacci(10))
for i in range(11):
    print(r_fibonacci(i))


# 4. lambda版
fibonacci = lambda n: 1 if n <= 2 else fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(35))

# 生成器版
class Fib(object):
    def __init__(self):
        self.prev = 0
        self.curr = 1
 
    def __iter__(self):
        return self
 
    def __next__(self):
        self.curr, self.prev = self.prev + self.curr, self.curr
        return self.curr
 
fib = Fib()
for i in range(10):
    print(next(fib))

# yield版
def fib():
    prev, curr = 0, 1
    while True:
        yield curr
        curr, prev = prev + curr, curr
 
f = fib()
for i in range(10):
    print(next(f))


欢迎斧正,that's all
posted @ 2020-02-10 23:00  听雨危楼  阅读(997)  评论(0编辑  收藏  举报