Python基础 实例

python基础的实例,看这一篇就够了

python 3.9.2 pycharm

字符串部分的学习代码:

# 编写人:刘钰琢
# 编写日期:2021/1/20 19:08
#字符串的驻留机制
a='python'
b="python"
c='''python'''
print(a,id(a))#python
print(b,id(b))#python
print(c,id(c))#python
a='abc%'
b="abc%"
print(a==	b)#true
#字符串的查询操作
s='hello,HEllo'
print(s.index('lo'))#3
print(s.find('lo'))#3
print(s.rindex('lo'))#9
print(s.rfind('lo'))#9
#print(s.index('k'))#会报错
#print(s.rindex('k'))#会报错
print(s.find('k'))#-1,如果没有find就会返回-1
print(s.rfind('k'))#-1
#字符串的大小写转换的方法
print(s.upper())#HELLO,HELLO,全部转化为大写
print(s.lower())#hello,hello 全部转化为小写
print(s.swapcase())#HELLO,hELLO  把字符串所有的字符大写转大写 大写转小写
print(s.capitalize())#Hello,hello对第一个字符大写转小写 ,其余全部转化为小写
print(s.title())#Hello,Hello 对每一个单词的第一个字符转化为大写其他转化为小写
#字符串的各种对齐
s='hello,python'
print(s.center(20,'*'))#****hello,python****居中对齐
print(s.ljust(20,'*'))#hello,python******** 左对齐
print(s.ljust(10,'*'))#hello,python 如果宽度小于字符串长度则,返回元字符
print(s.ljust(20))#hello,python 如果不要填空符则直接填入空格
print(s.rjust(20,'*'))#********hello,python 右对齐
print(s.rjust(10))#hello,python 如果宽度小于字符串长度则,返回元字符
print(s.zfill(20))#00000000hello,python 右对齐,会用0填充
print('-8910'.zfill(8))#-0008910
#字符串的劈分
#split 从左边开始劈分
s='hello world python'
lst=s.split()
print(lst)#['hello', 'world', 'python']
s1='hello|world|python'
print(s1.split(sep='|'))#['hello', 'world', 'python']
print(s1.split(sep='|',maxsplit=1))#['hello', 'world|python'] maxsplit可以限制划分几个部分
#rsplit从右边开始劈分
print(s1.rsplit(sep='|'))#['hello', 'world', 'python']
print(s1.rsplit(sep='|',maxsplit=1))#['hello|world', 'python']
#字符串判断的相关方法
s2='hello,python'
print('1',s.isidentifier())#False 判断字符串是否是合法字符串
print('2','hello'.isidentifier())#True
print('3','张三_'.isidentifier())#True
print('4','张三_123'.isidentifier())#True
print('5','\t'.isspace())#True 判断字符串是否全部都是有空字符组成
print('6','acasdc'.isalpha())#True 判断字符串是否全部都是有字母组成
print('7','张三'.isalpha())#True
print('8','123'.isdecimal())#True 判断字符串是否全部都是有十进制数字 罗马数字,汉子都不是
print('9','123四'.isnumeric())#True 判断字符串是否全部都是有数字组成 罗马数字还有汉字都是
print('10','abc1'.isalnum())#True 判断字符串是否全部都是有字母和s数字组成
print('11','张三123'.isalnum())#True
print('12','abc!'.isalnum())#False !不是字母也不是数字
#字符串的替换和合并
s3='hello,python'
print(s3.replace('python','java'))#hello,java
s4='hello,python,python,python'
print(s4.replace('python','java',2))#hello,java,java,python
lst=['hello','python','world']
print('|'.join(lst))#hello|python|world
print(''.join(lst))#hellopythonworld
print('*'.join('python'))#p*y*t*h*o*n
#字符串的比较操作
#可以使用比较运算符 > >= < <= == !=
print('apple'>'app')#True
print('apple'>'banana')#False
print(ord('a'),ord('b'))#97 98 ord函数可以输出ascall码
print(chr(97),chr(98))#chr 可以和获取ascll所对应的字母或者数字
print(ord('刘'))
print(chr(21016))
# is 是比较id是否相同
#字符串的切片操作
#字符串不具备增删改查操作 切片操作会产生新的对象
s='hello,python'
s1=s[:5]#由于没有指定起始位置,所以从索引为0开始
s2=s[6:]#由于没有指定结束位置,所以会结束到最后
s3='!'
news=s1+s3+s2
print(news)
print(s[1:5:1])#从一开始到结束限制的前一位结束,步长为一
print(s[::2])#可以没有开始也没有结束,但是又步长
print(s[::-1])#从后开始,步长为一
print(s[:-6:-1])
#格式化字符串
#(1) %
name='张三'
age=20
print('我叫%s,今年%d'%(name,age))
#(2) {}
print('我叫{0},今年{1}'.format(name,age))
#3(3) f-string
print(f'wojaio{name},jinnian{age}')
print("%10d"%age)
print('hhhhhhhhhh')
print("%10.3f"%3.1415926)#.3小数点后三位,总宽度为10
print('{0:.3}'.format(3.1415926))#.3表示一共有三个数字
print('{0:10.3f}'.format(3.1415926)) #10是宽度,.3f是小数点
#字符串的编码转换 编码要和解码的格式要相同
#编码
s='天涯共此时'
print(s.encode(encoding='GBK'))#在GBK编码格式中,一个中文占两个字节
print(s.encode(encoding='UTF-8'))#在UTF-8编码格式中,一个中文占三个字节
#解码
byte=s.encode(encoding='GBK')
print(byte.decode(encoding='GBK'))
byte=s.encode(encoding='UTF-8')
print(byte.decode(encoding='UTF-8'))
#结束与 2021/1/22 19:18

代码的运行结果:

python 1961584955248
python 1961584955248
python 1961584955248
True
3
3
9
9
-1
-1
HELLO,HELLO
hello,hello
HELLO,heLLO
Hello,hello
Hello,Hello
****hello,python****
hello,python********
hello,python
hello,python        
********hello,python
hello,python
00000000hello,python
-0008910
['hello', 'world', 'python']
['hello', 'world', 'python']
['hello', 'world|python']
['hello', 'world', 'python']
['hello|world', 'python']
1 False
2 True
3 True
4 True
5 True	
6 True
7 True
8 True
9 True
10 True
11 True
12 False
hello,java
hello,java,java,python
hello|python|world
hellopythonworld
p*y*t*h*o*n
True
False
97 98
a b
21016
刘
hello!python
ello
hlopto
nohtyp,olleh
nohty
我叫张三,今年20
我叫张三,今年20
wojaio张三,jinnian20
		20
hhhhhhhhhh
		3.142	
3.14
		3.142
b'\xcc\xec\xd1\xc4\xb9\xb2\xb4\xcb\xca\xb1'
b'\xe5\xa4\xa9\xe6\xb6\xaf\xe5\x85\xb1\xe6\xad\xa4\xe6\x97\xb6'
天涯共此时
天涯共此时

集合的学习

# 编写人:刘钰琢
# 编写日期:2021/1/20 12:05
#集合的创建(只是在字典中没有value值)
#第一种创建用{}
s={'python','hello',90}
s1={1,2,3,4,5,5,6,7,7}
print(s1)
print(s)
#第二种创建方式用内置函数set() 集合无序 集合内容不可以重复
s2=set(range(6))
print(s2)
print(set([3,4,56,53]))
print(set((3,4,5,6,456)))
print(set('python'))
print(set({2,3,4,4,5,6}))
print(set(),type(set()))
#集合的操作,增删改查操作
#in 和not in
print('------------------')
s={1,2,3,4,5,6}
print(3 in s)
print(7 not in s)
#增加操作add 一次添加一个元素和update一次至少添加一个元素
s.add(800)
print(s)
s4={200,300,400}
s.update(s4)
print(s)
s.update([30,40,5])
print(s)
#删除操作 remove discard pop clear
s.remove(200)#删除元素如果存在则可以进行删除,如果不存在则进行报错
print(s)
s.discard(500)#删除元素虽然不存在也不会进行报错
print(s)
s.pop()
s.pop()#随机删除与一个元素
# s.pop(400)#不能添加参数
print(s)
s.clear()
print(s)
#集合之间的关系
#两个集合是否相等
s={10,20,30,40}
s1={30,40,20,10}
print(s==s1)#True
print(s!=s1)#False
#一个集合是否是另一个集合的子集,用内置函数issubset判断 前面是小的,后面是大的
s1={10,20,30,40,50,60}
s2={30,40,20,10}
s3={10,20,30,90}
print(s2.issubset(s1))#True
print(s3.issuperset(s1))#False
#一个集合是不是另一个集合的超集,用内置函数issuperset判断 前面是大的,后面是小的
print(s1.issuperset(s2))#True
print(s1.issuperset(s3))#False
#两个集合是否有交集,用内置函数isdisjiont判断 False表示有交集,True表示没有交际
print(s2.isdisjoint(s3))#False
s4={100,200,300}
print(s2.isdisjoint(s3))#True
#集合的数学操作
#交集操作,用内置函数intersection与&是等价的 得到的就是交集 原原集合不变
s1={10,20,30,40}
s2={20,30,40,50}
print(s1.intersection(s2))
print(s1&s2)
#并集操作 用内置函数union与|是等价的,得到的就是交集  原原集合不变
print(s1.union(s2))
print(s1|s2)
#差集操作 前-(前交后) 原原集合不变
print(s1.difference(s2))
print(s2.difference(s1))
print(s1-s2)
#对称差集 前并后-前交后
print(s1.symmetric_difference(s2))
print(s1^s2)
#集合生成式
lst=[i*i for i in range(1,10)]
print(lst)
s6={i*i for i in range(1,10)}
print(s6)

主要是元组的学习:

    ```python
# 编写人:刘钰琢
# 编写日期:2021/1/16 11:00
#不可变序列,可变序列 可变:列表,字典  两次的输出id是一样的
lst=[10,20,30]
print(id(lst))
lst.append(300)
print(id(lst))
#不可变序列:字符串,元组  两次输出的id是不一样的
s='hello'
print(id(s))
s=s+'world'
print(id(s))
#元组的创建
t=('python','hello',90)#括号是可以省略不写的
t3='python','hello',90
t4=('python',)
print('第一种创建',t,type(t))
print('第二次创建,省略小括号',t3,type(t3))
print('第三次创建,单单一个元素时',t4,type(t4))
t1=tuple(('python','hello',90))#要有两重括号,
print('第四次创建,用内置函数:',t1,type(t1))
t2=(10,)#只有一个元素的时候要添加逗号
print('第五次创建,单单一个元素时',t2,type(t2))
#空列表,空字典,空元组的创建
#空列表
lst=[]
lst1=list()
#空字典
d={}
d1=dict()
#空元组
t6=()
t7=tuple()
print('空列表',lst,lst1)
print('空字典',d,d1)
print('空元组',t6,t7)
#元组的可变和不可变的部分
t=(10,[20,30],40)#10,和40属于不可变部分,但是在【20,30】是一个可变的列表
print(t,type(t))#所以说对[20,30]属于是可以进行增删改查操作的
print(t[0])
t[1].append(100)#增加还有extend
print('中间列表后面添加一个元素',t)
t[1].sort(reverse=True)#排序,还有删除pop()填入索引,remove()填入
print('对中间的列表进行逆序排序',t)

对于列表的复习

 # 编写日期:2021/1/13 20:31
    #主要是对列表的复习
    ##列表的创建
    lst1=['hello','world',98,'hello']
    lst=list(['hello','world',98,'hello'])
    ##列表的增加append
    lst1.append('hello')#直接在后面添加一个元素,不能够添加两个元素
    print(lst1)
    ##列表的增加extend
    lst1.extend(lst)#在末尾添加至少一个元素,也可以是一个列表,可以进行两个数列的合并
    print()
    print(lst1)
    ##列表的添加insert
    lst1.insert(1,30)#在指定的位置上添加一个元素
    print()
    print(lst1)
    ##添加多个元素(切片)
    lst[1:]=lst
    print('切片第一次')
    print(lst1)
    lst[1:3]=lst#1的起始位置也是保留的,结束位置也是保留的,只覆盖中间的元素
    print('切片第二次')#1是起始位置,2为结束位置,如果没有2则直接对后面进行删除不在保留,如果有2则保留2后面的包括二
    print(lst1)
    ##列表的删除操作
    lst1=['hello','world',98,'hello']
    lst=list(['hello','world',98,'hello'])
    print('删除操作')
    #remove
    lst1.remove('hello')
    print('删除第一次操作')
    print(lst1)#一次只删除一个元素,重复元素只删除第一个
    #pop,1为索引位置如果删除索引位置上有元素,则可以直接删除如果没有则会报错,如果不写入1则是直接删除最后一个元素
    lst1.pop(1)
    print('删除第二次操作')
    print(lst1)
    #切片,对起始位置和结束位置中间进行删除,不保留其实位置,保留结束位置
    lst[1:3]=[]
    print('删除第三次操作')
    print(lst)
    #修改操作
    lst=[10,20,30,40,50]
    #一次修改一个值
    lst[1]=100
    print('第一次修改')
    print(lst)
    lst[1:3]=[300,400,500,600]#和之前的一样对起始位置进行操作,但是不对结束位置进行操作
    print('第二次修改')
    print(lst)
    #clear 对列表进行清空处理但是还是存在列表输出时为空
    #del 删除列表处理,在输出列表会报错直接找不到列表
    #对列表进行排序操作
    #通常使用sort 和sorted进行排序
    #sort
    lst=[10,40,30,20,50]
    lst.sort(reverse=False)
    print('第一次排序')
    print(lst)
    lst.sort(reverse=True)
    print('第二次排序')
    print(lst)
    #sorted
    lst=[10,40,30,20,50]
    lst1=sorted(lst,reverse=True)
    print('第一次排序')
    print(lst)
    print(lst1)
    lst2=sorted(lst,reverse=False)
    print('第二次排序')
    print(lst)
    print(lst2)
    #我认为是查找操作,index函数可以查找出来所给的在列表中的索引位置
    lst=list(['hello','world',98,'hello'])
    print(lst.index('hello'))
    print(lst.index('world',1,))#对开始位置进行比对,对结束位置不进行操作
    #列表生成式
    lst=[i for i in range(1,10)]
    print(lst)
    #结束:2021.1.13 21.27
```

主要是对字典的学习:

 python
    # 编写人:刘钰琢
    # 编写日期:2021/1/1318:26
    # 字典的操作字典的操作
    score={'zhangsan':100,'lisi':98,'zhangmazi':56}
    print(score)
    print(type(score))
    #第二种创建方式
    std=dict(name='jack',age=20)
    print(std)
    #创建空字典
    d={}
    print(d)
    #字典中元素的获取
    print(score['zhangsan'])
    #print(score['hhah'])#在这个中如果没有就会直接报错
    print(score.get('zhangsan'))
    print(score.get('maliu'))#None这是获取没有
    print(score.get('dddd',99))#会输出默认值,即99
    #获取所有的key
    keys=score.keys()
    print(keys)
    print(type(keys))
    print(list(keys))
    #获取所有的value
    values=score.values()
    print(values)
    print(type(values))
    print(list(values))
    #获取所有的key——values对
    items=score.items()
    print(items)
    print(type(items))
    print(list(items))#转换之后的列表元素是由元组(())组成
    #字典元素的遍历
    for item in score:
        print(item,score.get(item),score[item])
    #字典
    #key不允许重复
    d={'name':'zhang','name':'lisi'}
    print(d)
    d1={'name':'zhang','dname':'zhang'}
    print(d1)
    #字典生成式
    items=['Fruits','books','Others']
    prices=[96,87,56]
    d2={item.upper():price for item,price in zip(items,prices)}#.upper是将他所有的变成大写
    print(d2)

主要是对类的学习:

   # 编写人:刘钰琢
   # 编写日期:2021/1/30 16:17
   class Car:
       def __init__(self,brand):
           self.brand=brand
       def start(self):
           print('汽车已启动')
   car1=Car('宝马X5')
   car1.start()
   print(car1.brand)
   class Student:
       def __init__(self,name,age):
           self.name=name
           self.__age=age#age不希望在类的外部去使用,所以加了两个_
       def show(self):
           print(self.name,self.__age)
   student1=Student('张三',20)
   student1.show()
   #在类的外部使用name, age
   print(student1.name)
   #print(student1.__age)__age不能单独使用
   print(dir(student1))
   print(student1._Student__age)#在类的外部可以通过_Student__age进行访问
   '''继承'''
   print('这是继承部分:')
   #继承的代码实现
   class Persion(object):
       def __init__(self,name,age):
           self.name=name
           self.age=age
       def info(self):
           print('姓名:{0},年龄:{1}'.format(self.name,self.age))
   class Stu(Persion):
       def __init__(self,name,age,score):
           super().__init__(name,age)
           self.score=score
   stu=Stu('王五',10,20)
   stu.info()
   class Tea(Persion):
       def __init__(self,name,age,teachofyear):
           super().__init__(name,age)
           self.teachofyear=teachofyear
   tea=Tea('张麻子',20,30)
   tea.info()
   #多继承
   class A(object):
       pass
   class B:
       pass
   class C(A,B):
       pass
   #方法重写
   print("方法重写")
   class Persion(object):
       def __init__(self,name,age):
           self.name=name
           self.age=age
       def info(self):
           print('姓名:{0},年龄:{1}'.format(self.name,self.age))
   class Stu(Persion):
       def __init__(self,name,age,score):
           super().__init__(name,age)
           self.score=score
       def info(self):#重写方法info
           super().info()#这样会先执行父类当中的info
           print("Stu重写方法后:",self.score)#在执行子类当中的info
   stu=Stu('王五',10,100)
   stu.info()
   class Tea(Persion):
       def __init__(self,name,age,teachofyear):
           super().__init__(name,age)
           self.teachofyear=teachofyear
       def info(self):
           super().info()
           print("Tea重写之后的","教龄:",self.teachofyear)
   tea=Tea('张麻子',20,30)
   tea.info()
   class Liu:
       def __init__(self,name,age):
           self.name=name
           self.age=age
       def __str__(self):
           return '我的名字是{0},今年{1}岁了'.format(self.name,self.age)
   liu1=Liu('张三',20)
   print(liu1)#默认会调用__str__()这样的方法
   class Animal:
       def eat(self):
           print('动物要吃东西')
   class Dog(Animal):
       def eat(self):
           print('狗吃肉')
   class Cat(Animal):
       def eat(self):
           print('猫吃鱼')
   class Persion:
       def eat(self):
           print('人吃五谷杂粮')
   def fun(obj):
       obj.eat()
   fun(Dog())
   fun(Cat())
   fun(Animal())
   fun(Persion())
   class A(object):
       pass
   class B:
       pass
   class C(A,B):
       def __init__(self,name,age):
           self.name=name
           self.age=age
   #创建C类的对象
   x=C('jack',20)
   print(x.__dict__)#实例对象的属性字典
   print(C.__dict__)
   print(x.__class__)#输出对象所属的类
   print(C.__bases__)#C类的父类类型的元素
   print(C.__base__)#C类的第一个父类的元素(基类)
   print(C.__mro__)#类的层次结构
   print(A.__subclasses__())#子类的列表
   a=20
   b=100
   c=a+b#两个整数类型的相加操作
   d=a.__add__(b)
   print(c)
   print(d)
   class Yu:
       def __init__(self,name):
           self.name=name
       def __add__(self, other):
           return self.name+other.name
       def __len__(self):
           return len(self.name)
   yu1=Yu('张三')
   yu2=Yu('李四')
   s=yu1+yu2#实现了两个对象的加法运算(因为在Yu类当中 编写了__add__(self,other)的特殊算法
   print(s)
   s=yu1.__add__(yu2)
   print(s)
   lst=[11,22,3,4]
   print(len(lst))
   print(lst.__len__())
   print('-----')
   print(yu1.__len__())
   #__new__()用于创建对象
   class Persion:
       def __init__(self,name,age):
           self.name=name
           self.age=age
       def __new__(cls, *args, **kwargs):
           print('__new__()被调用执行,cls的id值为{0}'.format(id(cls)))
           obj=super().__new__(cls)
           print('创建对象的id为{0}'.format(id(obj)))
           return obj
       def __init__(self,name,age):
           print('__init__被调用了self的id的值为{0}'.format(id(self)))
           self.name=name
           self.age=age
   print('object的这个类的对象id为:{0}'.format(id(object)))
   print('Persion这个对象的id为:{0}'.format(id(Persion)))
   p1=Persion('张三',20)
   print('p1这个Persion类的实例对象的id:{0}'.format(id(p1)))
   #print(p1)
   class Cpu:
       pass
   class Disk:
       pass
   class Computer:
       def __init__(self,cpu,disk):
           self.cpu=cpu
           self.disk=disk
   #(1)变量的赋值
   cpu1=Cpu()
   cpu2=cpu1
   print(id(cpu1))
   print(id(cpu2))
   #(2)类的浅拷贝,只是原对象和拷贝对象会引用同一个引用对象,但是两者的内存地址是不相同的
   print('-----------')
   disk=Disk()
   computer=Computer(cpu1,disk)
   import copy
   computer2=copy.copy(computer)
   print(computer,computer.cpu,computer.disk)
   print(computer2,computer2.cpu,computer2.disk)#cpu和disk类的内存地址是一样的,但是computer的内存地址是不一样的
   #(3)深拷贝
   print('-----------')
   computer3=copy.deepcopy(computer)
   print(computer,computer.cpu,computer.disk)
   print(computer3,computer3.cpu,computer3.disk)#所有的computer,cpu,disk的内存地址都是不同的

最后附上一个简单的车票管理系统的大作业

# 编写时间2021/6/9;16:01
# 编写  :刘钰琢
import MySQLdb


class chepiao():
    def __init__(self, ch_num, ch_start_ad, ch_end_ad, ch_start_time, ch_end_time, ch_length, ch_money, ch_speed):
        self.ch_num = ch_num
        self.ch_start_ad = ch_start_ad
        self.ch_end_ad = ch_end_ad
        self.ch_start_time = ch_start_time
        self.ch_end_time = ch_end_time
        self.ch_length = ch_length
        self.ch_money = ch_money
        self.ch_speed = ch_speed


class jilu():
    def __init__(self, buy_id, ch_start_ad, ch_end_ad, ch_length, p_name, ch_money, ch_num):
        self.buy_id = buy_id
        self.ch_start_ad = ch_start_ad
        self.ch_end_ad = ch_end_ad
        self.ch_length = ch_length
        self.p_name = p_name
        self.ch_money = ch_money
        self.ch_num = ch_num


def main():
    sql_begin()
    try:
        buy_id = get_buy_id()[-1] + 1
    except:
        buy_id = 1
    while (True):
        menu()
        answer_main = input("请问您要进行什么操作(1、购票,2、统计,3、打印,4、添加,其他、退出系统)")
        if answer_main == '1' or answer_main == '购票':
            buy(buy_id)
            buy_id += 1
        elif answer_main == '2' or answer_main == '统计':
            print_liuliang()
        elif answer_main == '3' or answer_main == '打印':
            print_piaoju()
        elif answer_main == '4' or answer_main == '添加':
            while (True):
                user_password=input("请输入管理员密码")
                if user_password=='lyz':
                    add()
                    break
                else:
                    continue
        else:
            answer_quit = input('您是否要退出?y/n?')
            if answer_quit == 'y' or answer_quit == 'Y':
                break
            else:
                continue


def menu():
    print('---------------------------------')
    print('--------欢迎使用车票订购系统--------')
    print('--------1、购票-------------------')
    print('--------2、统计进站和出站流量-------')
    print('--------3、打印票据信息------------')
    print('--------4、添加票据和车次-----------')


def buy(id):  # 购票
    global str
    p_name = input("请输入您的姓名")
    buy_id = id
    end_ad = input("请输入您要去的地方")
    buy_sql = "select * from chepiao where ch_end_ad='" + end_ad + "'";
    data = sql_chepiao(buy_sql, 'r')
    if data == ():
        print("还没有去这个地方的车辆,请联系管理员添加")
    else:
        i = 0
        print('这是车票的信息')
        for items in data:
            print('这是第{0}辆车的车次信息'.format(i + 1))
            for item in items:
                print(item, end='\t')
            print()
        while (True):
            answer_buy = int(input("请输入您要选择的车次信息"))
            if answer_buy > i + 1:
                print("您输入的车辆编号有误请重新输入")
                continue
            else:
                break
        chepiao_buy = data[answer_buy - 1]
        # ('001', '郑州', '北京', '08:00', '10:25', 725, '309', 'G')
        ch_money, ch_num, ch_start_ad, ch_end_ad, ch_length = chepiao_buy[6], chepiao_buy[0], chepiao_buy[1], \
                                                              chepiao_buy[
                                                                  2], chepiao_buy[5]
        lst = [buy_id, ch_start_ad, ch_end_ad, ch_length, p_name, ch_money, ch_num]
        # buy_id,ch_start_ad,ch_end_ad,ch_length,p_name,ch_money ,ch_num
        sql = "INSERT INTO jilu(buy_id,ch_start_ad,ch_end_ad,ch_length,p_name,ch_money ,ch_num)VALUES" + str(tuple(lst))
        # print(sql)
        sql_jilu(sql, 'w')


def print_liuliang():  # 输出流量
    print("您是哟啊统计数据吗?")
    end_ad = input("请输入您要统计的目的地")
    sql = "SELECT * FROM `jilu` where ch_end_ad='" + end_ad + "'"
    data = sql_chepiao(sql, 'r')
    if data == ():
        print("您输入的目的地并没有人去")
    else:
        i = 1
        for items in data:
            print("这是第{0}条数据:".format(i), end='  ')
            i += 1
            for item in items:
                print(item, end='\t')
            print('\n')
        print('去{0}的人数共有{1}人'.format(end_ad, i - 1))


def print_piaoju():  # 打印票据
    print("您是要打印的个人的凭据吗")
    username = input('请输入您的姓名')
    sql = "SELECT p_name,ch_money,buy_id,ch_num FROM `jilu` where p_name='" + username + "'"
    data = sql_jilu(sql, 'r')
    if data == ():
        print("您并没有买过票")
    else:
        i = 1
        for items in data:
            print("这是第{0}条数据:".format(i), end='  ')
            i += 1
            for item in items:
                print(item, end='\t')
            print('\n')


def sql_chepiao(sql, design):
    # 车票数据库信息
    '''
    create table chepiao(
    ch_num CHAR(10),
    ch_start_ad CHAR(10),
    ch_end_ad CHAR(10),
    ch_start_time char(10),
    ch_end_time char(10),
    ch_length int,
    ch_money char(15),
    ch_speed char(2)
    );
    '''
    db = MySQLdb.connect("localhost", "root", "root", "chepiaodinggou", charset='utf8')
    cursor = db.cursor()
    cursor.execute(sql)
    if design == 'r':
        all_data = cursor.fetchall()
        db.close()
        print('读取完成')
        return all_data
    elif design == 'w':
        db.commit()
        print("添加完成")
        db.close()
        return None


def sql_jilu(sql, design):
    '''
    create table jilu(
    buy_id int primary key,
    ch_start_ad char(10),
    ch_end_ad char(10),
    ch_length int,
    p_name char(20),
    ch_money char(15),
    ch_num char(10)
    )
    '''
    db = MySQLdb.connect("localhost", "root", "root", "chepiaodinggou", charset='utf8')
    cursor = db.cursor()
    cursor.execute(sql)
    if design == 'r':
        all_data = cursor.fetchall()
        db.close()
        print('读取完成')
        return all_data
    elif design == 'w':
        db.commit()
        db.close()
        print('添加完成')
        return None


def get_buy_id():
    sql = 'select buy_id from jilu '
    data = sql_jilu(sql, 'r')
    lst = []
    for item in data:
        lst.append(item[0])
    lst.sort()
    return lst


def add():
    global buy_id, ch_start_ad, ch_length, ch_end_ad, p_name, ch_num, ch_money
    while (True):
        answer_add = input("请问您想添加那个的呢1、票据记录,2、车票,其他、退出")
        if answer_add == '1' or answer_add == '票据记录':
            ji = add_jilu()
            lst1 = [ji.buy_id, ji.ch_start_ad, ji.ch_end_ad, ji.ch_length, ji.p_name, ji.ch_money, ji.ch_num]
            # buy_id,ch_start_ad,ch_end_ad,ch_length,p_name,ch_money ,ch_num
            sql = "INSERT INTO jilu(buy_id,ch_start_ad,ch_end_ad,ch_length,p_name,ch_money ,ch_num)VALUES" + str(
                tuple(lst1))
            sql_jilu(sql, 'w')
            # sql_jilu(sql,'w')
        elif answer_add == '2' or answer_add == '车票':
            ch = add_chepiao()
            lst2 = [ch.ch_num, ch.ch_start_ad, ch.ch_end_ad, ch.ch_start_time, ch.ch_end_time, ch.ch_length,
                    ch.ch_money, ch.ch_speed]
            sql = "INSERT INTO chepiao(ch_num,ch_start_ad,ch_end_ad,ch_start_time,ch_end_time,ch_length,ch_money,ch_speed)VALUES" + str(
                tuple(lst2))
            sql_chepiao(sql, 'w')
        # sql_chepiao(sql,'w')
        else:
            answer_add_quit = input("您确定要退出,不在添加了吗?y/n?")
            if answer_add_quit == 'y' or answer_add_quit == 'Y':
                break
            else:
                continue


def add_jilu():
    global buy_id, ch_start_ad, ch_length, ch_end_ad, p_name, ch_num, ch_money
    while (True):
        print('请输入你要添加的内容,请不要留有空格')
        buy_id = input("票据编号")
        if buy_id == '':
            continue
        buy_id = int(buy_id)
        ch_start_ad = input("开始地")
        if ch_start_ad == '':
            continue
        ch_end_ad = input("目的地")
        if ch_end_ad == '':
            continue
        ch_length = int(input("距离"))
        if ch_length == '':
            continue
        p_name = input("订票人")
        if p_name == '':
            continue
        ch_money = input("票价")
        if ch_money == '':
            continue
        ch_num = input("车次号")
        if ch_num == '':
            continue
        break
    ji = jilu(buy_id, ch_start_ad, ch_end_ad, ch_length, p_name, ch_money, ch_num)
    return ji


def add_chepiao():
    global num, start_ad, end_ad, start_time, end_time, length, money, speed
    while (True):
        print('请输入你要添加的内容,请不要留有空格')
        num = input("车辆编号")
        if num == '':
            continue
        start_ad = input("开始地")
        if start_ad == '':
            continue
        end_ad = input("目的地")
        if end_ad == '':
            continue
        start_time = input("发车时间")
        if start_time == '':
            continue
        end_time = input("到达时间")
        if end_time == '':
            continue
        length = input("距离")
        if length == '':
            continue
        length = int(length)
        money = input("票价")
        if money == '':
            continue
        speed = input("车辆类型")
        if speed == '':
            continue
        break
    ch = chepiao(num, start_ad, end_ad, start_time, end_time, length, money, speed)
    return ch


def sql_begin():
    sql = "select ch_num from chepiao"
    data = sql_chepiao(sql, 'r')
    # print(data)
    data_true = (('001',), ('002',), ('003',), ('004',), ('005',), ('006',))
    if data == data_true:
        print("数据库里边已经有数据了")
        return None
    else:
        end_ad_lst = []
        beijing = chepiao('001', '郑州', '北京', '08:00', '10:25', 725, '309', 'G')
        xian = chepiao('002', '郑州', '西安', '08:10', '10:20', 511, '221', 'G')
        shijiazhuang = chepiao('003', '郑州', '石家庄', '08:09', '10:10', 427, '189', 'G')
        jinan = chepiao('004', '郑州', '济南', '07:52', '12:11', 473, '303', 'G')
        taiyuan = chepiao('005', '郑州', '太原', '07:10', '10:31', 509, '180', 'D')
        wuhan = chepiao('006', '郑州', '武汉', '07:57', '09:55', 502, '244', 'G')
        end_ad_lst.append(beijing)
        end_ad_lst.append(xian)
        end_ad_lst.append(shijiazhuang)
        end_ad_lst.append(jinan)
        end_ad_lst.append(taiyuan)
        end_ad_lst.append(wuhan)
        for item in end_ad_lst:
            ch = item
            lst2 = [ch.ch_num, ch.ch_start_ad, ch.ch_end_ad, ch.ch_start_time, ch.ch_end_time, ch.ch_length,
                    ch.ch_money,
                    ch.ch_speed]
            sql = "INSERT INTO chepiao(ch_num,ch_start_ad,ch_end_ad,ch_start_time,ch_end_time,ch_length,ch_money,ch_speed)VALUES" + str(
                tuple(lst2))
            sql_chepiao(sql, 'w')
        print("车次数据已经填入到数据库中")


if __name__ == '__main__':
    main()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值