1、实现二进制与十进制的转换
输入:
s = input("请输入一个由0和1组成的二进制字符串:")
d = int(s, base = 2)
while s:
d = d + 0
s = s[1:]
print(f"转换成十进制的数为: { d } ")
输出:
2、实现字符串到字节以及字节到字符串的转换方式(两种方式)
方法一:
str_data = "你好"
bytes_data = bytes(str_data, 'utf-8')
print(bytes_data)
str_data = bytes_data.decode()
print(str_data)
输出:
方法二
str_data1 = "你好"
bytes_data1 = str_data1.encode(encoding="utf-8")
print(bytes_data1)
str_data1 = bytes_data1.decode()
print(str_data1)
输出:
3、python中几种异常的处理
1、ZeroDivisionError
try: 1/0 except ZeroDivisionError: print("Division by zero")
输出:
# 2、元素键异常
dict_data = {"1": 2, "2": 3, "3": 4}
print(dict_data.get("4", "不存在此键"))
输出:
# 3、IndexError list_data = [1, 2, 3] try: print(list_data[3]) except IndexError: print("索引超出范围") 输出:
# 4、若没有遇到异常则输出Normal try: a = int(input('请输入第一个整数')) b = int(input('请输入第二个整数')) result = a / b print('结果为:', result) except ZeroDivisionError as e: print("difficulty") else: print("Normal") 输出:
# 5、无论异常或正常则输出finally try: a = int(input('请输入第一个整数')) b = int(input('请输入第二个整数')) result = a / b print('结果为:', result) print("Finally") except ZeroDivisionError: print('Finally') 输出:
# 4、利用format打印如下列表 print_list = [ {"name": "zhangsan", "stu_id": "04101041", "score": "[90, 80, 100]"}, {"name": "lisi", "stu_id": "04104042", "score": "[70, 80, 90]"}, {"name": "wangwu", "stu_id": "04101043", "score": "[76, 90, 80]"} ] print("{0:^10}{1:^10}{2:^10}{3:^10}{4:^10}".format("stu_id", "name", "chinese", "math", "english")) print("{0:^10}{1:^10}{2:^10}{3:^10}{4:^10}".format("04101041", "zhangsan", "90", "80", "100")) print("{0:^10}{1:^10}{2:^10}{3:^10}{4:^10}".format("04104042", "lisi", "70", "80", "90")) print("{0:^10}{1:^10}{2:^10}{3:^10}{4:^10}".format("0411043", "wangwu", "76", "90", "80"))
输出: