1、猜拳游戏
####猜拳游戏
"""
1.从控制台输入要出的拳 ---石头(1)/剪刀(2)/布(3)
2.电脑随即出拳--先假定电脑只会出石头,完成整体代码功能
3.比较胜负
石头 胜 剪刀
剪刀 胜 布
布 胜 石头
"""
import random
player = int(input('Your Choice:'))
computer = random.randint(1,3)
print(computer)
if((player == 1 and computer == 2) or (player == 2 and computer == 3)
or (player == 3 and computer == 1)):
print('player win')
elif player == computer:
print('no winner')
else:
print('computer win')
2、输出1 2 3 4 组成的不同书记的三位数的个数
##数字统计
"""
有1,2,3,4四个数字
求这四个数字能生成多少个互不相同且无重复数字的三位数(不能含有122,
133这种)
"""
count = 0
for i in range(1,5):
for j in range(1,5):
for x in range(1,5):
if i != j and j != x and i != x:
print(i * 100 + j * 10 + x)
count += 1
print('The count is: %d' %count)
3、用户登录验证
##验证已经给定的用户
"""
用户登陆程序需求:
1. 输入用户名和密码;
2. 判断用户名和密码是否正确? (name='root', passwd='westos')
3. 为了防止暴力破解, 登陆仅有三次机会, 如果超过三次机会,
报错提示;
"""
for i in range(3):
name = input('UserName:')
passwd = input('Password:')
if name == 'root' and passwd == 'westos':
print('Login success')
break
else:
print('Login failed')
print('%d chance last' %(2 - i))
else:
print('Please try later!')
4、模拟命令行操作
##模拟Linux命令行操作
import os ##调用系统模块
for i in range(1000):
cmd = input('[root@python test]$ ')
if cmd:
if cmd == 'exit':
print('logout')
break
else:
print('run %s' %(cmd))
os.system(cmd)
else:
continue
5、求最大公约数
##求最大公约数 采用枚举法求解
First_ _num = int(input ( 'first number:'))
Second_ _num = int(input ( ' second number:'))
for i in range_ ( min ( First. _num,Second. _num), max ( First_ _num, Second_ num)):
if First__num%i==0 and Second_.num%i==0:
num=i
continue
print (num)
6、输出
*
**
***
***
**
*
##输出结果
row = 1
while row <= 3:
col = 1
while col <= row:
print('*', end = '') ##以' '结尾
col += 1
print('')
row += 1
row = 1
while row <= 3:
col = 3
while col >= row:
print('*', end = '')
col -= 1
print('')
row += 1
7、猜字游戏
"""
猜数字游戏
1. 系统随机生成一个1~100的数字;
2. 用户总共有5次猜数字的机会;
3. 如果用户猜测的数字大于系统给出的数字,打印“too big”;
4. 如果用户猜测的数字小于系统给出的数字,打印"too small";
5. 如果用户猜测的数字等于系统给出的数字,打印"恭喜",并且退
出循环;
"""
import random
count = 0
computer = random.randint(1,100)
while trycount < 5:
player = int(input('Num:'))
count +=1
if player > computer:
print('too big')
elif player < computer:
print('too small')
else:
print('Congratulation!')
break
8、回文数
##检测输入的数是否为回文数
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不
是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。
"""
num = input('Num:')
if num == num[::-1]:
print('ok')
else:
print('failed')
9、判断一个字符串是否可做变量
##判断输入字符串是否符合变量要求
"""
变量名是否合法:
1.变量名可以由字母,数字或者下划线组成
2.变量名只能以字母或者下划线开头
s = 'hello@'
1.判断变量名的第一个元素是否为字母或者下划线 s[0]
2.如果第一个元素符合条件,判断除了第一个元素之外的其他元素s[1:]
"""
while True:
str = input ('your need check str("exit" to quit):')
if str == 'exit' :
print ('Logout')
break
if str[0] == '_' or str[0]. isalpha():
for i in str[1:]:
if i.isalnum() or i == '_':
continue
eLse:
print ('Can\'t use to var.')
break
else:
print ( '0K')
else:
print ('Can\'t use to var.')
10、判断一个学会生是否合格
"""
给定一个字符串来代表一个学生的出勤纪录,这个纪录仅包含以下三个字符>:
'A' : Absent,缺勤
'L' : Late,迟到
'P' : Present,到场
如果一个学生的出勤纪录中不超过一个'A'(缺勤)并且不超过两个连续的'L'(迟到),
那么这个学生会被奖赏。
你需要根据这个学生的出勤纪录判断他是否会被奖赏。
示例 1:
输入: "PPALLP"
输出: True
示例 2:
输入: "PPALLL"
输出: False
"""
str = input()
if s.count('A') <= 1 and s.count('LLL') == 0:
print(True)
else:
print(False)
11、句子翻转
"""
- 题目描述:
> 给定一个句子(只包含字母和空格), 将句子中的单词位置反转,单词用
空格分割, 单词之间只有一个空格,前后没有空格。
比如: (1) “hello xiao mi”-> “mi xiao hello”
- 输入描述:
> 输入数据有多组,每组占一行,包含一个句子(句子长度小于1000个字符)
- 输出描述:
> 对于每个测试示例,要求输出句子中单词反转后形成的句子
- 示例1:
```
- 输入
hello xiao mi
- 输出
mi xiao hello
"""
##1
str = input().split()
print(' '.join(str[::-1]))
##2
print(' '.join(input().split()[::-1]))
12、删除和替换字符串中的指定字符
"""
- 题目描述:
输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例如,>输入”They are students.”和”aeiou”,
则删除之后的第一个字符串变成”Thy r stdnts.”
- 输入描述:
每个测试输入包含2个字符串
- 输出描述:
输出删除后的字符串
- 示例1:
```
输入
They are students.
aeiou
输出
Thy r stdnts.
```
"""
First_ str = input (' input first str:')
Second_ str = input ( ' input second str:')
for i in First. _str[:]:
if i in Second_ str[:]:
First_ _str = First_ str.replace(i,"')
print (First_ str)
13 、 小学数学训练
"""
1. 设计一个程序,帮助小学生练习10以内的加法
详情:
- 随机生成加法题目;
- 学生查看题目并输入答案;
- 判别学生答题是否正确?
- 退出时, 统计学生答题总数,正确数量及正确率(保留两>位小数点);
"""
import random
count = 0
right = 0
while True:
a = random. randint(0,9)
b = random . randint(0, 9)
print ('%d+%d= ' %(a,b))
answer = input_ ("your answer('exit') to quit:")
count +=1
if answer == 'exit' :
print_ ('you all do %d questions, right pre: %.2f%%' %(count-1, (right / (count-1))*100))
break
elif int(answer) == (a + b):
print (' Congradlations!')
right +=1
else:
print_ ('False!')
14、列表输出
"""
假定有下面这样的列表:
names = ['fentiao', 'fendai', 'fensi', 'apple']
输出结果为:'I have fentiao, fendai, fensi and apple.'
"""
names = ['fentiao', 'fendai', 'fensi', 'apple']
print('I have ' + ', '.join(names[:-1]) + ' and ' + names[-1])
15、用户登录认证
"""
1.系统里面有多个用户,用户的信息目前保存在列表里面
users = ['root','westos']
passwd = ['123','456']
2.用户登陆(判断用户登陆是否成功
1).判断用户是否存在
2).如果存在
1).判断用户密码是否正确
如果正确,登陆成功,推出循环
如果密码不正确,重新登陆,总共有三次机会登陆
3).如果用户不存在
重新登陆,总共有三次机会
"""
user = [ ' root', 'Linux']
passwd = [ 123', '456']
User_ input = input( ' PLease input user:')
if User_ input in user:
for i in range(3):
Password = input('PLease input your user\'s password: ' )
if Password == passwd[user. index (User. _input)] :
print_ ('%s Login success!' %(User. input))
break
else:
print ('Your password can\'t Login.')
print ('You have %d changes.' %(2 - i))
eLse:
print ('Your input user not in BASEDATA.')
16、学生用户管理
"""
# 1. 后台管理员只有一个用户: admin, 密码: admin
# 2. 当管理员登陆成功后, 可以管理前台会员信息.
# 3. 会员信息管理包含:
# 添加会员信息
# 删除会员信息
# 查看会员信息
# 退出
"""
user = input ( 'PLease input your ID:')
passwd = input (' PLease input your ID password: ')
users = ['linux', 'windos', 'uinux']
password = [ '123', '456', '789']
if user == ' admin' and passwd == ' admin' :
while True:
print ( 'Welcome to DASEDATA' .center(50, '*' ))
print ("""
Choise list:
1. add user
2. delete user
3. view user list
4. quit
""")
Choise = int (input('PLease input your choise:'))
if Choise == 1:
add_ _user = input ( 'add user name: ' )
if add_ user in users:
print ( 'your add user in BASEDATA,not to add again.')
continue
else:
users.append(add_ user)
add_ passwd = input (' PLease input your user password: ' )
password.append(add_ passwd)
print ( 'Add user success!' )
continue
elif Choise == 2:
del_user = input( 'delete user name: ')
if del_user not in users:
print ('You can\'t deLete not exit user.1)
else:
password.pop(users . index(del_ user))
users. remove (deL_ user)
print ('User delete success!')
continue
elif Choise == 3:
view_ user = input ( 'PLease input your want to view user(all can view all user):')
if view_ user == 'all' :
print ( ' username: ' , users)
print (' userpassword: ', password)
continue
else:
print ('username: ' , users[users. index(view_ user)])
print (' userpassword: ' , password[users. index(view_ user)])
continue
else:
break
else:
print_ ('You have no power to do for this BASEDATA. ' )
17、随机找人
"""
明明想在学校中请一些同学一起做一项问卷调查,为了实验的客观性
他先用计算机生成了N个1~1000之间的随机整数(N<=1000),N是用户输入的,
对于
其中重复的数字,只保留一个,把其余相同的数字去掉,不同的数对应着不>同的学生的学号,然后再把这些
数从小到大排序,按照排好的顺序去找同学做调查,请你协助明明完成“去重
”与排序工作
"""
import random
set. _list = set([ ])
for i in range(int(input('N:'))):
set_ list . add(random. randint(1, 1000))
print (sorted(set _list))
18、统计重复数
"""
数字重复统计:
1). 随机生成1000个整数;
2). 数字的范围[20, 100],
3). 升序输出所有不同的数字及其每个数字重复的次数;
"""
import random
all_nums = []
for item in range(1000):
all_nums.append(random.randint(20,100))
sorted_nums = sorted(all_nums)
num_dict = {}
for num in sorted_nums:
if num in num_dict:
num_dict[num] += 1
else:
num_dict[num] = 1
print(num_dict)
19 、统计一句话中,单词出现的评率
"""
重复的单词: 此处认为单词之间以空格为分隔符, 并且不包含,和.;
# 1. 用户输入一句英文句子;
# 2. 打印出每个单词及其重复的次数;
"hello java hello python"
# hello 2
# java 1
# python 1
"""
char_ name = input ('Your check:')
char_ dirc = {}
for item in char. name.split(' '):
if item in char_ dirc:
char_ dirc[item] += 1
else:
char_ dirc[item] = 1
print (char. dirc. items())
20、生成银行卡号
"""
1.生成100个卡号;
卡号以6102009开头, 后面3位依次是 (001, 002, 003, 100),
2. 生成关于银行卡号的字典, 默认每个卡号的初始密码为"redhat";
3. 输出卡号和密码信息, 格式如下:
卡号 密码
6102009001 000000
"""
account_num = []
for i in range(100):
acount_num.append('6102009%.3d' %(i+1))
account_info = {}.formkeys(acount_num,'redhat')
print ('卡号:'\t\t '密码:')
for i,v in account.info.items():
print(i,'\t\t',v)
21、查询平均数,并输出大于平均数的所有数
"""
编写一个函数cacluate, 可以接收任意多个数,返回的是一个元组.
元组的第一个值为所有参数的平均值, 第二个值是大于平均值的所有数.
"""
def cacluate(*args):
avg = sum(args) / len(args)
Mavg = []
for item in args:
if item > avg:
Mavg.append(item)
return avg, Mavg
print (cacluate(1,2,3,4,3,6,8,0))
22、统计大小写
"""
编写一个函数, 接收字符串参数, 返回一个元组,'ehllo WROLD'
元组的第一个值为大写字母的个数, 第二个值为小写字母个数.
"""
def fun(s):,
count_ _min = 0
count_ _max = 0
for i in s:
if i.isupper():
count_ _max += 1
elif i.islower():
count_ _min +=1
eLse:
continue
return count_ _max, count_ min
print(fun('hello WORLD'))
23、抽奖游戏
"""
模拟轮盘抽奖游戏
# 轮盘分为三部分: 一等奖, 二等奖和三等奖;
# 轮盘转的时候是随机的,
# 如果范围在[0,0.08)之间,代表一等奖,
# 如果范围在[0.08,0.3)之间,代表2等奖,
# 如果范围在[0.3, 1.0)之间,代表3等奖,
# 模拟本次活动1000人参加, 模拟游戏时需要准备各等级奖品的个数.
"""
import random
win_dirc = {
'1':(0,0.08),
'2':(0.08,0.3),
'3':(0.3,1)
}
def userfun():
num = random.random( )
for k,v in win_dirc.items():
if v[0] <= num <v[1]:
return k
result_dir = {}
for item in range(1000):
res = userfun()
if res in result_ dir:
result_dir[res] += 1
eLse:
result_dir[res] = 1
for k,V in result_ dir. items():
print (k,'----->',v)
24、判断一个数是否为质数
"""
题目描述:
给定一个正整数,编写程序计算有多少对质数的和等于输入的这个正整数,>并输出结果。输
入值小于1000。
如,输入为10, 程序应该输出结果为2。(共有两对质数的和为10,分别为(5,5),(3,7))
# [2,3,5,7]
- 输入描述:
输入包括一个整数n,(3 ≤ n < 1000)
- 输出描述:
输出对数
- 示例1 :
```
输入:
10
输出:
2
"""
num = int(input())
def isPrime(num):
for i in range(2,num):
if num % i == 0:
return False
else:
return True
primeli = [i for i in range(2,num) if isPrime(i)]
primecount = 0
for item in primeli:
if (num - item) in primeli and item <= num - item:
primecount += 1
print(primecount)
25、将字典中的所有字母相同的值,加起来
##大小写key值合并,统一以小写输出
d = dict(a=2, b=1, c=2, B=9, A=10)
print({k.lower(): d.get(k.lower(), 0) + d.get(k.upper(), 0) for k in d})
26、统计学生分数
"""
# 需求1:假设有20个学生,学生名为westosX,学生分数在60~100之间,筛选出
#成绩在90分以上得学生
"""
import random
###普通方法
stuInfo = {}
for i in range(20):
name = 'linux' + str(i)
score = random.randint(60,100)
stuInfo[name] = score
highscore = {}
for name,score in stuInfo.items():
if score > 90:
highscore[name] = score
print(highscore)
##字典生成式方法
print({name: score for name,score in stuInfo.items() if score > 90})
27、计算阶乘
##定义阶乘函数
def fun(x):
res = 1
for i in range(1,x+1)
res *= i
return res
li = [random.randint(2,7) for item in range(10)] ##随机取10个2~7之间的数
print (list(map(fun,li)))
28、设置当第一个排序树=数相同时,按第二个数进行排序
info = [
# 商品名称 商品数量 商品价格
('apple1',200,32),
('apple2',40,12),
('apple3',40,2),
('apple4',1000,23),
('apple5',40,5)
]
def sorted_by_count_price(x):
return x[1],x[2]
print(sorted(info,key=sorted_by_count_price))
29、设置排序方式,将序列中的所有0排到最后,不改变原排序方式
"""
给定一个整形数组, 将数组中所有的0移动到末尾, 非0项保持不变;
在原始数组上进行移动操作, 勿创建新的数组;
# 输入:
第一行是数组长度, 后续每一行是数组的一条记录;
4
0
7
0
2
# 输出:
调整后数组的内容;
4
7
2
0
0
"""
n = ". join(input() . split())
li = [int(i) for i in n]
def move_ zero(x):
if x == 0:
return 2
else:
return 1
print (sorted(li,key = move_ zero))
30、匿名函数练习
print (reduce(Lambda x,y: x+y,[1,2,3,4,5]) ###将1 2345累加
print (list(map(lambda X:x**2, range(5)))) ###计算01 23 4的平方
linfo =[
('linux01' ,200,1),
('Linux08' ,100,8),
('linux17',5,100),
('linux05',60, 99),
( 'linux10',111,26)
]
print (sorted(info, key=Lambda x:x[1], reverse=True))
###将info按照第二列关键字排序
31、生成‘验证码’
###生成验证码
import random
import string
code_str = string.ascii_letters + string.digits
####方法一####
def gen_code(len=4):
code = ''
for i in range(len):
new_s = random.choice(code_str)
code += new_s
print([gen_code(len=6) for i in range(10)])
###方法二###
def gen_code(len=4):
return ''.join(random.sample(code_str,len))
print([gen_code() for i in range(10)])
32、通过装饰器计算一个函数的运行时间
##通过装饰器计算函数运行时间
def time_ test(func):
def wrapper(*args , **kwargs):
str_ time = time . time()
res = func_ (*args , **kwargs) ##返回函数的结果
end_ time = time . time()
print(' Runing time:%.6f' %(end_ time - str. _time))
return res
return wrapper
@time_test
def fun_ list(n):
return [2 * i for i in range(n)]
print(fun. _list(10000))
33、通过装饰打印函数信息
"""
# 创建装饰器, 要求如下:
# 1. 创建add_log装饰器, 被装饰的函数打印日志信息;
# 2. 日志格式为: [字符串时间] 函数名: xxx, 运行时间:xxx, 运行返回
值结果:xxx
"""
import time
import functools
def add. _log(func):
@functools . wraps(func)
def wrapper(*agrs , **kwagrs):
start_ time = time. time ()
res = func(*agrs , **kwagrs)
end_ .time = time. time()
print('[%s] name:%s , Runing time:%. 6f, result:%d.'
%(time . ctime (), func._. name_ . , end. time-start. _time , res))
return res
return wrapper
@add. _log
def add(x,y):
time . sleep(1)
return x+y
add(1,15)
34、输入类型判断
"""
编写装饰器required_types, 条件如下:
# 1). 当装饰器为@required_types(int,float)确保函数接收到的每一>个参数都是int或者float类型;
# 2). 当装饰器为@required_types(list)确保函数接收到的每一个参数
都是list类型;
# 3). 当装饰器为@required_types(str,int)确保函数接收到的每一个>参数都是str或者int类型;
# 4). 如果参数不满足条件, 打印 TypeError:参数必须为xxxx类型
"""
import functools
def required_type(*kind):
def require (func):
@functools . wraps (func)
def wrapper(*args , **kwargs):
for i in args:
if not isinstance(i, kind):
print('TypeError:must%s,%s' %kind)
exit( )
else:
res = func(*args , **kwargs)
return res
return wrapper
return require
@required_ type(int, int)
def add(a,b):
add(1,15)
return a + b
print(add(1,2))
35、通过Python建立新文件
"""
创建文件data.txt,文件共100000行,每行存放一个1~100之间的整数
"""
import random
##方法1
f = open('data.txt','w+')
for i in range(100000):
f.write(str(random.randint(1,100)) + '\n')
f.seek(0)
print(f.read())
f.close()
##方法2
with open ('data1.txt', 'w+川) as f1:
for i in range (100000):
f1.write(str(random. randint(1,100)) + '\n')
f1. seek(0)
36、创建ip字段,并排序
"""
# 1. 生成一个大文件ips.txt,要求1200行, 每行随机为172.25.254.0/24段的ip;
# 2. 读取ips.txt文件统计这个文件中ip出现频率排前10的ip;
"""
import random
##创建ip文件
def create_ ip_ file(filename):
ip = ['172.25.254.' + str(i) for i in range(1,255)]
with open (filename, 'a+') as f:
for i in range (1200) :
f . write(random. sampLe(ip,1)[0] +'\n')
create_ ip_ file('ips.txt')
##排序
ips_ dict = {}
def sorted. by_ ip(file_ name , count=10) :
with open(file_ name) as f:
for ip in f:
if ip in ips_ dict:
ips_ dict[ip] += 1
else:
ips_ dict[ip] = 1
sorted_ _ip = sorted(ips. dict. items(),key. =_ lambda x:x[1],
reverse_ =_ True)[ : count]
return sorted_ .ip
print(sorted_ _by_ ip( 'ips.txt'))
37、生成MAC地址
"""
生成100个MAC地址并写入文件中,MAC地址前6位(16进制)为01-AF-3B
01-AF-3B
01-AF-3B-xx
01-AF-3B-xx-xx
01-AF-3B-xx-xx-xx
"""
import random
import string
def creat. mac():
MAC = '01-AF-3B '
hex_ .num = string. hexdigits
for i in range(3):
n = random. sample(hex_ num, 2)
sn = '-'+'.join(n) .upper()
MAC += sn
return MAC
def. create_ file():
with open( 'mac.txt','w') as f
for i in range_ (100):
f. write(creat. _mac()+'\n')
create_ file()
38、查看本机信息
"""
需求:
1. 获取当前主机信息, 包含操作系统名, 主机名,
内核版本, 硬件架构等
2. 获取开机时间和开机时长;
3. 获取当前登陆用户
"""
import time
import os
from datetime import datetime
import psutil
print(' Computer info'.center(50, '*'))
info = os. uname()
print (
"""
System:%s
Hostname:%s
Kernoal :%s
Hard :%s
"""
%(info. sysname, info. nodename, info. release, info. machine)
)
print( 'Opening info' .center(50, '*'))
boot_ time = psutil.boot_.time() ##开启启动时间
boot_ .time_ obj = datetime.fromt imestamp (boot_ .time ) ##时间戳转化为字符串时间
now_ time = datetime. now() ##当前时间
time1 = now_time-boot_.time_obj
print(
"""
Opening time :%s
Now time :%s
Opening time to now:%s
"""
%(boot_ _time_obj , now_time, time1)
)
print( ' Now user' . center(50,'*'))
print(psutil. users() [0] . name)
39、通过第三方微信模块,获取登录微信者中的好友信息
###通过扫描登录,获取扫码微信中的好友男女个数
import itchat
itchat.auto _login()
friends = itchat. get_ friends()
info = {}
for friend in friends[1:]:
if friend['Sex'] == 1:
info['maLe'] = info.get('male',0) + 1
elif friend['Sex'] == 2:
info['female'] = info. get('female',0) + 1
else:
info['other'] = info. get('other',0) + 1
print_ (info)
40、通过类实现指定的需求
"""
需求
1.小明体重75.0公斤
2.小明每次跑步会减肥0.5公斤
3.小明每次吃东西体重会增加1公斤
需求
1.小明和小美都爱跑步
2.小美体重45.0公斤
3.小明体重75.0公斤
4.每次跑步都会减少0.5公斤
5.每次吃东西都会增加1公斤
"""
class People():
def __init__(self,name,weight):
self.name = name
self.weight = weight
def __str__(self):
return 'My name is %s, weight is %.2f' %(self.name,self.weight)
def run(self):
print('%s is running...' %self.name)
self.weight -= 0.5
def eat(self):
print('%s is eating...' %self.name)
self.weight += 1
xiaoming = People('xiaoming',75.0)
xiaoming.run()
print(xiaoming)
xiaomei = People('xiaomei',45.0)
xiaomei.eat()
print(xiaomei)
41、用类实现栈
class Stack(object):
def __init__(self):
self.stack = []
def __len__(self):
return len(self.stack)
def top(self):
if self.is_empty():
raise Exception('Stack is empty!')
else:
return self.stack[-1]
def push(self,element):
self.stack.append(element)
def pop(self):
if self.is_empty():
raise Exception('Stack is empty!')
else:
item = self.stack.pop()
return item
def length(self):
return len(self.stack)
def is_empty(self):
return len(self.stack) == 0
stack = Stack()
stack.push(1)
print(stack.length())
item = stack.pop()
print('The pop item is: %s' %item)
print(stack.length())
42 、按照需求编写类
"""
需求:
1.房子有户型,总面积和家具名称列表
新房子没有任何的家具
2.家具有名字和占地面积,其中
床:占4平米
衣柜:占2平米
餐桌:占1.5平米
3.将以上三件家具添加到房子中
4.打印房子时,要求输出:户型,总面积,剩余面积,家具名称列表
"""
class Furniture(object):
def __init__(self,name,area):
self.name = name
self.area = area
def __str__(self):
return '[%s] 占地 %.2f 平米' %(self.name,self.area)
# bed = Furniture('bed',4)
# print(bed)
class House(object):
def __init__(self,type,area):
self.type = type
self.area = area
self.free_area = area
self.fur_list = []
def __str__(self):
return ('户型: %s\n总面积: %.2f\n剩余面积: %.2f\n家具: %s'
%(self.type,self.area,self.free_area,self.fur_list))
def add_fur(self,item):
self.fur_list.append(item.name)
self.free_area -= item.area
bed = Furniture('bed',4)
table = Furniture('table',1.5)
home = House('villa',200)
home.add_fur(bed)
home.add_fur(yigui)
print(home)
持续更新.......