1.实验任务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='-') 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)] print('-'.join(y1)) print('字符输出2:',end='') y2=[str(i).zfill(2) for i in range(10)] print('-'.join(y2))
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=' ')
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))
思考:
1.random.randint(1,100)生成的随机整数范围是?是否包括100?利用range(1,100)生成的有序序列范围是?是否包括100?
答:1<=x<=100。包括。1<=x<100。不包括。
2.使用集合解析形式s={random.randint(1,100) for i in range(5)}生成集合,len(s)一定是5吗?
答:不一定。
import random print('用集合存储随机整数:') while True: s={random.randint(1,100) for i in range(5)} print(s) if len(s)<5: break
2.实验任务2
x = [0,1] i = 1 while True: x1 = x[i-1] + x[i] if x1 > 1000: break x.append(x1) i += 1 m=1 for n in x: print(f'{n:4d}', end = '' if m % 5 else '\n') m+=13. 实验任务3
import random x = random.randint(1,31) y = int(input('猜猜2021年5月哪一天会是你的lucky day:) \n你有三次机会,猜吧(1~31):')) i=1 while i<=2: if y==x: print('猜对啦') break elif y<x: print('猜早啦,你的lucky day还早呢') y=int(input('再猜再猜:')) elif y>x: print('猜晚啦,你的lucky day在前面') y = int(input('再猜再猜:')) i+=1 else: if y==x: print('猜对啦') elif y<x: print('猜早啦,你的lucky day还早呢') print('次数用完啦') print(f'2021年5月你的lucky day是{x}号') elif y>x: print('猜晚啦,你的lucky day在前面') print('次数用完啦') print(f'2021年5月你的lucky day是{x}号')4. 实验任务4
x,y=eval(input('输入十进制整数x和转换的进制n(2或8或16):')) print('{}的{}进制是:'.format(x,y),end='') p=[] while x: c=x%y p.append(c) x=x//y if y==16: i=len(p)-1 while i>=0: if p[i]>9: q=['A','B','C','D','E','F'] m=p[i]-10 print(q[m],end='') else: print(p[i],end='') i-=1 else: i=len(p)-1 while i>=0: print(p[i],end='') i-=1