赞
踩
1、pytharm的安装及环境配置
import math a=1 b=4 c=3 p=(-b)/(2\a) q=math.sqrt(b\b-4\a\c)/(2\a) x1=q+p x2=q-p print('x1=',x1,'\\n','x2=',x2) str="君子之行,静以修身,俭以养德,非淡泊无以明志,非宁静无以致远 " print(str[:]) print(str[13]) print(str[-16:-1])
结果:
:
组合数据、函数和面向对象
代码:
a=input("input a:") b=input("input b:") c=input("input c:") if a>b and a>c : print(a) if c>b : print(c) print(b) else : print(b) print(c) elif b>c and b>a : print(b) if c>a : print(c) print(a) else : print(a) print(c) elif c>a and c>b : print(c) if a>b : print(a) print(b) else : print(b) print(a)
2
list = [3,8,11,26,47]
a=int(input("input:"))
i=1
for i in range(4):
if list[i-1]<a and list[i]>a:
list.insert(i,a)
print(a)
if a<=3:
list.insert(0,a)
elif a>=47:
list.append(a)
print(list)
-
3、
def func(str):
alpha,num,space,other=0,0,0,0
for i in str:
if i.isalpha():
alpha+=1
elif i.isdigit():
num+=1
else:
other+=1
print('字母数{},数字数{},其他字符数{}'.format(alpha,num,other))
func(input("请输入一个字符串:"))
import csv import os import pandas as pd start =[('商品','数量','单价'), ('土豆','200','3'), ('番茄','300','4') ] with open('超市管理.csv','w',newline='') as file: fw =csv.writer(file) fw.writerows(start) def showall(): with open('超市管理.csv','r') as file: fr = csv.DictReader(file) print('商品 数量 单价') for row in fr: print(row['商品'], row['数量'], row['单价']) return 0 def add(): with open('超市管理.csv', 'a+') as file: csv_write = csv.writer(file) a = input("请输入商品名:") b = input("请输入商品数量:") c = input("请输入商品单价:") row = [a,b,c] csv_write.writerow(row) return 0 def delgoods(): a=input("输入要删除的行数:") df = pd.read_csv('超市管理.csv') df.head(2) df.drop([a]) # def change(): # a = input("输入行数:") # with open("超市管理.csv") as csvfile: # *def sell(): a=input("输入卖出的商品行数:") f = open("超市管理.csv", "rb+") lines = f.readlines() last_line = lines[a] for i in range(len(last_line)): f.seek(a, os.SEEK_END) f.truncate() f.close() print("1:显示所有商品 ",end="") print("2:添加新的商品 ",end="") print("3:修改商品 ",end="") print("4:删除商品 ",end="") print("5:卖出商品 ",end="") print("6:汇总 ",end="") print("-1:退出 ") while 1: a=int(input("输入编号:")) if a == 1: showall() elif a == 2: add() *# elif a == 3: # change elif a == 4: delgoods() elif a == 5: sell() elif a == 6: history() elif a == -1 : exit() else: break
结果:
模块与正则表达式
代码:
import turtle
turtle.penup()
turtle.goto(-150,0)
turtle.pencolor("red")
turtle.begin_fill()
turtle.fillcolor("red")
for i in range(5):
turtle.forward(200)
turtle.right(144)
turtle.end_fill()
turtle.done()
-
2
import os
print(os.getcwd())
print(os.listdir())
3
import re
a = input('请输入电话号码:')
reg =
**"^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$"
pattern = re.compile(reg)
res = pattern.match(a)
if** res:
print("正确号码")
else:
print("错误号码!")
4
import urllib.request,re with urllib.request.urlopen('https://top.baidu.com/') as file: print("网页状态:",file.status,file.reason) data = file.read().decode('utf-8') reg = '<title>(.*?)</title>' title = re.findall(reg,data,re.S|re.M) print("title:",title) *#热搜 reg = '<div class="c-single-text-ellipsis">(.*?)</div>' content = re.findall(reg, data, re.S | re.M) i=0 print("热搜:\n") while i<20: print(content[i]) i=i+2 *#榜单名 reg = '<span class="title_jDbBV c-theme-color">(.*?)</span>' 榜单名 = re.findall(reg, data, re.S | re.M) print("榜单名:\n", 榜单名) *#游戏排行榜 reg = 'rsv_dl=fyb_hp_game" class="c-single-text-ellipsis name_3SMKh" target="_blank">(.*?)</a>' 游戏排行榜 = re.findall(reg, data, re.S | re.M) print("游戏排行榜:\n", 游戏排行榜) *#汽车排行榜 reg = 'rsv_dl=fyb_hp_car" class="c-single-text-ellipsis name_3SMKh" target="_blank">(.*?)</a>' 汽车 = re.findall(reg, data, re.S | re.M) print("汽车排行榜:\n", 汽车)
结果:
文件和异常处理
代码:
with open("a.txt","r") as file: str1 = file.readlines() print(str1) with open("b.txt","r") as file: str2 = file.readlines() print(str2) with open("c.txt","w") as file: file.writelines(str1) file.writelines("\n") file.writelines(str2) with open("c.txt","r") as file: str3 = file.readlines() print(str3) -
2
class List_Queue: def __init__(self): self.list1 = [] print('初始化成功!') def enqueue(self, item): self.list1.append(item) print('添加成功!') def dequeue(self): if len(self.list1) > 0: print("出队列数据:", self.list1(0)) self.list1.pop(0) else: raise List_Queue_Exception() def lenqueue(self): return len(self.list1) def l_queue(self): print(self.list1) class List_Queue_Exception(BaseException): def __init__(self): print("列表为空!") if _name_ == 'main': list_queue = List_Queue() print("1,入队") print("2,出队") print("3,队列长度") print("4,显示列表") print("0,退出*") while True: x = int(input("输入序号:")) try: if x in [0, 1, 2, 3, 4]: if x == 0: print("退出") break; elif x == 1: y = input("请输入输入的数据:") list_queue.enqueue(y) elif x == 2: list_queue.dequeue() elif x == 3: print("队列长度为:", list_queue.lenqueue()) elif x == 4: list_queue.l_queue() else: print("输入有误") except BaseException as ex: print(ex)
结果:
数据库和用户界面
代码:
import pymysql def menu(): print("学生成绩管理系统") print("1、添加一个学生的信息") print("2、删除一个学生的信息") print("3、修改一个学生的信息") print("4、查询一个学生的信息") print("5、退出") print("6、显示所有信息") def connection(): try: db = pymysql.connect(host="localhost", user="root", passwd="123456", db="studb", port=3306) print('数据库连接成功!') except pymysql.Error as e: print('数据库连接失败'+str(e)) db.close() def Insert(): db = pymysql.connect(host="localhost", user="root", passwd="123456", db="studb", port=3306) cur = db.cursor() sqlQuery = " INSERT INTO tg_grade (sno,sname,sex,age,birthday,math,english,os) VALUE (%s,%s,%s,%s,%s,%s,%s,%s) " a = input("请输入学生学号:") b = input("请输入学生姓名:") c = input("请输入学生性别:") d = input("请输入学生年龄:") e = input("请输入学生生日:") f = input("请输入学生数学成绩:") h = input("请输入学英语成绩:") i = input("请输入os:") value = (a, b, c,d,e,f,h,i) try: cur.execute(sqlQuery, value) db.commit() print('数据插入成功!') except pymysql.Error as e: print("数据插入失败:" + e) db.rollback() db.close() def deletedata(): db = pymysql.connect(host="localhost", user="root", passwd="123456", db="studb", port=3306) cur = db.cursor() sqlQuery = "DELETE FROM tg_grade where sName=%s" b=input("请输入要删除学生的姓名:") value = (b) try: cur.execute(sqlQuery, value) db.commit() print('Date Deleted Successfully') except pymysql.Error as e: print("数据删除失败:" + str(e)) db.rollback() def update(): db = pymysql.connect(host="localhost", user="root", passwd="123456", db="studb", port=3306) cur = db.cursor() num=input("输入数字:(1更改学号,2更改姓名,3更改性别,4更改年龄,5更改生日,6更改数学成绩,7更改英语成绩,8更改os)") if num =='1': sqlQuery = "UPDATE tg_grade SET sno= %s WHERE sname=%s" a = input("请输入要更新学生的姓名:") b = input("请输入更新后的学号:") if num =='2': sqlQuery = "UPDATE tg_grade SET sname= %s WHERE sname=%s" a = input("请输入要更新学生的姓名:") b = input("请输入更新后的姓名:") if num =='3': sqlQuery = "UPDATE tg_grade SET sex= %s WHERE sname=%s" a = input("请输入要更新学生的姓名:") b = input("请输入更新后的性别:") if num =='4': sqlQuery = "UPDATE tg_grade SET Age= %s WHERE sname=%s" a = input("请输入要更新学生的姓名:") b = input("请输入更新后的年龄:") if num =='5': sqlQuery = "UPDATE tg_grade SET birthday= %s WHERE sname=%s" a = input("请输入要更新学生的姓名:") b = input("请输入更新后的生日:") if num =='6': sqlQuery = "UPDATE tg_grade SET math= %s WHERE sname=%s" a = input("请输入要更新学生的姓名:") b = input("请输入更新后的数学成绩:") if num == '7': sqlQuery = "UPDATE tg_grade SET english= %s WHERE sname=%s" a = input("请输入要更新学生的姓名:") b = input("请输入更新后的英语成绩:") if num == '8': sqlQuery = "UPDATE tg_grade SET os= %s WHERE sname=%s" a = input("请输入要更新学生的姓名:") b = input("请输入更新后的os:") value = (a, b) try: cur.execute(sqlQuery, value) db.commit() print('数据更新成功!') except pymysql.Error as e: print("数据更新失败:" + str(e)) db.rollback() db.close() def Find(stunum): db = pymysql.connect(host="localhost", user="root", passwd="123456", db="studb", port=3306) cur = db.cursor() sqlQuery = "SELECT * FROM tg_grade WHERE sno=%s" value=(stunum) try: cur.execute(sqlQuery,value) results = cur.fetchall() for row in results: sno = row[0] sname = row[1] sex = row[2] age = row[3] birthday = row[4] math = row[5] english = row[6] os = row[7] print('sno:%s,sname:%s,sex:%s,age:%s,birthday:%s,math:%s,english:%s,os:%s' % (sno,sname,sex,age,birthday,math,english,os)) except pymysql.Error as e: print("学号不存在,或者数据查询失败:" + str(e)) db.close() def showall(): try: db = pymysql.connect(host="localhost", user="root", passwd="123456", db="studb", port=3306) cursor = db.cursor() r = cursor.execute('select * from tg_grade') data = cursor.fetchall() print(data) except pymysql.Error as e: print("显示失败:" + str(e)) db.close() def main(): connection() menu() while True: number=input("请输入数字:") if number'1': Insert() elif number'2': deletedata() elif number'3': update() elif number'4': stunum = input("输入学生学号:") Find(stunum) elif number'5': print("退出") break elif number'6': showall() main()
import wx,math def onclick(event): button = event.GetEventObject() label = button.GetLabel() nums = [str(i) for i in range(18)] + ['.', '+', '-', 'x', u'÷','cos','sin','sqrt','^']* if label in nums: xyz.AppendText(label) elif label == 'clear': xyz.SetValue('') def resul(event): x = xyz.GetValue() x = x.replace('x', '*').replace(u'÷', '/') if '.' not in x: x = x + '.0'* if x: xyz.SetValue(str(eval(x, {"builtins": None}, {}))) if _name_ == 'main': app = wx.App() win = wx.Frame(None, title='计算器', size=(400, 400)) bkg = wx.Panel(win) xyz = wx.TextCtrl(bkg) result_button = wx.Button(bkg, label='=') hbox = wx.BoxSizer() hbox.Add(xyz, proportion=4, flag=wx.EXPAND) hbox.Add(result_button, proportion=1, flag=wx.EXPAND, border=2) xbox = wx.GridSizer(4) buttons = ['7', '8', '9', u'÷', '4', '5', '6', 'x', '1', '2', '3', '-', 'clear', '.', '0', '+','^','sqrt','sin','cos'] for x in buttons: button = wx.Button(bkg, label=x) xbox.Add(button, proportion=2, flag=wx.EXPAND, border=5) button.Bind(wx.EVT_BUTTON, onclick) vbox = wx.BoxSizer(wx.VERTICAL) vbox.Add(hbox, proportion=1, flag=wx.EXPAND | wx.ALL, border=5) vbox.Add(xbox, proportion=3, flag=wx.EXPAND | wx.ALL, border=4) bkg.SetSizer(vbox) result_button.Bind(wx.EVT_BUTTON, resul) win.Show() app.MainLoop()
结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。