函数的定义和使用作业参考答案
练习1:写一个函数实现摇色子的功能,传入色子的个数,返回所有色子的点数总和。
import random
def roll_dice(num):
total = 0
for _ in range(num):
total += random.randint(1, 6)
return total
练习2:写一个函数,求出列表中数值类元素(int、float)的平均值。
def calc_avg(items):
total, counter = 0, 0
for item in items:
if type(item) in (int, float):
total += item
counter += 1
return total / counter
练习3:写一个函数,传入一个字符串,返回去掉字符串中所有空格后的字符串。
def remove_space(content):
return content.replace(' ', '')
练习4:写一个函数,传入两个字符串,返回从第一个字符串中去掉第二个字符串中的字符之后的字符串。
def remove_chars(str1, str2):
str3 = ''
for ch in str1:
if ch not in str2:
str3 += ch
return str3
练习5:写一个函数,生成指定长度的验证码,验证码由英文字母和数字构成。
import random
def gen_vccode(length=4):
all_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
selected_chars = random.choices(all_chars, k=length)
return ''.join(selected_chars)
练习6:写一个函数,返回给定文件名的后缀名(扩展名)。
def get_suffix(filename):
pos = filename.rfind('.')
return filename[pos + 1:] if pos > 0 else ''
练习7:写一个函数,传入圆的半径,返回圆的周长和面积。
import math
def calc_circle(radius):
return 2 * math.pi * radius, math.pi * radius * radius
练习8:写一个函数,传入两个正整数,返回两个数的最大公约数。
def gcd(x, y):
while y % x != 0:
x, y = y % x, x
return x
练习9:写一个函数,判断传入的正整数是不是素数,返回布尔值。
def is_prime(num):
for factor in range(2, int(num ** 0.5) + 1):
if num % factor == 0:
return False
return num != 1
练习10:写一个函数,判断传入的正整数是不是回文数,返回布尔值。
说明:12321是一个回文数,因为从左向右和从右向左读,结果是一样的。
def is_palindrome(num):
total, temp = 0, num
while temp > 0:
total *= 10
total += temp % 10
temp //= 10
return num == total
练习11:写一个函数,传入一个列表,返回列表中最大的和第二大的元素,不允许使用Python内置的排序和最大函数。
def find_max_two(items):
first, second = (items[0], items[1]) if items[0] >= items[1] \
else (items[1], items[0])
for index in range(2, len(items)):
if items[index] > first:
second = first
first = items[index]
elif items[index] > second:
second = items[index]
return first, second
练习12:写一个函数,实现对字符串的加密,假设字符串中只有小写英文字母和空格,加密规则是a
变d
,b
变e
,c
变f
,……,x
变a
,y
变b
,z
变c
,空格保持不变。
def encrypt(message):
result = ''
for ch in message:
if ch == ' ':
result += ch
elif 'a' <= ch <= 'w':
result += chr(ord(ch) + 3)
else:
result += chr(ord(ch) - 23)
return result