Python练习题
程序员文章站
2022-07-01 17:09:11
...
# 2. 把2.918 转化为整形
# ❖
mun_a=2.918
mun_b=int(mun_a)
print(mun_b)
# 3. 把10 进制数 18 转化为2进制数
# ❖
mun_c=18
print('10 进制数 18 转化为2进制数为:',bin(int(mun_c)))
# 4. ⽤java 替换字符串:”Python is popular” ⾥⾯的Python,并
# 把java 变换成JAVA
# ❖
str_a='Python is popular'
str_b=str_a.split()
# print(str_b)
str_c = str_a.replace("Python", "java".upper())
print(str_c)
# 5. 把列表 [1, 2, 3,4 5,6,7,8]⾥⾯的2, 4, 6,8 打印出来
list_01=[1, 2, 3,4,5,6,7,8]
list_02=[]
for i in list_01:
if i%2==0:
list_02.append(i)
print(list_02)
# ❖
# 6. 创建⼀个字典,字典的key分别是name, sex, province , 修改
# ❖
# 原始province 的值 为新值”江苏”
dict_01={"name":"张三","sex":"12","province":"安徽"}
dict_01["province"]="江苏"
print(dict_01)
# 作业2
# ❖
# 1. Test_str=“Python was created in 1989, Python is using in AI, big
# data, IOT.” 按下列要求对上⾯⽂字做出处理。
# ❖
# • 把上⾯⽂字中的所有⼤写转化为⼩写
# ❖
# • 把这段话每个单词放到列表⾥⾯,不能包含空格。
# ❖
# • 把列表最中间的⼀个单词打印出来。
# ❖
Test_str="Python was created in 1989, Python is using in AI, big data, IOT."
Test_str_01=Test_str.lower()
print(Test_str_01)
list_03=Test_str.replace(","," ").split()
print(list_03)
str_middle = list_03[int(len(list_03)/2)]
print("最中间的单词是:", str_middle)
# 2. List1=[“python”, 5,6, 8], list2=[“python”,”5”, 6, 8,10], 对list1和 list2做出如下处理:
# ❖
# • 把上⾯2个list的内容合并成⼀个
# ❖
# • 利⽤set⾥⾯的⽅法,对合并后的list, 去除重复元素。最 后输出是还
# 是list =[“python”, 5,6, 8,”5”,10] (顺序可以不⼀ 样)
List1=["python", 5,6, 8]
list2=["python","5", 6, 8,10]
list3=List1+list2
print(list3)
print('去除重复元素。最 后输出:',set(list3))
#把1000-2500之间,既能被7整除,也能被5整除的数取出来,放到一个列表输出
li=[]
for num in range(1000,2501):
if num%5==0 and num%7==0:
li.append(num)
print(li)
#打印出0-20之间的数字,如果此数字能被3整除,输出英文”three”, 如果能被5整除,输出”five”,如果既能被3整除也
# 能被5整除,输出”threes+fives”, 要求用到continue
# 1 2
# Threes
# 4
# fives
# Threes
# 7 … 1
# 4
# Thees+fives
for num_01 in range(21):
if num_01%3==0:
print('three')
continue
elif num_01%5==0:
print('fives')
continue
elif num_01%3==0 and num_01%5==0:
print("threes+fives")
continue
print(num_01)
# 作业3
# ❖
# 1. 实现⼀个函数,要求对⼀个列表⾥⾯所有数字求和,如果⾥ ⾯含有⾮数字的
# 元素。直接跳过。⽐如[1,2,3] 输出是5, 如果 是[1,2,4,”a”] 输出是7。 并在另外
# ⼀个包(⽬录)⾥⾯调⽤这个 函数
def sum_01(li):
sum = 0
for num in li:
if isinstance(num, int):#isinstance() 函数来判断一个对象是否是一个已知的类型
sum += num
print('⼀个列表⾥⾯所有数字求和',sum)
if __name__ == '__main__':
sum_01([1,2,4])
# ❖
# 2. 已有字典dic={“name”:”xiaozhang ”,”sex”:”male”}, 访问字典 dic[“grade”],, 通过try… exception 把异常信息打印出来
dic = {"name": "xiaozhang", "sex": "male"}
try:
dic["grade"]
except KeyError as e:
print(e)
# ❖
# 3. 实现⼀个不定长参数的函数def flexible(aa, *args, **kwargs):,
# ❖
# 把传⼊的参数和值打印出来。⽐如传⼊参数是
# ❖
# flexible(aa, 2, 3, x = 4, y = 5, *[1, 2, 3], **{'a':1,'b': 2})
# ❖
# 输出结果:(2, 3, 1, 2, 3),{'a': 1, 'y': 5, 'b': 2, 'x': 4}
def flexible(aa, *args, **kwargs):
print(aa, args, kwargs)
if __name__ == '__main__':
flexible('aa', 2, 3, x=4, y=5, *[1, 2, 3], **{'a': 1, 'b': 2})
答案: