实验3
任务1
#格式控制,列表解析,类型转换 x = list(range(10)) print('整数输出1: ',end = '') for i in x: print(i,end=' ') print('\n整数输出2: ',end = '') for i in x: print(f'{i:02d}',end='-')#指定每个整数输出宽度站两列,不足两列,左边补0 print('\n整数输出3: ',end = '') for i in x[:-1]: print(f'{i:02d}',end='-') print(f'{x[-1]:02d}') print('\n字符输出1: ',end = '') y1=[str(i)for i in range(10)]#函数str()用于把其他类型对象转换成字符串对象 print('-'.join(y1)) print('字符输出2: ',end = '') y2=[str(i).zfill(2) for i in range(10)]#方法.zfill()函数用于对字符窜进行格式化,指定列宽为2列,不足左边补0 print('-'.join(y2))
#range对象,列表解析,类型转换,字符串方法 print('整数列表:') x = list(range(97,97+26)) for i in x: print(i, end=' ') print('\n字符列表1: ') lower_alpha = [chr(i) for i in range(97,97+26)] for i in lower_alpha: print(i,end = ' ') print('\n字符列表2: ') upper_alpha = [i.upper() for i in lower_alpha] for i in upper_alpha: print(i,end = ' ')
# 标准库random, string import random import string print('用列表存储随机整数: ') ls = [random.randint(1, 100) for i in range(5)] print(ls) print('\n用集合存储随机整数: ') s = {random.randint(1,100) for i in range(5)} print(s) print('\n\n字母串: ', end = '') alpha = string.ascii_letters print(alpha) print(type(alpha)) print('\n数字串:', end = '') digits = string.digits print(digits) print(type(digits))
import random print('用集合存储随机整数: ') while True: s = {random.randint(1,100) for i in range(5)} print(s) if len(s) < 5: break
思考1:random.randint(1,100)生成的随机整数范围是1到100,包括100。
利用range(1,100)生成的有序序列范围是1,99,不包括100。
2:使用集合解析形式 s = {random.randint(1,100) for i in range(5)} 生成集合,len(s)不一定是5
任务2
x1 = 0 x2 = 1 i=x2 y=2 print(f"{x1:>10} {x2:>10}",end=" ") while i<=1000: x1,x2=x2,i print(f"{i:>10}",end=" ") i=x1+x2 y +=1 if y %5==0: print(end="\n")
任务3
import random y=random.randint(1,31) print(y) x=eval(input("猜猜2021年5月那一天会是你的lucky day:)你有三次机会,猜吧(1,31):")) i=1 while i<3: if x<y: print("猜早啦,你的lucky day还早呢") c=eval(input("再猜再猜:")) i+=1 elif x>y: print("猜晚啦,你的lucky day在前面") x=eval(input("再猜再猜:")) i+=1 else: print("猜对啦") i=4 if i==3 and x<y: print("猜早啦,你的lucky day还早呢,前面次数用完啦") print(f"2021年5月你的lucky day 是{x}号") elif i==3 and x>y: print("猜晚啦,你的lucky day在前面,前面次数用完啦") print(f"2021年5月你的lucky day 是{x}号") else: print("猜对啦")
任务4
s="Remote Interpreter Reinitialized" print(f"{s:*^38}") x,y=eval(input("输入十进制整数x和需要转化的进制n(2或8或16):")) x2,y2=x,y i=1 list=[] list1=["A","B","C","D","E","F"] while i>0: x1=i i=x//y c=x%y x=i if i!=0 and c>=10: c=list1[c-10] list.append(c) elif i!=0 and c<10: list.append(c) else: if x1>10: x1=list1[x1-10] list.append(x1) else: list.append(x1) list.reverse() print(f"{x2}的{y2}进制是",end=":") for i in list: print(f"{i}",end="")