文章目錄
定義一個門票系統
門票的原價是100元
當週末的時候門票漲價20%
小孩子半票
計算2個成人和1個小孩的平日票價
class Ticket():
def __init__(self, weekend=False, child=False):
self.exp = 100
if weekend:
self.inc = 1.2
else:
self.inc = 1
if child:
self.discount = 0.5
else:
self.discount = 1
def cal_price(self, num):
return self.exp * self.inc * self.discount * num
adult = Ticket()
child = Ticket(child=True)
print("兩個成年人和一個小孩子平日的價格是{}".format(adult.cal_price(2)+ child.cal_price(1)))
遊戲編程:按一下要求定義一個烏龜類和魚類並嘗試編程
一、假設遊戲場景爲範圍(x,y)爲0<=x<=10,0<=y<=10
二、遊戲生成1只烏龜和10條魚
三、他們的移動方向均隨機
四、烏龜的最大移動能力是2(烏龜可以隨機選擇移動是1還是2),魚的最大移動能力是1
五、當移動到場景邊緣,自動向反方向移動
六、烏龜沒移動一次,體力消耗1
七、當烏龜和魚重疊,烏龜吃掉魚,烏龜體力增加20
八、魚不計算體力
九、當烏龜體力值爲0或者魚的數量爲0時,遊戲結束
import random as r
class Turtle(object):
def __init__(self):
self.power = 100
#初始化烏龜的位置
self.x = r.randint(0, 10)
self.y = r.randint(0, 10)
def move(self):
new_x = r.choice([1, 2, -1, -2]) + self.x
new_y = r.choice([1, 2, -1, -2]) + self.y
# 判斷 烏龜的移動是否超出了邊界
if new_x < 0:
self.x = 0 - (new_x - 0)
elif new_x > 10:
self.x = 10 - (new_x - 10)
else:
self.x = new_x
if new_y < 0:
self.y = 0 - (new_y - 0)
elif new_y > 10:
self.y = 10 - (new_y - 10)
else:
self.y = new_y
self.power -= 1
return (self.x, self.y)
def eat(self):
self.power += 20
if self.power >= 100:
self.power = 100
class Fish(object):
def __init__(self):
self.x = r.randint(0, 10)
self.y = r.randint(0, 10)
def move(self):
new_x = self.x + r.choice([1, -1])
new_y = self.y + r.choice([1, -1])
if new_x < 0:
self.x = 0 - (new_x - 0)
elif new_x > 10:
self.x = 10 - (new_x - 10)
else:
self.x = new_x
if new_y < 0:
self.y = 0 - (new_y - 0)
elif new_y > 10:
self.y = 10 - (new_y - 10)
else:
self.y = new_y
return (self.x, self.y)
turtle = Turtle()
fish = []
for i in range(10):
new_fish = Fish()
fish.append(new_fish)
while True:
if not len(fish):
print("魚被吃完了,遊戲結束")
break
if not turtle.power:
print("烏龜體力被耗盡了,遊戲結束了")
break
pos = turtle.move()
# 在迭代中做列表的刪除元素是非常危險的,經常會出現一些意想不到的問題,因爲迭代器是直接引用列表元素的數據做的操作
# 所以 我們這裏把列表拷貝一份傳給迭代器,然後再對原列表做操作
for each_fish in fish[:]:
if each_fish.move() == pos:
turtle.eat()
fish.remove(each_fish)
print("有一條魚被吃掉了")
定義一個點(point)和直線(Line)類,使用getLen方法獲取兩點構成直線的長度
import math
class Point(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def get_x(self):
return self.x
def get_y(self):
return self.y
class Line(object):
def __init__(self, p1, p2):
self.x = p1.get_x() - p2.get_x()
self.y = p1.get_y() - p2.get_y()
self.len = math.sqrt(self.x*self.x + self.y*self.y)
def get_len(self):
return self.len
p1 = Point(2,3)
p2 = Point(5,7)
line = Line(p1, p2)
line.get_len()
定義異常
# 定義減法,當第二個數小於第一個數是拋出異常
def jianfa(a,b):
if a<b:
raise BaseException('被減數不能小於減數')
else:
return a-b
try:
jianfa(3,7)
except BaseException as e:
print(e)
生成密碼
### 生成6位密碼,必須包含數字及大小寫字母
import string
import random
secrets = random.choice(string.ascii_lowercase)
secrets += random.choice(string.ascii_uppercase)
secrets += random.choice(string.digits)
while len(secrets)<6:
secrets += random.choice(string.ascii_letters+string.digits)
print(secrets)
登陸小程序
輸入用戶名時,如果用戶文件存在:
1、判斷是否過期;
2、判斷是否鎖定;
3、判斷密碼是否輸入正確,3次錯誤則鎖定
"""
import json
import os
import time
count = 0
while count < 3:
flag = 0
user = input('請輸入用戶名:')
file_path = user.strip() + '.json'
if os.path.exists(file_path):
f = open(file_path, 'r+')
file_content = json.load(f)
if file_content['status'] == 1:
flag = 1
# print('賬號已鎖定')
else:
t = time.strftime("%Y-%m-%d", time.gmtime())
if file_content['expire_date'] < t:
flag = 2
else:
while count < 3:
passwd = input('請輸入密碼:')
if file_content['password'] == passwd:
# print('恭喜登陸成功!')
flag = 3
break
else:
if count == 2:
flag = 4
# print('用戶登陸已超過3此,將鎖定賬號')
file_content['status'] = 1
f.seek(0)
f.truncate() # 清空文件
json.dump(file_content, f)
count += 1
if flag == 3:
print('恭喜登陸成功!')
break
elif flag == 1:
print('此賬號已鎖定')
elif flag == 2:
print('此賬號已過期')
elif flag == 4:
print('用戶密碼輸入錯誤3次,將鎖定賬號')
break
else:
print('用戶名不存在')
將首字母大寫,其他小寫
## 函數方法
def stadard(s):
f = s.lower().capitalize()
return f
l = ['asdQqweq', 'rtyy', 'AmingQ', 'eretWqwe']
res = list(map(stadard, l))
print(res)
## lambda方法
l = ['asdQqweq', 'rtyy', 'AmingQ', 'eretWqwe']
res = list(map(lambda x:x.lower().capitalize(), l))
print(res)
輸出1-1000之間從左往右與從右往左數一樣的數
output = filter(lambda x:x == int(str(x)[::-1]), range(1,1000))
print(list(output))
學生排序
# 學生排序---按照分數
L= [('zhangsan',55),('lisi',32),('wangwu','11'),('chenl',65)]
l = sorted(L,key=lambda x : int(x[1]), reverse=True)
print(l)
# 學生排序---按照姓名
L= [('zhangsan',55),('lisi',32),('wangwu','11'),('chenl',65)]
l = sorted(L,key=lambda x : x[0], reverse=False)
print(l)