python实例,python实例100例,1.平方根 方法一
python实例,python实例100例,1.平方根 方法一
1.平方根
方法一:
num=float(input(‘请输入数字>>>‘))num_sqrt=num**0.5print(num_sqrt)View Code
方法二:
import cmathnum = int(input(‘>>>‘).strip())num_sqrt=cmath.sqrt(num)print(‘{0}的平方根为{1:0.3f}+{2:0.3f}j‘.format(num,num_sqrt.real,num_sqrt.imag))View Code
2.三角形面积计算
while True: a=float(input(‘三角形第一边长>>>‘)) b=float(input(‘三角形第二边长>>>‘)) c=float(input(‘三角形第三边长>>>‘)) if a+b>c and a-b<c: s=(a+b+c)/2 area=(s*(s-a)*(s-b)*(s-c))**0.5 print(‘面积%f‘%area) break else: print(‘输入的不是三角形‘) continueView Code
3.摄氏转华氏温度
celsius=float(input(‘输入摄氏度>>>‘))fahrenheit=(celsius*1.8)+32print(‘%f摄氏度转为华氏温度为%f‘%(celsius,fahrenheit))View Code
4.判断是不是闰年
year=int(input(‘输入一个年份>>>‘))if(year%4)==0: if(year%100)==0: if(year%400)==0: print(‘{0}是闰年‘.format(year)) else: print(‘不是闰年‘) else: print(‘不是闰年‘)else: print(‘不是闰年‘)View Code
5.打印三角形
max_level=input(‘输入行数>>‘)max_level=int(max_level)for current_level in range(1,max_level+1): for i in range(max_level-current_level): print(‘ ‘,end=‘‘) for j in range(2*current_level-1): print(‘*‘,end=‘‘) print()View Code
6.打印倒三角形
max_level=input(‘输入行数>>‘)max_level=int(max_level)for current_level in range(max_level,0,-1): for i in range(max_level-current_level): print(‘ ‘,end=‘‘) for j in range(2*current_level-1): print(‘*‘,end=‘‘) print()View Code
7.打印九九乘法表
for i in range(1,10): for j in range(1,i+1): print(‘%s * %s = %s‘%(i,j,i*j),end=‘ |‘) print()View Code
8.复制文件
import sysl=sys.argvsource_file_path=l[1]dest_file_path=l[2]with open(r‘%s‘%source_file_path,‘rb‘) as s_f, open(r‘%s‘%dest_file_path,‘wb‘) as d_f: for line in s_f: d_f.write(line)View Code
9.修改文件
方法一:
with open(‘db.txt‘,‘r‘,encoding=‘utf-8‘) as f: data=f.read() data=data.replace(‘SB‘,‘aa‘)with open(‘db.txt‘,‘w‘,encoding=‘utf-8‘) as f: f.write(data)View Code
方法二:
import ostarget_file=r‘db.txt‘intermediary_file=r‘a.txt‘with open(target_file,‘r‘,encoding=‘utf-8‘) as t_f, open(intermediary_file,‘w‘,encoding=‘utf-8‘) as i_f: for line in t_f: if ‘alex‘ in line: line=line.replace(‘alex‘,‘SB‘) i_f.write(line)os.remove(target_file)os.rename(intermediary_file,target_file)View Code
10.购物车
1 import os 2 product_list = [[‘Iphone 7‘, 5800], [‘Coffee‘, 30], [‘疙瘩汤‘, 10], [‘Python Book‘, 99], [‘Bike‘, 199], [‘vivo X9‘, 2499]] 3 shopping_cart = {} 4 current_userinfo = [] 5 6 db_file = r‘db.txt‘ 7 8 while True: 9 print(‘‘‘ 10 1 登陆 11 2 注册 12 3 购物 13 ‘‘‘) 14 15 choice = input(‘>>: ‘).strip() 16 17 if choice == ‘1‘: 18 # 1 登陆 19 tag = True 20 count = 0 21 while tag: 22 if count == 3: 23 print(‘尝试次数过去,退出。。。‘) 24 break 25 uname = input(‘用户名: ‘).strip() 26 pwd = input(‘密码: ‘).strip() 27 28 with open(db_file, ‘r‘, encoding=‘utf-8‘)as f: 29 for line in f: 30 user_info = line.strip(‘\n‘).split(‘,‘) 31 uname_of_db,pwd_of_db,balance_of_db = user_info 32 if uname == uname_of_db and pwd == pwd_of_db: 33 print(‘登陆成功‘) 34 35 # 登陆成功则将用户名和余额添加道列表 36 current_userinfo = [uname_of_db, balance_of_db] 37 print(‘用户信息为: ‘, current_userinfo) 38 tag = False 39 break 40 else: 41 print(‘用户名或密码错误‘) 42 count += 1 43 44 elif choice == ‘2‘: 45 uname = input(‘请输入用户名: ‘).strip() 46 while True: 47 pwd1 = input(‘请输入密码: ‘).strip() 48 pwd2 = input(‘再次确认密码: ‘).strip() 49 if pwd2 == pwd1: 50 break 51 else: 52 print(‘两次输入密码不一致,请重新输入!!!‘) 53 54 balance = input(‘请输入充值金额: ‘).strip() 55 with open(db_file, ‘a‘, encoding=‘utf-8‘) as f: 56 f.write(‘%s,%s,%s\n‘ % (uname, pwd1, balance)) 57 58 elif choice == ‘3‘: 59 if len(current_userinfo) == 0: 60 print(‘请先登陆。。。‘) 61 else: 62 # 登陆成功后,开始购物 63 uname_of_db = current_userinfo[0] 64 balance_of_db = current_userinfo[1] 65 print(‘尊敬的用户[%s] 您的余额为[%s],祝您购物愉快‘ % (uname_of_db, balance_of_db)) 66 67 tag = True 68 while tag: 69 for index, product in enumerate(product_list): 70 print(index, product) 71 choice = input(‘输入商品编号购物,输入q退出>>: ‘).strip() 72 if choice.isdigit(): 73 choice = int(choice) 74 if choice < 0 or choice >= len(product_list): continue 75 76 pname = product_list[choice][0] 77 pprice = product_list[choice][1] 78 if balance_of_db > pprice: 79 if pname in shopping_cart: # 原来已经购买过 80 shopping_cart[pname][‘count‘] += 1 81 else: 82 shopping_cart[pname] = {‘pprice‘: pprice, ‘count‘: 1} 83 84 balance_of_db -= pprice # 扣钱 85 current_userinfo[1] = balance_of_db # 更新用户余额 86 print( 87 "Added product" + pname + "into shopping cart,your current balance" + str( 88 balance_of_db)) 89 else: 90 print("买不起,穷逼!产品价格是{price},你还差{lack_price}".format(price=pprice, 91 lack_price=(pprice - balance_of_db))) 92 print(shopping_cart) 93 elif choice == ‘q‘: 94 print(‘‘‘ 95 --------———已购买商品列表--———————— 96 id 商品 数量 单价 总价 97 98 ‘‘‘) 99 total_cost = 0100 for i, key in enumerate(shopping_cart):101 print(‘%22s%18s%18s%18s%18s‘ % (102 i,103 key,104 shopping_cart[key][‘count‘],105 shopping_cart[key][‘pprice‘],106 shopping_cart[key][‘pprice‘] *shopping_cart[key][‘count‘]107 ))108 total_cost += shopping_cart[key][‘pprice‘] * shopping_cart[key][‘count‘]109 110 print(‘‘‘111 你的总花费: %s112 你的余额为: %s113 -----------------------end----------------------- 114 ‘‘‘ % (total_cost, balance_of_db))115 116 while tag:117 inp = input(‘确认购买(yes/no?)..: ‘).strip()118 if inp not in [‘Y‘, ‘N‘, ‘y‘, ‘n‘, ‘yes‘, ‘no‘]: continue119 if inp in [‘Y‘, ‘y‘, ‘yes‘]:120 # 将余额写入文件121 122 src_file = db_file123 dst_file = r‘%s.swap‘ % db_file124 with open(src_file, ‘r‘, encoding=‘utf-8‘) as read_f, 125 open(dst_file, ‘w‘, encoding=‘utf-8‘) as write_f:126 for line in read_f:127 if line.startswith(uname_of_db):128 l = line.strip(‘\n‘).split(‘,‘)129 l[-1] = str(balance_of_db)130 line = ‘,‘.join(l) + ‘\n‘131 132 write_f.write(line)133 os.remove(src_file)134 os.rename(dst_file, src_file)135 136 print(‘购买成功,请耐心等待发货‘)137 138 shopping_cart = {}139 current_userinfo = {}140 tag = False141 else:142 print(‘输入非法‘)143 else:144 print(‘非法操作‘)View Code
11.注册(函数)
1 db_path=‘db.txt‘ 2 def uname(): 3 while True: 4 uname = input(‘username>>>‘).strip() 5 if not uname.isalnum():continue 6 with open(r‘%s‘%db_path,‘r‘,encoding=‘utf-8‘)as f: 7 for line in f: 8 if line.startswith(uname): 9 print(‘该用户已注册,请重新输入‘)10 break11 else:12 return uname13 14 def upwd():15 while True:16 upwd1=input(‘password>>>‘).strip()17 upwd2=input(‘confirm password>>>‘).strip()18 if upwd1==upwd2:19 return upwd120 else:21 print(‘输入不一致,请重新输入‘)22 23 def balance():24 balance=input(‘请输入充值金额>>>‘).strip()25 if balance.isdigit():26 return balance27 28 def db_handle(*args):29 info=‘:‘.join(args)30 with open(r‘%s‘%db_path,‘a‘,encoding=‘utf-8‘) as f:31 f.write(‘%s\n‘ %(info))32 33 def interactive():34 username=uname()35 password=upwd()36 user_balance=balance()37 return username,password,user_balance38 39 username,password,user_balance=interactive()40 print(username)41 print(password)42 print(user_balance)43 44 db_handle(username,password,user_balance)View Code
12.昨天是哪天
1 import datetime2 def get_yesterday():3 today=datetime.date.today()4 oneday=datetime.timedelta(days=1)5 yesterday=today-oneday6 return yesterday7 8 print(get_yesterday())View Code
13.计算某月的第一天是星期几,该月有几天
1 import calendar2 year=int(input(‘输入年份>>>‘).strip())3 mon=int(input(‘输入月份>>>‘).strip())4 month_range=calendar.monthrange(year,mon)5 week,num=month_range6 print(‘该月的第一天是星期{week},该月有{num}天‘.format(week=week+1,num=num))7 cal=calendar.month(year,mon)8 print(‘该月的日历为:‘)9 print(cal)View Code
python实例
相关内容
- 安装python性能检测工具line_profiler,python中line,line_prof
- Python绘制五星红旗,什么的五星红旗,# -*- codi
- 如何让你的Python代码更加pythonic ?,怎样让代码高亮显
- Python安装numpy模块及pycharm配置,,查看Python版本
- python拉格朗日插值,,#拉格朗日插值代码i
- 【Python】使用Python进行主成分分析,,使用sklearn库
- 数据标准化 (data normalization) 的原理及实现 (Python sklea
- Python——Label控件说明,控件是,Anchor :
- 一:python (int & str 的方法),python的int,1.变量:
- python之面向对象,python是面向对象吗,(一)构造方法和
评论关闭