python入门的120个基础练习(4/12)

158 阅读2分钟

31-拷贝文件 每次读取4K,读完为止: src_fname = '/bin/ls' dst_fname = '/root/ls'

src_fobj = open(src_fname, 'rb')
dst_fobj = open(dst_fname, 'wb')

while True:
    data = src_fobj.read(4096)
    if not data:
        break
    dst_fobj.write(data)

src_fobj.close()
dst_fobj.close()

32-位置参数 注意:位置参数中的数字是字符形式的 import sys

print(sys.argv)  # sys.argv是sys模块里的argv列表

# python3 position_args.py
# python3 position_args.py 10
# python3 position_args.py 10 bob

33-函数应用-斐波那契数列 def gen_fib(l): fib = [0, 1]

    for i in range(l - len(fib)):
        fib.append(fib[-1] + fib[-2])

    return fib  # 返回列表,不返回变量fib

a = gen_fib(10)
print(a)
print('-' * 50)
n = int(input("length: "))
print(gen_fib(n))  # 不会把变量n传入,是把n代表的值赋值给形参

34-函数-拷贝文件 import sys

def copy(src_fname, dst_fname):
    src_fobj = open(src_fname, 'rb')
    dst_fobj = open(dst_fname, 'wb')

    while True:
        data = src_fobj.read(4096)
        if not data:
            break
        dst_fobj.write(data)

    src_fobj.close()
    dst_fobj.close()

copy(sys.argv[1], sys.argv[2])
# 执行方式
# cp_func.py /etc/hosts /tmp/zhuji.txt

35-函数-九九乘法表 def mtable(n): for i in range(1, n + 1): for j in range(1, i + 1): print('%s*%s=%s' % (j, i, i * j), end=' ') print()

mtable(6)
mtable(9)

36-模块基础 每一个以py作为扩展名的文件都是一个模块。 star.py:

hi = 'hello world!'

def pstar(n=50):
    print('*' * n)

if __name__ == '__main__':
    pstar()
    pstar(30)
在call_star.py中调用star模块:

import star

print(star.hi)
star.pstar()
star.pstar(30)

37-生成密码/验证码 此文件名为:randpass.py 思路: 1、设置一个用于随机取出字符的基础字符串,本例使用大小写字母加数字 2、循环n次,每次随机取出一个字符 3、将各个字符拼接起来,保存到变量result中 from random import choice import string

all_chs = string.ascii_letters + string.digits  # 大小写字母加数字

def gen_pass(n=8):
    result = ''

    for i in range(n):
        ch = choice(all_chs)
        result += ch

    return result

if __name__ == '__main__':
    print(gen_pass())
    print(gen_pass(4))
    print(gen_pass(10))

38-序列对象方法 from random import randint

alist = list()  # []
list('hello')  # ['h', 'e', 'l', 'l', 'o']
list((10, 20, 30))  # [10, 20, 30]  元组转列表
astr = str()  # ''
str(10)  # '10'
str(['h', 'e', 'l', 'l', 'o'])  # 将列表转成字符串
atuple = tuple()  # ()
tuple('hello')  # ('h', 'e', 'l', 'l', 'o')
num_list = [randint(1, 100) for i in range(10)]
max(num_list)
min(num_list)

39-序列对象方法2 alist = [10, 'john'] # list(enumerate(alist)) # [(0, 10), (1, 'john')] # a, b = 0, 10 # a->0 ->10

for ind in range(len(alist)):
    print('%s: %s' % (ind, alist[ind]))

for item in enumerate(alist):
    print('%s: %s' % (item[0], item[1]))

for ind, val in enumerate(alist):
    print('%s: %s' % (ind, val))

atuple = (96, 97, 40, 75, 58, 34, 69, 29, 66, 90)
sorted(atuple)
sorted('hello')
for i in reversed(atuple):
    print(i, end=',')

40-字符串方法 py_str = 'hello world!' py_str.capitalize() py_str.title() py_str.center(50) py_str.center(50, '#') py_str.ljust(50, '') py_str.rjust(50, '') py_str.count('l') # 统计l出现的次数 py_str.count('lo') py_str.endswith('!') # 以!结尾吗? py_str.endswith('d!') py_str.startswith('a') # 以a开头吗? py_str.islower() # 字母都是小写的?其他字符不考虑 py_str.isupper() # 字母都是大写的?其他字符不考虑 'Hao123'.isdigit() # 所有字符都是数字吗? 'Hao123'.isalnum() # 所有字符都是字母数字? ' hello\t '.strip() # 去除两端空白字符,常用 ' hello\t '.lstrip() ' hello\t '.rstrip() 'how are you?'.split() 'hello.tar.gz'.split('.') '.'.join(['hello', 'tar', 'gz']) '-'.join(['hello', 'tar', 'gz'])

41~120题见下篇 ———————————————— 作者:ChiefZHG 原文链接:blog.csdn.net/weixin_45