
能力说明:
精通JVM运行机制,包括类生命、内存模型、垃圾回收及JVM常见参数;能够熟练使用Runnable接口创建线程和使用ExecutorService并发执行任务、识别潜在的死锁线程问题;能够使用Synchronized关键字和atomic包控制线程的执行顺序,使用并行Fork/Join框架;能过开发使用原始版本函数式接口的代码。
能力说明:
了解Python语言的基本特性、编程环境的搭建、语法基础、算法基础等,了解Python的基本数据结构,对Python的网络编程与Web开发技术具备初步的知识,了解常用开发框架的基本特性,以及Python爬虫的基础知识。
阿里云技能认证
详细说明
开始接触mavenweb项目,自己试着使用ECS配置了tomcat9实现了一下eclipse中的项目热部署,下面是心得体会:首先,创建好自己的mavenWeb项目。然后就是在服务器中配置Tomcat了。在link下载tar.gz版本,使用xftp将上传至服务器,我的是放在根目录下面了,解压缩tar -xzvf +文件名 tar -xzvf apache-tomcat-9.0.26.tar.gz 解压出目录名为apache-tomcat-9.0.26的文件目录后,使用移动命令将文件移动到/usr/local目录下并且重命名为tomcat mv apache-tomcat-9.0.26 /usr/local/tomcat 进入tomcat/bin 文件夹修改文件catalina.sh vi catalina.sh 添加内容CATALINA_HOME=/usr/local/tomcat启动Tomcat service tomcat start PS(如果失败了就查看一下权限的问题) 去客户端的浏览器中访问 ip地址:8080 就可以看到熟悉的Tomcat欢迎界面了(第一次进入的时间可能会有点慢,没关系,咱们让子弹飞一会...)看到界面之后点击Host-Manager 这时候会报错,因为还没有配置完呢接下来就进入到关键的步骤了,注意:1,打开Tomcat安装目录的conf目录,编辑tomcat-users.xml文件 vi tomcat-users.xml 添加下面的角色 <role rolename="manager-gui"/> <role rolename="manager-script"/> <role rolename="manager-jmx"/> <role rolename="manager-status"/> <role rolename="admin-gui"/> <role rolename="admin-script"/> <user username="你自己的用户名" password="你的密码" roles="manager-gui,manager-script,manager-jmx,manager-status,admin-gui,admin-script"/> 添加完成后重启Tomcat浏览器输入地址后点击Host Manager出现下面这个就ok了,成功了?不,才成功了一半 在eclipse中进行部署测试,tomcat7:deploy 并不能成功 接下来就要进行最关键的一步了,修改上传的权限tomcat安装目录下面有两个名为host-manager和manager的目录打开其中一个,编辑里面的META-INF目录中的context.xml文件 vim context.xml 这段话注释掉 <!--这里是使用的正则表达式控制可以上传项目的IP,默认设置的是只有本机才行--> <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" /> --> host-manager和manager中的解决办法一样完成后重启tomcat来到eclipse中热部署就可以开始了,这里说明一下,第一次的部署命令和后面的不同 第一次 tomcat7:deploy 非第一次 tomcat7:redeploy 看到这样的信息,终于成功了!!!
今天在阿里的ECS中的安装部署了Nginx1.6.2留一下经验心得:首先要下载这几个库和工具目录在/usr/local/src下面(可以改成自己想要目录): cd /usr/local/src wget http://nginx.org/download/nginx-1.10.2.tar.gz wget http://www.openssl.org/source/openssl-fips-2.0.10.tar.gz wget http://zlib.net/zlib-1.2.11.tar.gz wget https://netix.dl.sourceforge.net/project/pcre/pcre/8.40/pcre-8.40.tar.gz openssl用于加密解密,服务器提供安全网页(https://)时,会用到OpenSSL库;zlib提供在内存上的压缩和解压缩的函数,包括对数据完整性的检查;pcre库,nginx的rewrite模块和HTTP核心模块会用到pcre正则表达式语法 解压文件: tar -zxvf nginx-1.10.2.tar.gz tar -zxvf zlib-1.2.11.tar.gz tar -zxvf pcre-8.40.tar.gz tar -zxvf openssl-fips-2.0.10.tar.gz 分别进入 nginx、zlib、 pcre、openssl解压后的目录进行安装: ./configure && make && make install 完成后查看安装在哪里了 whereis nginx 我的是在这个文件夹下面执行下面命令开启服务 /usr/local/nginx/sbin/nginx 启动nginx: /usr/local/nginx/sbin/nginx重启nginx: /usr/local/nginx/sbin/nginx -s reload停止nginx: /usr/local/nginx/sbin/nginx -s stop查看nginx启动后信息:ps -ef|grep nginx查看nginx所占端口:netstat -ntlp我的80端口已经被占用了,就修改了一下 vim /usr/local/nginx/conf/nginx.conf 修改完了,访问一下地址,出现了404,猛地想起来,我去,安全组规则还没改,于是乎去控制台添加了安全组规则,从新打开一次这个地址,OK了,没毛病!
今天使用java的File类实现了一个简单的创建多层级多维度的文件目录结构结构如下同时使用递归方法实现了文件的遍历查询和全部删除。(核心思想)判断文件是不是目录,如果是目录就进行递归调用,否则直接进行处理。下面看一下代码吧! import java.io.File; import java.io.IOException; /** * * @author jjking * @version v1.0 * * 创建时间: 2019年8月28日 下午3:10:27 * */ public class ClassWork01 { static final int NUM = 10; /** * 创建文件夹 * @param path 要创建的路径 */ public static void createFilesAndDirs(String path) { File file = new File(path); file.mkdir(); for (int i = 0; i < NUM; i++) { File file0 = new File(path +"\\"+ i); File file1 = new File(path + "\\" + i + ".txt"); try { file1.createNewFile(); } catch (IOException e) { e.printStackTrace(); } file0.mkdir(); for (int j = 0; j < NUM; j++) { File f = new File(path + "\\" + i + "\\" + j); File f1 = new File(path +"\\" + i + "\\" + j + ".txt"); f.mkdir(); try { f1.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 递归查看文件和目录 * * @param path */ public static void showAllFilesAndDirs(String path) { File file = new File(path); File[] files = file.listFiles(); for (File file2 : files) { if (file2.isDirectory()) { System.out.println("目录》》》" + file2); showAllFilesAndDirs(file2.toString()); } else { System.out.println("文件》》》" + file2); } } } /** * 递归删除指定位置内部文件 * * @param path */ public static void deleteAllInnerFilesAndDirs(String path) { File file = new File(path); File[] listFiles = file.listFiles(); for (File f : listFiles) { if (f.isFile()) { f.delete(); } else { deleteAllFilesAndDirs(f.toString()); f.delete(); } } System.out.println("删除完成!"); } /** * 删除指定位置的所有文件 * * @param path */ public static void deleteAllFilesAndDirs(String path) { deleteAllInnerFilesAndDirs(path); File file = new File(path); file.delete(); } }
已知(只有一个已知条件): 1900年1月1号是星期一 实现的功能: 通过本条件来写一个输入相应的年份和月份就可以在控制台输出相应月份月历 基本的思路: 已知1900年的1月1日是周一,要输出这个月的月历首先最需要知道的就是本月1号是周几,这样我们才可以排列出来这个月的月历第一天的位置 本月1号距离1900年1月1号多少天设为days,这个天数对7取余数就可以求出本月1号是周几 0周一 | 1周二 | 2周三 |3 周四 | 4周五 | 5周六 | 6周日 天数 = (输入的年份 - 1900)* 365 (如果是闰年在加一天) 闰年的判断条件(可以被4整除但是不能被100整除的 或者 是可以被400整除的年份) 第二点就是要知道这个月有多少天 本月的天数就是从1月份到12月份判断(中间要注意平年和閏年的2月份不一样,加一个条件判断) 第三点就是每次要在周六的日期输出之后换到下一行(以周日为每周的第一天的情况) 判断日期为周几的方法和判断1号的方法是一样的,为了方便可以直接在本月1号的时间上加上今天的日期减一就可以知道今天的时间 距离1900年1月1号的时间差,对7取余就知道是周几了 下面是个人写的代码: public class WanNianLi { public static void main(String[] args) { Scanner input = new Scanner(System.in); // 欢迎界面 System.out.println("*************************"); System.out.println("******** 万年历 *********"); System.out.println("*************************"); System.out.print("请输入年份:"); // 年份 int year = input.nextInt(); System.out.print("请输入月份:"); // 月份 int month = input.nextInt(); boolean isRun = year % 4 == 0 && year % 100 != 0 || year % 400 == 0; /** * 当前月份的月1日距离1900 年的1月1日多少日 */ int dates = 0; for (int i = 1900; i < year; i++) { dates += 365; //判断是不是闰年,如果是闰年就在dates的基础上+1天 if ((i % 4 == 0 && i % 100 != 00) || (i % 400 == 0)) { dates += 1; } // System.out.println(i + "年:" + dates); } // System.out.println(dates); // 1、3、5、7、8、10月份加31天,3、6、9、11月加30天,平年2月加28,闰年2月加29天 for (int i = 1; i < month; i++) { switch (i) { case 1: case 3: case 5: case 7: case 8: case 10: dates += 31; break; case 4: case 6: case 9: case 11: dates += 30; break; case 2: if (isRun) { dates += 29; } else { dates += 28; } break; } } // System.out.println(dates); System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六"); /** * 1号需要空几个制表符 */ int week = dates % 7; switch (week) { case 0: System.out.print("\t");// 周一 break; case 1: System.out.print("\t\t");// 周二 break; case 2: System.out.print("\t\t\t");// 周三 break; case 3: System.out.print("\t\t\t\t");// 周四 break; case 4: System.out.print("\t\t\t\t\t");// 周五 break; case 5: System.out.print("\t\t\t\t\t\t");// 周六 break; default: break; } /** * 选择输出的这个月的天数 */ int days = 31; switch (month) { case 4: case 6: case 9: case 11: days = 30; break; case 2: if (isRun) { days = 29; } else { days = 28; } break; } /** * 循环输出本月的每一天,判断如果是周六就换行 */ for (int i = 1; i <= days; i++) { System.out.print(i + "\t"); if ((dates + i - 1) % 7 == 5) { System.out.println(); } } } } 结果演示:
今天使用数组和循环结构实现了一个简单的商品管理系统主要功能如下: 1.查询所有商品、2.添加、3.修改、4.删除、5.退出 查询: 编号 名称 价格 1 苹果 3.1 2 橘子 3.5 添加: 输入编号名称价格添加到数组中 修改: 根据编号修改名称、价格 删除: 根据编号删除商品 退出: 结束程序, 谢谢使用 import java.util.Scanner; public class ShoppingManageSystem { public static void main(String[] args) { Scanner input = new Scanner(System.in); int[] ids = {1,2,3}; String[] names = {"香蕉","苹果","橘子"}; double[] prices = {1.2,3.2,1.5}; //欢迎界面 System.out.println("*********************************"); System.out.println("*****欢迎使用JJ商品管理系统*******"); System.out.println("*********************************"); System.out.println("================================="); //功能选择 while (true) { System.out.println("**************************"); System.out.println("** 1、查询商品 *******"); System.out.println("** 2、添加商品 *******"); System.out.println("** 3、修改商品 *******"); System.out.println("** 4、删除商品 *******"); System.out.println("** 5、退出 *******"); System.out.println("**************************"); System.out.println("请选择功能:"); String choose = input.next(); if (choose.equals("1")) { //查询商品功能 System.out.println("编号\t名称\t价格"); System.out.println("-------------------------"); for (int i = 0; i < prices.length; i++) { if (ids[i]>=0) { System.out.print(ids[i] + "\t"); System.out.print(names[i] + "\t"); System.out.println(prices[i] + "\t"); } } System.out.println(); }else if (choose.equals("2")) { //添加商品功能 int addId; String addName; double addPrice; while (true) { //输入添加的商品信息 System.out.println("请输入要添加的商品编号"); addId = input.nextInt(); System.out.println("请输入要添加的商品名称"); addName = input.next(); System.out.println("请输入要添加的商品价格"); addPrice = input.nextDouble(); boolean flag = true; //判断编号是否重复,重复从新输入,不重复继续添加 for (int i = 0; i < ids.length; i++) { if (addId == ids[i]) { System.out.println("编号重复请重试"); flag = false; } } if(flag == false){ continue; } //新建数组 int[] newIds = new int[ids.length+1]; String[] newNames = new String[names.length+1]; double[] newPrices = new double[prices.length+1]; //将数据放入新的数组中 for (int i = 0; i < prices.length; i++) { newIds[i] = ids[i]; newNames[i] = names[i]; newPrices[i] = prices[i]; } newIds[newIds.length-1] = addId; newNames[newNames.length-1] = addName; newPrices[newPrices.length-1] = addPrice; //数组赋值 ids = newIds; names = newNames; prices = newPrices; System.out.println("Success!"); break; } }else if (choose.equals("3")) { //修改商品功能 int updateId; String updateName; double updatePrice; while (true) { //输入添加的商品信息 System.out.println("请输入要修改的商品编号"); updateId = input.nextInt(); System.out.println("请输入要修改的商品名称"); updateName = input.next(); System.out.println("请输入要修改的商品价格"); updatePrice = input.nextDouble(); boolean flag = true; //判断编号是否存在,不存在从新输入,存在修改 for (int i = 0; i < ids.length; i++) { if (updateId == ids[i]) { names[i] = updateName; prices[i] = updatePrice; flag = false; System.out.println("修改成功!"); }else{ } } if(flag == false){ break; } System.out.println("编号不存在,请重新输入!"); } }else if (choose.equals("4")) { //删除商品功能 while(true){ System.out.println("请输入要删除的商品编号:"); int delId = input.nextInt(); boolean flag = true; for (int i = 0; i < ids.length; i++) { if (delId == ids[i]) { ids[i] = -1; System.out.println("删除成功!"); flag = false; }else{ } } if (flag == false) { break; } System.out.println("没有该商品,请从新选择!"); } }else if (choose.equals("5")) { //退出 break; }else{ System.out.println("您输入的功能不存在,请重新输入:"); } } System.out.println("程序结束,谢谢使用。"); } }
分支语句主要包括以下几种结构: if、 if-else、 多重if、 嵌套if、 switch 下面详细解释一下各个语句的结构和使用示例。1、if // 单纯的if结构 /* * if(条件){ * 内容 * } */ int num = 3; if (num >= 0) { System.out.println("if结构"); } if(false == 2>=4){ System.out.println("1"); } 2、if-else // if-else结构 /* * if(条件){ * 内容 * }else{ * 内容 * } */ int rank = 2; if (rank==1) { System.out.println("啥奖励都有!"); }else { System.out.println("奖励你一巴掌!"); } 3、多重if // if-else if-else结构 /* * if(条件1){ * 内容1 * }else if(条件2){ * 内容2 * }else if(条件3){ * 内容3 * }else{ * 内容4 * } */ if(a==0) { System.out.println("a=0"); }else if(a==1) { System.out.println("a==1"); }else if(a==2){ System.out.println("a=2"); }else{ System.out.println("a>2"); } 4、嵌套if //嵌套if语句 /* * if(条件1){ * if(条件2){ * 内容 * } * } */ if (isFull==false) { if (a==2) { System.out.println("嵌套if"); } } 5、switch // switch 语句 /* * switch(变量){ * case 值1: * 内容1 * break; * case 值2: * 内容2 * break; * default: * 内容3 * break; * } */ switch (a) { case 0: System.out.println(0); break; case 1: System.out.println(1); break; case 2: System.out.println(2); break; default: System.out.println("啥都没有"); break; } 接下来是几个个人练习使用示例:练习1 题目描述: 如果你有500w以上可以在四环以内买房, 如果你有200w到500w之间可以在四环到五环买房, 如果你有100w到200w你可以在五环外买房, 如果有10000到100w之间可以租房住, 如果连1w都不到那你只能露宿街头了... 练习2每周一次的大扫除开始了, 老师对同学们做了如下安排: 一米七以上的男生挑水,一米七以上的女生擦玻璃,一米七以下的男生墩地,一米七以下的女生擦桌子请按照要求编写一个程序来分配班级人员的工作分组 练习1参考: public class Exercise06 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int money = in.nextInt(); if (money>=5000000) { System.out.println("四环以内买房!"); }else if (money >= 2000000) { System.out.println("四环到五环"); }else if (money >= 1000000) { System.out.println("五环外"); }else if (money >= 10000) { System.out.println("租房"); }else { System.out.println("露宿街头"); } } } 练习2参考: public class Exercise07 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("please input height:"); int height = in.nextInt(); System.out.println("please input sex:"); String sex = in.next(); if (height>=170) { if (sex.equals("男")) { System.out.println("一米七以上的男的去挑水吧"); }else{ System.out.println("一米七以上的女的去擦玻璃吧"); } }else { if (sex.equals("男")) { System.out.println("一米七以下的男的去墩地吧"); }else{ System.out.println("一米七以下的女的去擦桌子吧"); } } } } 欢迎大家指导交流!
编写程序:由键盘输入给出一个百分制成绩,要求输出成绩等级’A’、’B’、’C’和’D’,90分以上为’A’,75~89为’B’,60~74为’C’,60分以下为’D’。 最开始写的方法:没有注意到百分制的限定,缺少条件分析,思考不到位。 public class Test01 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int score = scanner.nextInt(); if (score>=90) { System.out.println("A"); }else if (score>=75 && score<=89) { System.out.println("B"); }else if (score>=60 && score<=74) { System.out.println("C"); }else if (score<60) { System.out.println("D"); } }} 改正后: public class Test01 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int score = scanner.nextInt(); if (score>=90&&score<=100) { System.out.println("A"); }else if (score>=75 && score<=89) { System.out.println("B"); }else if (score>=60 && score<=74) { System.out.println("C"); }else if (score<60&&score>=0) { System.out.println("D"); }else{ System.out.println("很显然,这成绩是假滴!"); } }}
今天在自己买的服务器上试验了一把ftp服务器的配置,下面讲一下经过和收获吧。 首先使用putty远程链接服务器(基本的操作感觉有点废话了,但我还是写上吧)……1.查询本机是否安装了ftp服务 rpm qa |grep vsftpd 或者使用服务状态查看 service vsftpd status 当然,检查结果是没有安装 2.在服务器上安装ftp服务 yum install vsftpd -y 3.安装完毕,查看一下状态是没有运行的,这时候启动ftp服务,再查看一下状态 service vsftpd status service vsftpd start service vsftpd status 4.关于ftp服务器的配置,有点多,下篇文章再详细描述吧5.使用本地电脑连接ftp服务器进行测试,打开控制台,然后直接输入 ftp xxx.xxx.xxx.xx 这里是你自己的公网ip可惜第一次失败了,然后我就重新试了两次,结果还是连接超时不知道怎么回时,想了半天……最后终于想起来了,要配置服务器实例的安全组,在安全组规则里面添加ftp服务的mo'ren'du默认端口号21这次再连接就成功了,Yeah!当然,这里使用的是匿名用户的方式登陆的。时间原因,先到这里吧……
1、首先去Apache官网下载Tomcat 2、Tomcat是一个绿色的软件,所以,直接解压到你想要存放的文件中就可以,我就直接放在c盘的根目录了 3、配置Tomcat环境 【我的电脑】-【属性】-【高级系统设置】-【环境变量】 在系统变量里面新建 变量名:CATALINA_HOME 变量值:C:\apache-tomcat-7.0.93 4、在Tomcat文件中找到bin目录里面的startup.bat文件,双击打开文件,启动Tomcat服务器 5、在控制台里面的最后面显示的Server startup in XXXX ms,就说明服务器启动成功 6、在浏览器中输入网址 http:/localhost:8080/ 转到网站,如果出现以下界面就说明服务器配置成功了!
首先去oracle的官网下载相应的系统的jdk 一定要将Accept Lisense Argeement选中,否则是不能下载的 选中之后就出现了这个画面,我的是win10 64位的,直接选用最后的 .zip格式的 下载之后的文件 直接解压到你想要的磁盘或者文件夹中就可以了,这里我直接解压到c盘的根目录 下面是配置环境变量的方法: 1、右键 【我的电脑】—>【属性】—>【高级系统设置】—>【环境变量】 2、【系统变量】下面的新建 变量名:JAVA_HOME 变量值:C:\jdk-11.0.2(就是jdk文件的根目录) 3、【系统变量】下面找到Path变量,进行编辑 然后添加%JAVA_HOME%\bin(jdk中的bin文件的目录) 4、【系统变量】下面新建 变量名:CLASS_PATH 变量值:%JAVA_HOME%\lib(jdk中的lib文件的目录) 5、全部确定。 6、win+R,调出运行cmd命令,在控制台中输入java后回车,出现以下信息 运行javac命令,会显示以下信息 那么,恭喜你!环境变量配置成功!
面向对象三大特点: 封装、继承、多态 封装: 在python中,封装就是将有相同属性和功能的事物归纳好之后放在同一个类(class)中 优点:简化代码、便于日后修改和维护 下面定义一个人类作为例子: 里面包含了对象的初始化(构造函数),变量的访问限制(共有变量和私有变量) class Person(object): def __init__(self, name, age, money, height): self.__name__ = name #特殊变量,可以直接访问 self.age = age #普通变量 self.__money = money #私有变量,不能直接访问 self._height = height #可以直接访问,但是请视为私有变量,尽量不要直接访问 def show(self): print("My name is %s, I am %d years old. I have %d $$."%(self.__name__, self.age, self.__money)) def setMoney(self, money): if money < 0: pass else: self.__money = money def getMoney(self): return self.money per = Person("Jjking", 23, 50, 60) per.show() per.money = 200 per.age = 24 per.show() per.__money = 200 print(per.__money) per.setMoney(200) per.show() print(per.getMoney()) #动态数据语言的体现,在执行过程中可以添加属性 per.a = 34 print(per.a) 执行结果: 继承: 子类继承父类的属性,父类有的功能和属性(私有除外),子类都可以用 下面是例子: 因为父类是Animal类,定义了eat的行为,子类是Cat类继承了Animal的eat的行为,所以在创建一个cat的对象的时候,这个对象就直接有了cat的行为,因此执行结果就是小白eat class Animal(object): def __init__(self, namne): self.name = namne def eat(self): print(self.name + "eat") class Cat(Animal): def __init__(self, name): Animal.__init__(self, name) cat = Cat("小白") cat.eat() #执行结果 小白eat 多态: 用一个例子来理解一下多态,就是有继承,有函数重写,父类引用指向子类对象 #人类 class Person(object): def __init__(self, name, gender): self.name = name self.gender = gender def whoAmI(self): return 'I am a Person, my name is %s' % self.name #学生类 class Student(Person): def __init__(self, name, gender, score): super(Student, self).__init__(name, gender) self.score = score def whoAmI(self): return 'I am a Student, my name is %s' % self.name #老师类 class Teacher(Person): def __init__(self, name, gender, course): super(Teacher, self).__init__(name, gender) self.course = course def whoAmI(self): return 'I am a Teacher, my name is %s' % self.name def who_am_i(x): print(x.whoAmI()) p = Person('Tim', 'Male') s = Student('Bob', 'Male', 88) t = Teacher('Alice', 'Female', 'English') who_am_i(p) who_am_i(s) who_am_i(t)
import datetime import time ''' datetime比time高级了不少,可以理解为date time基于time进行了封装, 提供了各种实用的函数,date time模块的接口更为直观,更容易调用 模块中的类: datetime 同时有时间和日期 timedelta 主要用于计算时间跨度 tzinfo 时区相关 time 只关注时间 date 只关注日期 ''' #获取当前时间 d1 = datetime.datetime.now() print(d1) # d2 = datetime.datetime(1995, 4, 28,10,23,34,123355) print(d2) # d3 = datetime.datetime.time(d1) print(d3) #将时间转换为字符串 #d4 = d1.strptime("%Y-%m-%d %X") #print(d4) #时间加减 d5 = d1 - d2 print(d5) #间隔的天数 print(d5.days) #间隔天数除外的秒数 print(d5.seconds) import calendar ''' 日历 ''' #使用 print(calendar.month(2019, 7)) #返回指定年的日历 print(calendar.calendar(2019)) #判断闰年,返回True print(calendar.isleap(2000)) #返回某个月的weekday的第一天和这个月的天数 print(calendar.monthrange(2018, 12)) #返回某个月以每一周为元素的列表 print(calendar.monthcalendar(2017, 12))
#UTC(世界协调时间):格林尼治天文时间,世界标准时间,在中国来说是UTC+8(东八区) #DST(夏令时):是一种节约能源而人为规定的时间制度,在夏季调快一个小时 ''' 时间的表示形式: 1、时间戳 以整形或浮点型表示时间的一个以秒为单位的时间间隔 时间间隔的基础值是从1970年1月1号0点开始算起的 2、元组 一种Python的数据结构表示,这个元组有9个整形内容 year month day hours minutes seconds weekday Julia day fiag(1 【夏令时】或 -1【】 或 0【正常】) 3、格式化字符串 %y 两位数的年份表示(00-99) %Y 四位数的年份表示(000-9999) %m 月份(01-12) %d 月内中的一天(0-31) %H 24小时制小时数(0-23) %I 12小时制小时数(01-12) %M 分钟数(00=59) %S 秒(00-59) %a 本地简化星期名称 %A 本地完整星期名称 %b 本地简化的月份名称 %B 本地完整的月份名称 %c 本地相应的日期表示和时间表示 %j 年内的一天(001-366) %p 本地A.M.或P.M.的等价符 %U 一年中的星期数(00-53)星期天为星期的开始 %w 星期(0-6),星期天为星期的开始 %W 一年中的星期数(00-53)星期一为星期的开始 %x 本地相应的日期表示 %X 本地相应的时间表示 %Z 当前时区的名称 ''' import time #以浮点数形式返回当前时间的时间戳,不需要参数(UTC) c = time.time() print(c) #将时间戳转为UTC时间元组 t = time.gmtime(c) print(t) #将时间戳转为本地时间元组 b = time.localtime(c) print("b =", b) #将本地时间元组转换为时间戳 m = time.mktime(b) print(m) #将时间元组转换成字符串 s = time.asctime(b) print(s) #将时间戳转为字符串 h = time.ctime(c) print(h) #将时间元组转换为指定格式的字符串,参数2 为时间元祖,如果没有参数2, 默认转换为当前时间 q = time.strftime("%Y-%m-%d %H:%M:%S",b) print(q) #将时间字符串转换为时间元组 i = time.strptime(q, "%Y-%m-%d %H:%M:%S") print(i) #延迟一个时间,整形或浮点型 #time.sleep(1) #返回当前程序的cpu时间 #Unix系统始终返回全部的运行时间 #Windows从第二次开始,都是以第一个调用此函数的开始时间戳作为基数 j = time.clock() print(j) time.sleep(2) j1 =time.clock() print("%d" % j1) time.sleep(2) j2 =time.clock() print("%d" % j2)
用递归方法遍历目录: 使用到os模块,所以要先引入os模块 处理文件: 核心是判断文件是否是目录文件,如果是目录文件就进行递归处理,直接将文件名打印出来 下面是文件代码: import os def getAllDir(path, sp = " "): fileList = os.listdir(path) #处理每一个文件 sp += " " for fileName in fileList: #判断是否是路径(用绝对路径) absFliePath = os.path.join(path, fileName) if os.path.isdir(absFliePath): print(sp + "目录:", fileName) #递归调用 getAllDir(absFliePath, sp) else: print(sp + "普通文件", fileName) return fileList getAllDir(r"C:\Users\Administrator\PycharmProjects\untitled\day011") 栈方法: import os def getAllDirDE(path): stack = [] stack.append(path) #处理栈,当栈为空的时候结束循环 while len(stack) != 0: dirPath = stack.pop() fileDir = os.listdir(dirPath) for fileName in fileDir: fileAbsPath = os.path.join(dirPath, fileName) if os.path.isdir(fileAbsPath): print("目录:"+ fileName) stack.append(fileAbsPath) else: print("普通文件:", fileName) getAllDirDE(r"C:\Users\Administrator\PycharmProjects\untitled\day011") 队列方法:import os import collections def getAllDir(path): queue = collections.deque() #进队 queue.append(path) while len(queue) != 0: dirPath = queue.popleft() fileList = os.listdir(dirPath) for fileName in fileList: fileAbsPath = os.path.join(dirPath, fileName) if os.path.isdir(fileAbsPath): print("目录:"+fileName) queue.append(fileAbsPath) else: print("文件:"+fileName) getAllDir(r"C:\Users\Administrator\PycharmProjects\untitled\day011")
#模拟栈结构 stack = [] #压栈(向栈里面存数据) stack.append("A") print(stack) stack.append("B") stack.append("C") print(stack) #出栈(在栈里面取数据) res1 = stack.pop() print(res1) print(stack) res2 = stack.pop() print(res2) print(stack) res3 = stack.pop() print(res3) print(stack) #模拟队列 import collections #创建队列 queue = collections.deque() print(queue) #进队 queue.append("A") print(queue) queue.append("B") print(queue) #出队 res1 = queue.popleft() print(res1) print(queue) res2 = queue.popleft() print(res2) print(queue)
''' 递归调用:一个函数,调用了自身,成为递归调用 递归函数:一个会调用自身的函数 凡是循环能干的事,递归都能干 ''' ''' 方式: 1、写出临界条件 2、找这一次和上一次的关系 3、假设当前函数已经能用,调用自身计算行一次的结果,再求出本次的结果 ''' #输入一个数,求 1+2+3+……+ n 的和 def sum1(n): sum = 0 for x in range(1, n + 1): sum += x return sum res = sum1(10) print("res =", res) #递归方法 def sum2(n): if n == 1: return 1 else: return n + sum2(n - 1) res1 = sum2(10) print(res1)
今天利用这个小功能做了个植物大战僵尸的外挂,哈哈哈 等以后学了GUI编程的时候做成图形化界面 #进程模块 import win32process #系统 import win32api import win32con import win32gui import ctypes #获取最高权限,\位运算 PROCESS_ALL_ACCESS = (0x000F000|0x00100000|0xFFF) #找窗体 win = win32gui.FindWindow("MainWindow","植物大战僵尸中文版") #根据窗体找到进程号 hid, pid = win32process.GetWindowThreadProcessId(win) #以最高权限打开进程 p = win32api.OpenProcess(PROCESS_ALL_ACCESS, False, pid) data = ctypes.c_long() #c语言中的长整形 #加载内核模块 md = ctypes.windll.LoadLibrary("C:\\Windows\\System32\\kernel32") #读取内存 md.ReadProcessMemory(int(p),0x12508678, ctypes.byref(data), 4, None) print("data =", data) #设置新值 newData = ctypes.c_long(1000) #修改 md.WriteProcessMemory(int(p), 0x12508678, ctypes.byref(newData), 4, None)
import win32com.client import time dehua = win32com.client.Dispatch("SAPI.SPVOICE") dehua.Speak("Hello") while 1: dehua.Speak("Hi") time.sleep(5)还有语音模块,后面慢慢补
这里需要安装和下载pywin32导入相应的库 同时需要下载spy++工具来获取窗口句柄和标题 打开qq执行代码就有效果了 控制窗体的显示和隐藏 ''' import time import win32con import win32gui ''' #找出窗体的编号 QQWin = win32gui.FindWindow("Tedkaafa","QQ") #窗口句柄和标题 #隐藏窗体 win32gui.ShowWindow(QQWin,win32con.SW_HIDE) #显示窗体 win32gui.ShowWindow(QQWin,win32con.SW_SHOW) ''' while True: QQWin = win32gui.FindWindow("TXGuiFoundation", "QQ") win32gui.ShowWindow(QQWin, win32con.SW_HIDE) time.sleep(2) win32gui.ShowWindow(QQWin, win32con.SW_SHOW) time.sleep(2) ''' 控制窗体的位置和大小 ''' import win32con import win32gui import time import random QQWin = win32gui.FindWindow("TXGuiFoundation", "QQ") #参数1:控制的窗体 #参数2:大致方位,HWND_TOPMOST上方 #参数3:位置x #参数4:位置y #参数5:长度 #参数6:宽度 while True: time.sleep(0.2) x = random.randrange(600) y = random.randrange(800) win32gui.SetWindowPos(QQWin, win32con.HWND_TOPMOST, x, y, 600, 600, win32con.SWP_SHOWWINDOW)
vimport pickle #数据持久性模块 Mylist = [1, 2, 3, 44, "aaa", True] path = r"C:\Users\Administrator\PycharmProjects\untitled\day011\文件读写\file2.txt" f = open(path, "wb") pickle.dump(Mylist, f) f.close() #读取 f1 = open(path, "rb") tempList = pickle.load(f1) print(tempList) f1.close()
import time path = r"C:\Users\Administrator\PycharmProjects\untitled\day011\文件读写\file1" f = open(path,"w") ''' #写文件 #1、 f.write("Hello !!!") f.write("and") #2、刷新缓冲区 #直接把内部缓冲区数据立刻写入文件,而不是被动等待自动刷新缓冲区写入 f.flush() while True: f.write("Hello!\n") f.flush() time.sleep(1) f.close() #写文件 with open(path,"a") as f2: f2.write("aaa$$%##%##%") ''' #编码 with open(path, "wb") as f3: str = "My name is jjking.你好" f3.write(str.encode("utf-8")) with open(path, "rb") as f4: data = f4.read() print(data) print(type(data)) newData = data.decode("utf-8") print(newData) print(type(newData))
''' 过程: 1、打开文件 2、读文件内容 3、关闭文件 ''' ''' 1、打开文件 open(path, flag[, encoding]) path:要打开文件的路径 flag:打开方式 r(read) 以只读方式打开文件,文件的描述符放在文件的开头 rb 以为进制格式打开文件用于只读,文件的描述符放在文件的开头 r+ 打开一个文件用于读写,文件的描述符放在文件的开头 w 打开一个文件只用于写入,如果该文件已经存在会覆盖,不存在则创建新文件 wb 打开一个文件只用于写入二进制,如果该文件已经存在会覆盖,不存在则创建新文件 w+ 打开一个文件用于读写,如果该文件已经存在会覆盖,不存在则创建新文件 a 打开一个文件用于追加,如果文集那存在,文件描述符将会放到文件末尾 a+ encoding:编码格式 errors:错误处理 ''' #打开文件 path = r"E:\File.txt" #f = open(path, "r", encoding = "utf-8",errors = "ignore") f = open(path, "r") ''' 2、读文件内容 ''' #读文件的所有内容 str1 = f.read() print("str1 =", str1) #读文件中指定字符数 f.seek(0) #修改描述符的位置 str2 = f.read(5) print("str2 =", str2) #读取整行,包括"\n"字符 f.seek(0) str3 = f.readline() print("str3 =", str3) #读取所有行并返回列表 f.seek(0) str4 = f.readlines() print("str4 =", str4) #读取指定字符数 f.seek(0) str5 = f.readline(20) print("str5 =", str5) #修改描述符的位置 f.seek(0) ''' 3、关闭文件 ''' f.close() ''' 完整过程 ''' #第一种 try: f1 = open(path,"r") print(f1.read()) finally: if f1: f1.close() #更为简单的方法 with open(path, "r", encoding= "gbk", errors="ignore") as f2: print(f2.read())
import os ''' OS:包含了普遍的操作系统的功能 ''' #获取操作系统类型 nt->Windows posix->Linux/Unix或Mac OS X print(os.name) #打印操作系统详细信息,注意:windows 不支持 #print(os.uname()) #获取操作系统的环境变量 print(os.environ) #获取指定环境变量 print(os.environ.get("ALLUSERSPROFILE")) #获取当前目录 print(os.curdir) #获取当前工作目录,即当前脚本所在的目录 print(os.getcwd()) #返回指定目录下的所有文件(列表形式) print(os.listdir(r"C:\Users\Administrator\PycharmProjects\untitled\day006")) #在当前目录下创建新目录 #os.mkdir("My name") #删除目录 #os.rmdir("My name") #获取文件属性 print(os.stat("断言.py")) #重命名 #os.rename("My name","sd") #删除普通文件 #os.remove("sd") #运行shell命令 #os.system("notepad") #os.system("write") #os.system("shutdown -s -t 500") #自动关机 #os.system("taskkill /f /im notepad.exe") #关闭notepad进程 ''' os.path ''' #查看当前的绝对路径 print(os.path.abspath("./sd")) #拼接路径 p1 = r"C:\Users\Administrator\PycharmProjects\untitled\day011" p2 = "jjking"#注意:开始不能有斜杠 print(os.path.join(p1,p2)) #拆分路径 path2 = r"C:\Users\Administrator\PycharmProjects\untitled\day011\sd" print(os.path.split(path2)) #获取扩展名 print(os.path.splitext(path2)) #是否是目录 print(os.path.isdir(path2)) #判断文件是否存在 path3 = r"C:\Users\Administrator\PycharmProjects\untitled\day011\断言.py" print(os.path.isfile(path3)) #判断文件是否存在 print(os.path.exists(path3)) #获得文件字节 print(os.path.getsize(path3)) #获得文件路径 print(os.path.dirname(path3)) #获得文件名 print(os.path.basename(path3))
try: print(enume) print(3 / 0) except ZeroDivisionError as e: print("除数为零!") except NameError as e: print("名称错了!") #使用except而不使用任何错误类型 try: print(" ",de) except: print("Error!") #使用except显示多种异常 try: pass except(NameError,ZeroDivisionError): print("出现了NameError或ZeroDivisionError" ''' 特殊 #1、错误其实是class(类),所有的错误都继承自BaseException,所以在捕获 #2、跨越多层调用 #需求:当程序遇到问题时不让程序结束,而越过错误继续向下执行 ''' ''' try……except……else 格式: try: 语句t except 错误码 as e: 语句1 except 错误码 as e: 语句2 except 错误码 as e: 语句3 ... except 错误码 as e: 语句n else: 语句e 注意:else可有可无 作用:检测try语句块中的错误,从而让except语句捕获错误信息并处理 逻辑:当程序执行到try-except-else语句时 1、当try【语句t】执行出现错误,会匹配第一个错误码,如果匹配上就执行第一个语句 2、当try【语句t】执行出现错误,没有匹配到任何的错误码,错误将会被提交到上一层的 try语句,或者到程序的最上层 3、当try【语句t】执行没有出现错误,执行else下的【语句e】(有else的情况下) ''' def func1(num): print(1 / num) def func2(num): func1(num) def main(): func2(0) try: main() except ZeroDivisionError as e: print("QQQQQ") ''' try……except……else 格式: try: 语句t except 错误码 as e: 语句1 except 错误码 as e: 语句2 except 错误码 as e: 语句3 ... except 错误码 as e: 语句n finally: 语句f 注意:else可有可无 作用:语句t无论是否有错误都将执行最后的语句f ''' try: print(1/1) finally: print("这是必须执行的语句!") print("sda") try: print(1/0) finally: print("这是必须执行的语句!") print("sda")
def func(num,div): assert (div != 0),"div不能为0" return num / div res = func(3, 2) print(res) res1 = func(2, 0) print(res1)
作用域:变量可以使用的范围 程序的变量并不是所有位置都能使用的,访问的权限决定于变量在哪里赋值的 作用域:局部作用域全局作用域内建作用域
''' 概念:是一个闭包,把一个函数当作参数返回一个替代版的函数 本质上是一个返回函数的函数 ''' #简单的装饰器 def func1(): print("My name is jjking.") def func2(): print("******************") func1() func2() def func3(func): def inner(): print("******************") func() return inner #f是func1的加强版本 f = func3(func1) f() def outer(func): def inner(age): if age < 0: age = 0 func(age) return inner #使用@符号将装饰器应用到函数 #python2.4支持使用@符号 @outer def say(age): print("My age is %d"% (age)) #say = outer(say) say(-12) def outer(func): def inner(*args, **kwargs): #添加修改的功能 print("&&&&&&&&") func(*args, **kwargs) return inner @outer def say(name, age): print("My name is %s, I am %d years old."%(name, age)) say("jjking", 23)
''' 认识函数:在以恶完整的项目中,某些功能会反复的使用,那么 会将功能封装成函数,当我们要使用这些功能的时候 直接调用函数即可 本质:函数就是对功能的封装 优点: 1、简化代码结构,增加了代码的复用度(重复使用的程度) 2、如果想修改某些功能或修改某个bug只需要修改相应的函数即可 ''' ''' 定义函数: 格式: def 函数名(参数列表): 语句 return 表达式 def:函数代码块从def关键字开始 函数名:遵循标识符规则 参数列表(参数1, 参数2,……参数n):任何传入函数的参数和变量 必须放在圆括号之间 语句:执行的功能 return:以return为结束 ''' ''' 函数的调用 格式:函数名(参数列表) 函数名:是要使用的功能的函数 '''
from collections import Iterable, Iterator ''' 可迭代对象:可以直接作用于for循环的对象统称为可迭代对象 (Iterable) 可以用isinstance()去判断一个对象是否是Iterable对象 可以直接作用于for的数据类型一般分两种 1、集合类数据类型:list、 tuple、 dict、 set、 string 2、是generator,包括生成器和带yield的generator function ''' print(isinstance([],Iterable)) print(isinstance((),Iterable)) print(isinstance({},Iterable)) print(isinstance("",Iterable)) print(isinstance((x for x in range(10)),Iterable)) print(isinstance(1,Iterable)) ''' 迭代器:不但可以作用于for循环,还可以被next()函数不断的调用并返回下一个值 直到最后抛出一个StopIteration错误表示无法继续返回下一个值 可以被next()函数调用并不断返回下一个之的对象称为迭代器 (Iterator对象) 可以用isinstance()函数判断一个对象是否是可迭代对象 ''' print(isinstance([],Iterator)) print(isinstance((),Iterator)) print(isinstance({},Iterator)) print(isinstance("",Iterator)) print(isinstance((x for x in range(10)),Iterator)) l = (x for x in range(4)) print(l) print(next(l)) print(next(l)) print(next(l)) print(next(l)) lq = (x for x in [1, 2, 3, 5]) print(next(lq)) print(next(lq)) print(next(lq)) print(next(lq)) #同理tuple、dict、set、string都可以 #转换成Iterator对象 a = iter([2, 4, 6]) print(next(a)) print(next(a)) print(next(a)) print(isinstance((a), Iterator)) endstr = "end" str = "" for line in iter(input, endstr): str += line + "\n" print(str)
''' set:类似dict,是一组key的集合,不存储value 本质:无序和无重复元素的集合 用途:经常用于去除list和tuple中的重复元素 ''' #创建 #创建set 需要一个list或者tuple或者dict作为输入集合 #重复元素在set中会自动被过滤 set1 = set([1, 2, 2, 2, 3, 4, 5]) print(set1) set2 = set((1, 2, 3, 1, 2, 3)) print(set2) set3 = set({1:"2" , 3: "4", 5: "2"}) print(set3) #添加 注意;列表不能作为key,而set里面存的就是key,所以不能添加list[] set1.add(5) print(set1) set2.add((1,2,1,5)) print(set2) #set3.add({1,2}) #会报错 #插入整个list tuple 字符串,打碎插入 set1.update([12,3]) print(set1) set1.update((22,23,24,24)) print(set1) set1.update("name") print(set1) #删除 set1.remove("n") print(set1) set1.remove(2) print(set1) #遍历 for i in set1: print(i) #注意:set没有索引 for index, data in enumerate(set1): print(index,data) s1 = set([1, 2, 3]) s2 = set([2, 3, 4]) #交集 a1 = s1 & s2 print(a1) print(type(a1)) #并集 a2 = s1 | s2 print(a2) print(type(a2)) #list -> set l1 = [1, 2, 3, 4] set3 = set(l1) #tuple -> set t1 = (1, 2, 3) s4 =set(t1) print(s4) #去重 list5 =[1, 1, 2, 3, 4, 3, 4] print(list5) list6 = list(set(list5)) print(list6)
import time musucLrc = ''' [00:00.01]给我你的爱 [00:02.01]林宥嘉,张杰 [00:05.53] 作词:秋风 [00:09.83] 作曲:秋风 [00:14.90] [00:15.65]相信我 在每个生命的路口 [00:20.98]在每个无助的时候 [00:24.75]都有对爱的渴求 [00:30.47]我想把 真的爱向你传达 [00:36.53]无论你在海角天涯 [00:39.52]都能感到 我的牵挂 [00:44.28]请给我你的爱 [00:47.84]请伸出手来传递这信赖 [00:51.54]就在这茫茫人海 [00:53.79]真心的爱 让世界变色彩 [00:59.02]请给我你的爱 [01:02.45]让我们用爱改变着未来 [01:06.10]在每个艰难时刻 [01:08.88]伸你的手 感觉真的爱 [01:14.81]牵着手 让我们静静地感受 [01:19.92]当风雨艰难过去后 [01:23.79]那种美好的自由 [01:29.29]我们都曾 错过幸福的意义 [01:34.77]只希望我还来得及 [01:38.45]去告诉你 真心爱你 [01:43.15]请给我你的爱 [01:47.39]请伸出手来传递这信赖 [01:50.42]就在这茫茫人海 [01:53.18]真心的爱 让世界变色彩 [01:57.72]请给我你的爱 [02:01.53]让我们用爱改变着未来 [02:05.19]在每个艰难时刻 [02:07.86]伸你的手 感觉真的爱 [02:14.27]我不再想要错过 [02:15.81]你的每个热切期待 [02:19.18]用爱 在明天到来之前 [02:22.56]向你大声说出爱~~爱 [02:29.44]请给我你的爱 [02:32.65]请伸出手来传递这信赖 [02:36.33]就在这茫茫人海 [02:39.08]真心的爱 让世界变色彩 [02:43.89]请给我你的爱 [02:47.56]让我们用爱改变着未来 [02:51.05]在每个艰难时刻 [02:53.96]伸你的手 感觉真的爱 [03:01.38]给我你的爱~~ ''' #将数据分解存储到字典里 lrcDict = {} musicList = musucLrc.splitlines() for lrcLine in musicList: #runCount = lrcLine.count(":") lrcLineList = lrcLine.split("]") for index in range(len(lrcLineList) - 1): timeStr = lrcLineList[index][1:] #print(timeStr) timeList = timeStr.split(":") timea = float(timeList[0]) * 60 + float(timeList[1]) #print(timea) lrcDict[timea] = lrcLineList[-1] #print(lrcDict) allTimeList = [] for t in lrcDict: allTimeList.append(t) allTimeList.sort() #print(allTimeList) #在字典里将数据调出来然后按照时间间隔将数据显示出来 #效果是一行一行的刷新 getTime = 0 while 1: for n in range(len(allTimeList)): tempTime = allTimeList[n] if getTime < tempTime: break lrc = lrcDict.get(allTimeList[n]) if lrc == None: pass else: print(lrc) if n in range(len(allTimeList) - 1): time.sleep(allTimeList[n + 1] - allTimeList[n]) getTime += (allTimeList[n + 1] - allTimeList[n]) else: break
''' 概述: 使用键-值(key-value)存储,具有极快的查找速度 key的特性: 1、字典中的key必须唯一,一个字典可以存储多个键值对 2、key必须是不可变的对象 3、字符串、整数等都是不可变的,可以作为key 4、list是可变的,不能作为key ''' ''' 保存多位学生成绩 使用字典,学号为key,学生成绩作为值 ''' dict1 = {"1101":60, "1102":80} print(dict1) #元素的访问 #获取: 字典名[key] print(dict1["1102"]) print(dict1.get("1103")) ret = dict1.get("1103") if ret ==None: print("不存在!") else: print("存在!") #添加 dict1["1103"] = 90 #因为一个key对应一个value,所以,多次对一个key的value赋值,其实就是修改值 dict1["1101"] = 70 print(dict1) #删除 dict1.pop("1102") print(dict1) #遍历 for key in dict1: print(key) print(dict1.values()) for value in dict1.values(): print(value) print(dict1.items()) for k, v in dict1.items(): print(k, v) print(enumerate(dict1)) for i, c in enumerate(dict1): #枚举法 print(i,c) ''' #和list比较 1、查找和插入的速度极快,不会随着key-value的增加而变慢 2、需要占大量的内存,内存浪费多 ''' ''' list: 缺点: 查找和插入的速度随着数据量的增多而减慢 优点: 内存占用小,节省内存 '''
#创建空元组 tuple1 = () print(tuple1) #创建带有元素的元组 tuple2 = (1, 2, 3, "jjking", True) #元素类型可以不同 print(tuple2) #定义只有1 个元素的元组 tuple3 = (1 ) #后面必须加逗号 print(tuple3) print(type(tuple3)) ''' 元组元素的访问 格式: 元组名[下标] 注意:下标不能越界 ''' tuple4 = (1, 2, 3, 4, 5) print(tuple4[3]) #获取最后一个元素 print(tuple4[-1]) #获取倒数第二个元素 print(tuple4[-2]) #修改元组,实际上修改的是元素里面的数据 tuple5 = (1, 2, 3, 4, [1, 2, 3], 5) print(tuple5) tuple5[4][2] = 4 print(tuple5) #删除元组 del tuple5 #print(tuple5) 因为被删除了所以打印不出来,会报错 #元组的操作 t1 = (1 ,2, 3, 4) t2 = (5, 6) t3 = t1 + t2 print(t3) #元组重复 print(t3 *3) #判断元素是否在元组中 print( 3 in t3) #元组的截取 #格式:元组名[ 开始下标:结束下标 ] #从开始下标开始截取,到结束下标之前,默认从头到尾 print(t3[1:4]) #二维元组:元素为一维元组的元组 t4 = ((1, 2, 3), (4, 5, 6), (7, 8, 9)) print(t4) print(t4[2][1]) '''元组的方法''' #len() 返回元组中元素的个数 print(len(t4)) #max() 返回元组中的最大值 print(max(t1)) #min() 返回元祖中的最小值 print(min(t1)) #列表转元组 list2 = [1, 2, 3, 4, 5] t5 = tuple(list2) print(t5) #元组转列表 list1 = list(t3) print(list1) ''' 一旦初始化元组里面的元素就不能修改了 和列表的区别就是不可变 这就提高了数据的安全性 所以说能用元组尽量用元组 ''' #元组的遍历 for i in (1, 2, 3, 4,5): print(i)
学了for循环语句之后,就会变得相当简单了#99乘法表 for a in range(10): for b in range(10): if a!=0 and b!=0: print(a,"*", b,"=", a * b) 执行结果: 1 * 1 = 1 1 * 2 = 2 1 * 3 = 3 1 * 4 = 4 1 * 5 = 5 1 * 6 = 6 1 * 7 = 7 1 * 8 = 8 1 * 9 = 9 2 * 1 = 2 2 * 2 = 4 2 * 3 = 6 2 * 4 = 8 2 * 5 = 10 2 * 6 = 12 2 * 7 = 14 2 * 8 = 16 2 * 9 = 18 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 3 * 4 = 12 3 * 5 = 15 3 * 6 = 18 3 * 7 = 21 3 * 8 = 24 3 * 9 = 27 4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16 4 * 5 = 20 4 * 6 = 24 4 * 7 = 28 4 * 8 = 32 4 * 9 = 36 5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 5 * 6 = 30 5 * 7 = 35 5 * 8 = 40 5 * 9 = 45 6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30 6 * 6 = 36 6 * 7 = 42 6 * 8 = 48 6 * 9 = 54 7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49 7 * 8 = 56 7 * 9 = 63 8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64 8 * 9 = 72 9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81
str = input() str1 = str.strip() index = 0 count = 0 while index < len(str1): while str1[index] != " ": index += 1 if index == len(str1): break count += 1 if index == len(str1): break while str1[index] == " ": index += 1 print(count) 执行结果 C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\python.exe C:/Users/Administrator/PycharmProjects/untitled/day005/提取字符转里面的单词数.py 4 Process finished with exit code 0
#死循环:表达式永远为真的循环 while 1: print("My name is jjking.") 执行结果会一直一直的打印 My name is jjking. My name is jjking. My name is jjking. My name is jjking. My name is jjking. ...... 直到你手动结束程序为止
''' break语句: 作用:跳出for和while循环 注意:只能跳出距离他最近的那一层的循环 ''' for i in range(8): if i == 5: break print(i) ''' continue语句: 作用:跳过当前循环中的剩余语句 ''' for a in range(5): print(a) if a >= 3: continue print("$$$") #a += 1 num = 0 while num < 5: print(num) num += 1 if num >= 3: continue print("@@@") 执行结果 0 1 2 3 4 0 $$$ 1 $$$ 2 $$$ 3 4 0 @@@ 1 @@@ 2 3 4
''' for 语句,是一种循环语句 格式: for 变量名 in 集合: 语句 逻辑:按顺序取“集合”中的每个元素赋值给“变量”,再去执行语句 如此循环往复,直到取玩“集合”中的元素为止 ''' for i in [1,2,3,4,5]: print(i) ''' num = int(input()) if num in [1, 2, 3, 4, 5]: print("你输入的数字,我也有不信你看:%d"% num) ''' ''' range([start,] end[, step])函数 列表生成器 start 默认为0,step默认为1 功能:生成数列 ''' a = range(12) print(a) for i in range(12): print(i) for c in range(1, 20, 3): print(c) #同时遍历下标和元素 enumrate 枚举遍历器 for index, m in enumerate([1,2,3,4,5]): #index,m = 下标, 元素 print(index, m) #1+2+3+...+100 sum = 0 for n in range(101): sum += n print(sum) 执行结果 1 2 3 4 5 range(0, 12) 0 1 2 3 4 5 6 7 8 9 10 11 1 4 7 10 13 16 19 0 1 1 2 2 3 3 4 4 5 5050
''' if-elif-else语句 格式: if 表达式1: 语句1 elif 表达式2: 语句2 elif 表达式3: 语句3 ...... elif 表达式4: 语句4 else: #可有可无 语句n 逻辑:当程序执行到if-elif-else语句时,首先计算【表达式1】的值, 如果【表达式1】的值为真,则执行【语句1】,执行结束 跳过整个if-elif-else语句 如果【表达式1】的值为假,那么计算【表达式2】的值, 如果【表达式2】的值为真,则执行【语句2】,执行结束 跳过整个if-elif-else语句 ...... 如果没有1个是真的且有else的情况下,执行else里面的语句 否则直接继续向下执行,此段程序相当于没有执行 ''' #判断年龄 执行效率:每条语句必须执行一次,平局时间复杂度相当于5 age = int(input()) if age <= 0: print("没出生呢!") if age > 0 and age <= 3: print("婴儿") if age > 3 and age <= 7: print("幼儿") if age >7 and age <= 18: print("未成年") else: print("成年了") #优化方法 和上一个相比较执行效率提高,平均执行次数2.5 age = int(input()) if age <= 0: print("没出生呢!") elif age > 0 and age <= 3: print("婴儿") elif age > 3 and age <= 7: print("幼儿") elif age >7 and age <= 18: print("未成年") else: print("成年了") #逻辑优化 当执行 age<=3 的时候,一定是 age>0, 以此类推 age = int(input()) if age <= 0: print("没出生呢!") elif age <= 3: print("婴儿") elif age <= 7: print("幼儿") elif age <= 18: print("未成年") else: print("成年了") ''' 这个语句可以用来写只能回答,像小艾同学,天猫精灵啊。。。。 可以用提取关键字的方法来回答问题 在c#里曾经写过那个唐诗三百首,当你输入唐诗的诗名或作者显示相应的古诗词 '''
''' 本质;一种有序的集合 格式: 列表名 = [列表选项1, 列表选项2, ...列表选项n] ''' list1 = [23, 22, 24, 22, 25] print(list1) #元素数据可以不同 list2 = [1, 233, "name", "jjking", True] ''' 列表元素的访问 取值: 格式:列表名[下标] 注意:列表下标不要越界 ''' print(list1[2]) #列表操作: #列表组合 list3 = list1 + list2 print(list3) #列表的重复 print(list2 * 5) #判断元素是否在列表中 print(1 in list2) #列表截取 [2:3) print(list2[2:3]) #二维列表 list4 = [[123],[2,2,3],[1,2,3],[4,5,6,8]] print(list4[2][2]) #列表方法 list5 = [1,2,3,4,5,6] #appeng() 在列表末尾添加新的元素 list5.append(7) print(list5) list5.append([8,9]) print(list5) #extend() 在末尾一次性追加另一个列表中的多个值 list5.extend([1,2,3]) print(list5) #insert() 在下标处添加一个元素,元数据向后顺延 list5.insert(2,10) print(list5) #pop() 删除下标处的元素,默认为最后一个下标,并返回删除的数据 list5.pop() print(list5) list5.pop(2) print(list5) print(list5.pop(2)) #remove() 移除列表中的某个元素 list5.remove(5) list5.remove([8, 9]) print(list5) #clear() 清除列表中所有的数据 list6 = [1,2,3] list6.clear() print(list6) #index() 从列表中找出某个值的第一个匹配的索引值,可以加开始和结束的下标范围 print(list5.index(2)) print(list5.index(2, 4,8)) #len() 列表中的元素 print(len(list5)) #max() 获取列表中的最大值,只能是在一维列表,不然会报错 print(max(list5)) #min() 获取列表中的最小值,只能是在一维列表,不然会报错 print(min(list5)) #count() 某元素出现的次数 print(list5.count(2)) #浅拷贝 内存地址是一样的 lis7 = list5 print(id(list5)) print(id(lis7)) #copy() 深拷贝 内存的拷贝 内存的地址是不一样的 print(id(list5.copy())) #reverse() 倒序 list5.reverse() print(list5) #sort() 从小到大排序 list5.sort() print(list5) #元组转换成列表 list8 = list((1,2,3,4)) print(list8)
代码:num = 10000 sum = 0 while num <= 99999: a = num % 10 b = num // 10000 c = num % 1000 // 10 d = (num - (num//10000)*10000)//1000 if a == b and c == d: print(num) sum += 1 num += 1 print("5位数的回文数个数为:"sum) 执行结果: 10001 11011 12021 13031 14041 15051 16061 17071 18081 19091 20002 21012 22022 23032 24042 25052 26062 27072 28082 29092 30003 31013 32023 33033 34043 35053 36063 37073 38083 39093 40004 41014 42024 43034 44044 45054 46064 47074 48084 49094 50005 51015 52025 53035 54045 55055 56065 57075 58085 59095 60006 61016 62026 63036 64046 65056 66066 67076 68086 69096 70007 71017 72027 73037 74047 75057 76067 77077 78087 79097 80008 81018 82028 83038 84048 85058 86068 87078 88088 89098 90009 91019 92029 93039 94049 95059 96069 97079 98089 99099 5位数的回文数个数为: 90
代码: num = 100 while num <= 999: a = num // 100 b = (num - a * 100) // 10 c = num % 10 if num == a**3 + b**3 + c**3: print( num, "是水仙花数") num += 1执行结果: 153 是水仙花数 370 是水仙花数 371 是水仙花数 407 是水仙花数
''' while 语句: 格式: while 表达式: 语句 逻辑:当程序遇到while语句的时候,首先计算【表达式】的值 如果【表达式】的值为假,那么结束整个while语句 如果表达式的值为真,则执行【语句】,循环调用,直到为假停止 ''' #从1打印到小于5的数 num = 1 while num < 5: print("num = %d"% num) num += 1 #计算1+2+3+...+100 sum = 0 num = 1 while num <= 100: sum += num num += 1 #print("sum = %d" % sum) print("sum = %d"% sum) #打印字符串里的每一个字符 str = "My name is jjking." index = 0 while index <= len(str): print(str[index]) index += 1 运行结果: num = 1 num = 2 num = 3 num = 4 sum = 5050 M y n a m e i s j j k i n g .
if 语句 格式: if 表达式: 语句 (注意:if 和表达式之间必须有空格,语句之前必须有tab键,也就是4个空格) 逻辑: 当程序执行到if语句时,首先会计算“表达式”的值 如果“表达式”的值为真,那么就执行if下的“语句” 如果“表达式”的值为假,则跳过整个if语句,继续向下执行 if-else 语句 格式: if 表达式: 语句1 else 表达式: 语句2 逻辑:当程序执行到if-else语句时,首先计算“表达式”的值 如果表达式的值为真,则执行语句1,执行完语句1之后,跳出if-else语句 如果表达式的值为假,则执行语句2,执行完语句2之后,跳出if-else语句
''' 什么是字符串 字符串就是以单引号或双引号括起来的任意文本 ''' #创建字符串 str1 = "My name is jjking" str2 = "I am a Little White" ''' 字符串运算 ''' #字符串连接 str3 = "My name is " str4 = "jjking. " str5 = str3 + str4 print("str5 = ",str5) #输入重复字符串 str6 = str5 * 3 print(str6) #访问字符转中的某一个字符,通过索引下标查找字符,从0开始 str7 = "My name is jjking" print(str7[0]) print(str7[1]) print(str7[2]) print(str7[3]) #第 0 个为 M, 第1个为 y, 第 2 个是空格没打印出来,以此类推... #截取字符串中的一部分 str8 = "My name is jjking" str9 = str8[0:7] #[包含,不包含] str10 = str8[:7] #默认为0开始 str11 = str8[4:] #默认截取到最后 print(str9) print(str10) print(str11) #成员运算符测试jjking是否在str8 的字符串中 if "jjking" in str8: print("jjking 在 str8中出现了") print("name" in str8) #输出格式化 num = 1 str12 = "My name is jjking." f = 1.23 print("num = ", num, "str12 =", str12, "f =", f ) #使用%s %d %f 占位符 print("num = %d, str = %s, f = %f" % (num, str12, f)) #%3.f 表示保留小数点后3位,四舍五入法 print("f = %.3f"% f) ''' 转义字符 \ \n 输出 换行 \\ 输出 \ \" 输出 " \t 制表符 ''' print("num = %d\nstr = %s\nf = %f" % (num, str12, f)) print("num = %d\n\"str = %s\"\nf = %f\\" % (num, str12, f)) print("one\tsecond") print("\\\t\\") # r 字符串中有好多字符需要转移时使用,python允许使用 r 表示内部字符串默认不转义 # windows系统下的路径打印常用 print(r"\\\t\\") print(r"C:\Users\Administrator\PycharmProjects\untitled\day003") #按照格式输出 print('''--------------- first second Third ''') str12 = "My name is jjking." #eval(str) #功能:将字符串str当成有效的表达式来求值并返回计算结果 num1 = eval("123") print(num1) print(type(num1)) print(eval("+123")) print(eval("-123")) print(eval("12+3")) print(eval("12-3")) #len(str) #功能:返回字符串的长度 print(len("My name is jjking!")) print(len(str12)) #lower() 转换字符串中的大写字母为小写字母 print(str12.lower()) #upper() 转换字符串中的小写字母为大写字母 print(str12.upper()) #swapcase() 大小写互换 print(str12.swapcase()) #capitalize() 首字母大写 print(str12.capitalize()) #title() 单词的首字母大写 print(str12.title()) #center(width, fillchar) 返回指定宽度的居中的字符串用后面的字符填充 print(str12.center(30,"#")) #ljust(width[, fillchar]) 返回指定宽度的左对齐的字符串用后面的字符填充 print(str12.ljust(30,"*")) #rjust(width[, fillchar]) 返回指定宽度的右对齐的字符串用后面的字符填充 print(str12.rjust(30,"*")) #zfill(width) 返回指定宽度右对齐前面用 0 填充的字符串 print(str12.zfill(30)) #count([str[, start][, end]) 返回字符串中str出现的次数,可以指定一个范围,默认从头到尾 print(str12.count("is")) #find(str[, start][, end]) # 从左向右检测str字符串是否包含在字符串中,可以指定范围,默认从头到尾得到的是第一次出现的开始下标,没有返回-1 print(str12.find("is")) #rfind(str[, start][, end]) # 从右向左检测str字符串是否包含在字符串中,可以指定范围,默认从头到尾得到的是第一次出现的开始下标,没有返回-1 print(str12.rfind("is")) #index(str,start=0, end=len(str)) 和find()一样,但在str不存在的时候会报异常 print(str12.index("is")) #rindex(str,start=0, end=len(str)) 和rfind()一样,但在str不存在的时候会报异常 print(str12.rindex("is")) #lstrip() 截掉字符串左侧指定的字符,要从头开始,默认为空格 print(str12.lstrip("My")) #lstrip() 截掉字符串右侧制定的字符,,要从最后面开始,默认为空格 print(str12.rstrip("jjking.")) #split("", a) 以“ ”中的内容为分隔符截取字符串,a默认为1 print(str12.split(" ")) #splitlines([keepends]) 按照# ('\r', '\r\n', '\n')分隔 stra = (''' My name is jjking. I am a boy! ''') print(stra.splitlines()) #join(seq) 以一个特定的字符串分隔符,将seq中的所有元素组合成一个字符串 strjo =["a", "s", "s"] str_join = "##".join(strjo) print(str_join) #max() 返回字符串中ascii码值最大的 print(max(str12)) #min() 返回字符串中ascii码值最小的 print("$" + min(str12) + "$") #replace(oldstr, newstr, count) 默认全部替换,如果指定了count数量,那么只替换前count个 str_replace = str12.replace("is", "isn't", 1) print(str_replace) #创建一个字符串映射表 str_maketrans = str12.maketrans("is", "nt") # i->n s->t str13 = "P is is kjs is;" str_translate = str13.translate(str_maketrans) print(str_translate) #startswith(str, start = 0, end = len(str)) #在给定的范围内判断是否以给定的字符串开头的,如果没有给定范围,默认整个字符串 print(str12.startswith("is" )) #endwith(str, start = 0, end = len(str)) #在给定的范围内判断是否以给定的字符串结尾的,如果没有给定范围,默认整个字符串 print(str12.endswith("is" )) #编码 #encode(encoding="utf-8", error="strict") print(str12.encode()) data = str12.encode("utf-8", "ignore") #解码 注意:要和编码使用的码制一致 python3之后没有decode()了 str_encode = data.decode("utf-8","ignore") print("###",str_encode, "###") print(type(str_encode)) #isalpha() #如果字符串中至少有一个字符且所有字符都是字母返回True,否则返回False print(str12.isalpha()) #isalnum() #如果字符串中至少有一个字符且所有字符都是字母或数字返回True,否则返回False print(str12.isalnum()) #isupper() #如果字符串中至少有一个英文字符且所有字符都是大写字母或数字或特殊字符返回True,否则返回False str_upper = "ACSD" print(str_upper.isupper()) print("ASD1".isupper()) print("ASD1#".isupper()) #islower() #如果字符串中至少有一个英文字符且所有字符都是小写字母或数字或特殊字符返回True,否则返回False str_upper = "acs" print(str_upper.islower()) print("asd1".islower()) print("asd1#".islower()) #istitle() #如果字符串是标题化的返回True,否则返回False print("My name".istitle()) #错的 print("My Name".istitle()) #对的 #isdigit() #如果字符串只包含数字字符返回True,否则返回False print("123".isdigit()) print("ade".isdigit()) #错的 #isnumeric() #如果字符串只包含数字返回True,否则返回False print("123".isnumeric()) print("ade".isnumeric()) #错的 #isdecimal() #如果字符串只包含十进制字符返回True,否则返回False print("123".isdecimal()) print("ade".isdecimal()) #错的 #isspace() #如果字符串中只包含空格则返回True,否则返回False print(" ".isspace()) print("\t".isspace()) print("\r".isspace()) print("\n".isspace()) #都是对的 执行结果: C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\python.exe C:/Users/Administrator/PycharmProjects/untitled/day003/String.py str5 = My name is jjking. My name is jjking. My name is jjking. My name is jjking. M y n My name My name ame is jjking jjking 在 str8中出现了 True num = 1 str12 = My name is jjking. f = 1.23 num = 1, str = My name is jjking., f = 1.230000 f = 1.230 num = 1 str = My name is jjking. f = 1.230000 num = 1 "str = My name is jjking." f = 1.230000\ one second \ \ \\\t\\ C:\Users\Administrator\PycharmProjects\untitled\day003 --------------- first second Third 123 <class 'int'> 123 -123 15 9 18 18 my name is jjking. MY NAME IS JJKING. mY NAME IS JJKING. My name is jjking. My Name Is Jjking. ######My name is jjking.###### My name is jjking.************ ************My name is jjking. 000000000000My name is jjking. 1 8 8 8 8 name is jjking. My name is ['My', 'name', 'is', 'jjking.'] ['', 'My name is jjking.', 'I am a boy!'] a##s##s y $ $ My name isn't jjking. P nt nt kjt nt; False False b'My name is jjking.' ### My name is jjking. ### <class 'str'> False False True True True True True True False True True False True False True False True True True True Process finished with exit code 0
''' 位运算符:按位运算是把数字看作是二进制数来计算 & / ^ ~ << >> ''' #与运算: & (同 1 为 1,否则为 0) print(5 & 7) #或运算: | (有 1 为 1,同 0 则 0) print(5 | 7) #异或运算:^ (相同为 0,不同为 1) print(5 ^ 7) # 取反:~ (1 变为 0, 0 变为 1) print(~2) #左移运算符: << () #各二进制位全部左移若干位,高位丢弃,低位补零,<< 右侧的数字决定移动几位 print(2<<2) #右移运算符: >> () #各二进制位全部右移若干位,高位丢弃,低位补零,<< 右侧的数字决定移动几位 print(10>>1) ''' 关系运算符和关系运算表达式 关系运算符: == != > < >= <= 关系运算表达式: 格式: 【表达式1】 关系运算符 【表达式2】 功能:计算【表达式1】和【表达式2】的值 值:如果关系成立,整个关系运算表达式的值为真,否则为假 ''' ''' 逻辑运算符(3种) 逻辑与: and 逻辑与运算表达式: 【表达式1】 and 【表达式2】 值:【表达式1】【表达式2】同真为真,有假则为假 **短路原则:【表达式1】 and 【表达式2】 and 【表达式3】 .....and 【表达式n】 从前向后执行,遇到假就立刻停止 逻辑或: or 逻辑或运算表达式: 【表达式1】 or 【表达式2】 值:【表达式1】【表达式2】有一个为真就是真,都是假为假 **短路原则:【表达式1】 or 【表达式2】 or 【表达式3】 .....or 【表达式n】 从前向后执行,遇到真就立刻停止 逻辑非: not 逻辑非运算表达式: not 【表达式1】 值:真变假,假变真 ''' ''' 成员运算符 in:如果在指定序列中找到值返回True,否则返回False not in:如果在指定序列中没有找到值返回True,否则返回False ''' ''' 身份运算符 is:判断两个标识符是不是引用同一个对象 is not:判断两个标识符是不是引用不同的对象 ''' ''' 运算符优先级 ** ~ +(正) -(负) * / % // +(加) -(减) >> << & ^ | <= < > >= == != = %= += -= //= **= /= is is not in not in not or and ''' print(~2) ''' 取反过程: 内存中都是补码的形式存储 2在内存中存的补码是 00000000 00000000 00000000 00000010 2在内存中存的补码取反 11111111 11111111 11111111 11111101 求原码(除符号位,逐位取反,末位+1) 10000000 00000000 00000000 00000011 则结果为-3 '''
#模拟彩票随机中奖 import random num = int(input("请输入您的号码:")) res = random.choice(range(100))+1 print("本期中奖号码为:", res) #判断是否中奖2 if res == num: print("恭喜您中奖了!!!") else: print("您未中奖,再接再厉!")
第一次写的比较复杂了#三位数比较大小 num1 = int(input("num1 = ")) num2 = int(input("num2 = ")) num3 = int(input("num3 = ")) if num1 < num2: max = num2 - num3 if max > 0: print("最大的数是", num2) else: print("最大的数是", num3) else: max = num1 - num3 if max > 0: print("最大的数是;", num1) else: print("最大的数是;", num3) 看了视频之后自己又写了一遍 #三位数比较大小 num1 = int(input("num1 = ")) num2 = int(input("num2 = ")) num3 = int(input("num3 = ")) max = num1 if num2 > num1: max = num2 if num3 > max: max = num3 print("最大数为:", max)
#打印回文数 num = int(input("请输入一个五位数:")) wanwei = num // 10000 qianwei = (num - wanwei * 10000) // 1000 baiwei = (num - wanwei * 10000 - qianwei *1000) // 100 shiwei = (num - wanwei * 10000 - qianwei *1000 - baiwei * 100) // 10 gewei = (num - wanwei * 10000 - qianwei *1000 - baiwei * 100 - shiwei * 10) if wanwei == gewei: if qianwei == shiwei: print("这是一个回文数") else: print("这个数不是回文数")
#打印水仙花数 num = int(input("请输入一个三位数(100~999):")) baiwei = num//100 shiwei = (num - baiwei*100)//10 gewei = num - baiwei * 100 - shiwei * 10 if num == baiwei ** 3 + shiwei ** 3 + gewei ** 3: print("这是水仙花数!") else: print("不是水仙花数!")