python习题,关于函数的练习03

2021-06-05 03:03

阅读:532

标签:无法   魔法   min   迭代   extend   文件   glob   replace   range   

习题1

请写出下列代码的执行结果:

例1:

def func1():
    print(‘in func1‘)


def func2():
    print(‘in func2‘)


ret = func1
ret()
ret1 = func2
ret1()
ret2 = ret
ret3 = ret2
ret2()
ret3()

结果:
in func1
in func2
in func1
in func1

例2:

def func1():
    print(‘in func1‘)


def func2():
    print(‘in func2‘)


def func3(x, y):
    x()
    print(‘in func3‘)
    y()


print(111)
func3(func2, func1)
print(222)

结果
111
in func2
in func3
in func1
222

例3:

def func1():
    print(‘in func1‘)


def func2(x):
    print(‘in func2‘)
    return x


def func3(y):
    print(‘in func3‘)
    return y


ret = func2(func1)  # ret = func1
ret()
ret2 = func3(func2)  # ret2 = func2
ret3 = ret2(func1)  # ret3 = func1
ret3()

ret = func1
ret2 = func2
ret3 = func1

运行结果是:
in func2
in func1
in func3
in func2
in func1

习题2

看代码写结果

def func(arg):
    return arg.replace(‘苍老师‘, ‘***‘)


def run():
    msg = ‘Alex的女朋友苍老师和大家都是好朋友‘
    result = func(msg)
    print(result)


data = run()
print(data)

结果:

Alex的女朋友***和大家都是好朋友
None

习题3

看代码写结果

DATA_LIST = []


def func(arg):
    return DATA_LIST.insert(0, arg)


data = func(‘绕不死你‘)
print(data)
print(DATA_LIST)

结果:

None
[‘绕不死你‘]

习题4

看代码写结果

def func():
    print(‘你好呀‘)
    return ‘好你妹呀‘


func_list = [func, func, func]
for item in func_list:
    val = item()
    print(val)

结果:
你好呀
好你妹呀
你好呀
好你妹呀
你好呀
好你妹呀

习题5

看代码写结果

def func():
    print(‘你好呀‘)
    return ‘好你妹呀‘


func_list = [func, func, func]
for i in range(len(func_list)):
    val = func_list[i]()
    print(val)

结果:
你好呀
好你妹呀
你好呀
好你妹呀
你好呀
好你妹呀结果:

习题6

看代码写结果

def func():
    return ‘烧饼‘


def bar():
    return ‘豆饼‘


def base(a1, a2):
    return a1() + a2()


result = base(func, bar)
print(result)

结果:
烧饼豆饼

习题7

看代码写结果

for item in range(10):
    print(item)
print(item)

结果:
0
1
2
3
4
5
6
7
8
9
9

习题8

看代码写结果

def func():
    for item in range(10):
        pass
    print(item)


func()

结果:
9

习题9

看代码写结果

item = ‘老男孩‘


def fun():
    item = ‘alex‘

    def inner():
        print(item)

    for item in range(10):
        pass
    inner()


fun()

结果:
9

习题10

看代码写结果

l1 = []


def func(args):
    l1.append(args)
    return l1


print(func(1))
print(func(2))
print(func(3))

结果:
[1]
[1, 2]
[1, 2, 3]

习题11

看代码写结果

name = ‘太白‘


def func():
    global name
    name = ‘男神‘


print(name)
func()
print(name)

结果:
太白
男神

习题12

看代码写结果

name = ‘太白‘


def func():
    print(name)


func()

结果:
太白

习题13

看代码写结果

name = ‘太白‘


def func():
    print(name)
    name = ‘alex‘


func()

结果:
执行到:print(name)
这时候name的打印值是:太白
继续执行name = ‘alex‘的时候会报错
局部作用域内的变量无法修改全局的变量
当然如果按照python解释器的说法是在修改这个变量之前,还没有对它进行引用也即是赋值的操作!

习题14

看代码写结果

def func():
    count = 1
    def inner():
        nonlocal count
        count += 1
        print(count)
    print(count)
    inner()
    print(count)


func()

结果:
1
2
2

习题15

看代码写结果

def extendList(val, lst=[]):
    lst.append(val)
    return lst


list1 = extendList(10)
list2 = extendList(123, [])
list3 = extendList(‘a‘)
print(‘list1 = %s‘ % list1)
print(‘list2 = %s‘ % list2)
print(‘list3 = %s‘ % list3)

结果:
list1 = [10, ‘a‘]
list2 = [123]
list3 = [10, ‘a‘]

习题16

看代码写结果

def extendList(val, lst=[]):
    lst.append(val)
    return lst


print(‘list1 = %s‘ % extendList(10))
print(‘list2 = %s‘ % extendList(123, []))
print(‘list3 = %s‘ % extendList("a"))

结果:
list1 = [10]
list1 = [123]
list1 = [10, "a"]

习题17

用你的理解解释一下什么是可迭代对象,什么是迭代器?

可迭代对象:内部含有‘iter‘魔法方法的对象

迭代器:同时含有‘iter‘魔法方法和"next"魔法方法的对象

习题18

如何判断该对象是否是可迭代对象或者迭代器?

from collections.abc import Iterable, Iterator

# isinstance() 判断该对象是否是该类实例化对象
# 可迭代对象 list tuple str dict set 文件句柄等
obj = set()
print(isinstance(obj, Iterable))  # True

# 迭代器
obj = (i for i in range(10))
print(isinstance(obj, Iterator))  # True
习题19

写代码:用while循环模拟for内部的循环机制(面试题)

# for循环例子
lst = range(10)
for i in lst:
    print(i)

# 用while模拟for循环内部机制例子
lst = iter(range(10))
while True:
    try:
        next(lst)
    except StopIteration:
        break
习题20

写函数,传入n个数,返回字典{‘max‘: ‘最大值‘, ‘min‘: ‘最小值‘}

例:min_max(2, 5, 7, 8, 4),返回:{‘max‘: 8, ‘min‘: 2}

import re


def min_max(*args):
    return {‘max‘: max(args), ‘min‘: min(args)}


nums = []
try:
    n = input(‘要输入几个数字:‘)
    if re.match(r‘[1-9][\d]*$‘, n):
        for i in range(int(n)):
            num = input(‘输入数字:‘)
            if re.match(r‘[1-9][\d]*$‘, n):
                nums.append(int(num))
            else:
                raise Exception(‘输入非法,应输入正整数!‘)
    else:
        raise Exception(‘输入非法,应输入正整数!‘)
except Exception as e:
    print(e)
finally:
    print(min_max(*nums))
# 运行结果
# 要输入几个数字:5
# 输入数字:+5
# 输入数字:-6
# 输入数字:58
# 输入数字:-10
# 输入数字:+60
# {‘max‘: 60, ‘min‘: -10}

# 运行报错结果
# 要输入几个数字:4
# 输入数字:3
# 输入数字:2
# 输入数字:7
# 输入数字:gg
# invalid literal for int() with base 10: ‘gg‘
# {‘max‘: 7, ‘min‘: 2}
习题21

写函数,传入一个参数n,返回n的阶乘

例如:cal(7) 计算:7x6x5x4x3x2x1

import re


def my_factorial(n: int):
    s = 1
    for i in range(1, n + 1):
        s *= i
    return s


try:
    n = input(‘阶乘n:‘)
    if re.match(r‘[1-9][\d]*$‘, n):
        print(my_factorial(int(n)))
except Exception as e:
    print(e)
# 运行结果:
# 阶乘n:10
# 3628800
习题22

写函数,返回一个扑克牌列表,里面有52项,每一项是一个元组。例如:[(‘红心‘, 2), (‘梅花‘, 2),...(‘黑桃‘, ‘A‘)]

poker_group = []
nums = list(range(2, 11))
nums.extend(‘JQKA‘)
color_block = [‘黑桃‘, ‘梅花‘, ‘方块‘, ‘红心‘]

for color in color_block:
    for num in nums:
        poker_group.append((color, num))
print(poker_group)
# 运行结果:
# [(‘黑桃‘, 2), (‘黑桃‘, 3), (‘黑桃‘, 4), (‘黑桃‘, 5), (‘黑桃‘, 6), (‘黑桃‘, 7), (‘黑桃‘, 8), (‘黑桃‘, 9), (‘黑桃‘, 10), (‘黑桃‘, ‘J‘), (‘黑桃‘, ‘Q‘), (‘黑桃‘, ‘K‘), (‘黑桃‘, ‘A‘),
# (‘梅花‘, 2), (‘梅花‘, 3), (‘梅花‘, 4), (‘梅花‘, 5), (‘梅花‘, 6), (‘梅花‘, 7), (‘梅花‘, 8), (‘梅花‘, 9), (‘梅花‘, 10), (‘梅花‘, ‘J‘), (‘梅花‘, ‘Q‘), (‘梅花‘, ‘K‘), (‘梅花‘, ‘A‘),
# (‘方块‘, 2), (‘方块‘, 3), (‘方块‘, 4), (‘方块‘, 5), (‘方块‘, 6), (‘方块‘, 7), (‘方块‘, 8), (‘方块‘, 9), (‘方块‘, 10), (‘方块‘, ‘J‘), (‘方块‘, ‘Q‘), (‘方块‘, ‘K‘), (‘方块‘, ‘A‘),
# (‘红心‘, 2), (‘红心‘, 3), (‘红心‘, 4), (‘红心‘, 5), (‘红心‘, 6), (‘红心‘, 7), (‘红心‘, 8), (‘红心‘, 9), (‘红心‘, 10), (‘红心‘, ‘J‘), (‘红心‘, ‘Q‘), (‘红心‘, ‘K‘), (‘红心‘, ‘A‘)]
习题23

写代码完成99乘法表(面试题)

for i in range(1, 10):
    for j in range(1, i + 1):
        print(f‘{j}x{i}={i * j:

python习题,关于函数的练习03

标签:无法   魔法   min   迭代   extend   文件   glob   replace   range   

原文地址:https://www.cnblogs.com/YXFate/p/14638247.html


评论


亲,登录后才可以留言!