python学习day2(一)
一.上周作业回顾
1.登陆接口:
思路流程:
1.登陆,三次锁定用户
2.用户信息文件,黑名单文件
3.检测黑名单,如输入账号在黑名单中存在,不允许登陆
4.用户密码判断
主要知识点:while,for循环,if判断,文件操作
2.三级菜单:
1.写字典,大字典里套小字典,再在小字典里套列表
2.程序开始,列出大字典力所有的keys。
3.用户选择后,列出小字典的key。
4.用户再次选择后,列出小字典中的列表。
5.在用户选择的时候,可以加入判断,如是否输入正确
6.在用户选择的时候,加入b返回上级,q退出程序
知识点:while,for循环,if判断,字典,列表操作
二.今天内容简介
1.Python简介
2.基本数据类型
3.文件操作
4.管理上下文
Python简介
1.python历史
详情见链接:python详细信息
2.python种类
原理:
cpython
print(‘aaa’) c解释器 .pyc(字节码) 机器码 CPU
jpython
print(‘aaa’) java解释器 java字节码 机器码 CPU
ironpython
print(‘aaa’) c#解释器 c#字节码 机器码 CPU
由上得出python种类区分主要是解释器不同,而我们常用的是cpython。
3.python安装环境
windows:
从官网下载安装包,进行安装;
2.7版本默认安装路径:c:\python2.7;3.x版本默认安装路径:C:\Users\(当前用户)\AppData\Local\Programs\Python\Python35\;
环境变量配置:【右键计算机】—>【属性】—>【高级系统设置】—>【高级】—>【环境变量】—>【系统环境变量】修改path,添加python安装路径。
Liunx:
默认装有python。
注:升级python后,修改yum使用的python版本
基本数据类型:
1.数字:
int(有符号整数)
通常被称为只是整数或整数,是正或负整数,不带小数点。
long(长整数)
是无限大的整数,这样写整数,后面跟着一个大写或小写的L。(在3.x版本中与int统一为一种类型,删除了后缀L)
float(浮点实数值)
或浮点数,表示实数,并写入一个小数点分隔的整数部分和小数部分。浮点数也可以是科学记数法,用e或E表示的功率10 (2.5e2 = 2.5 x 102 = 250).
complex(复数)
形式如 a + bJ,其中a和b是浮点和J(或j)表示-1的平方根(这是一个虚数)。 a是数的实部,b是虚部。Python编程不使用复杂的数字。
2.布尔值
真或假
1或0
3.字符串
字符串是 Python 中最常用的数据类型。我们可以使用引号来创建字符串。
创建字符串很简单,只要为变量分配一个值即可。
例如:
var1 = 'Hello World!'
var2 = "Python Programming"字符串
访问字符串中的值
Python不支持单字符类型,单字符也在Python也是作为一个字符串使用。
Python访问子字符串,可以使用方括号来截取字符串,如下实例:
#!/usr/bin/python var1 = 'Hello World!'
var2 = "Python Programming" print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5] #结果:
#var1[0]: H
#var2[1:5]: ytho访问字符串
字符串更新
可以“update”现有的字符串(重新)分配到另一个字符串变量。其以前的值或一个完全不同的字串完全可以与新的价值。
例如:#!/usr/bin/python var1 = 'Hello World!' print "Updated String :- ", var1[:6] + 'Python' #结果:
#Updated String :- Hello Pytho字符串更新
转义字符
下表是一个逃跑或反斜线符号可以代表的非打印字符的清单。
注:在doublequoted字符串,转义字符被解释;在singlequoted字符串,转义字符被保留。
反斜线 符号
十六进制字符
描述
\a
0x07
Bell or alert
\b
0x08
Backspace
\cx
Control-x
\C-x
Control-x
\e
0x1b
Escape
\f
0x0c
Formfeed
\M-\C-x
Meta-Control-x
\n
0x0a
Newline
\nnn
Octal notation, where n is in the range 0.7
\r
0x0d
Carriage return
\s
0x20
Space
\t
0x09
Tab
\v
0x0b
Vertical tab
\x
Character x
\xnn
Hexadecimal notation, where n is in the range 0.9, a.f, or A.F
字符串运算符
假设A持有'hello'和变量b拥有'Python'的字符串变量:
操作符
描述
例子
+
串联 - 添加操作两边的值
a + b 将得到 HelloPython
*
重复 - 创建新的字符串,相同的字符串连接的多个副本
a*2 将得到 -HelloHello
[]
切片 - 从给定的索引字符
a[1] will give e
[:]
范围切片 - 从给定范围内的字符
a[1:4] will give ell
in
成员关系 - 返回true,如果存在一个字符在给定的字符串
H in a will give 1
not in
成员关系 - 返回true如果不存在一个字符在给定的字符串
M not in a will give 1
r/R
原始字符串 - 禁止转义字符的实际意义。原始字符串的语法是完全正常与异常的原始字符串操作,字母“r”,前面的引号字符串相同。 “R”可以是小写字母(R)或大写字母(R)的,必须放在紧接第一个引号。
print r'\n' prints \n and print R'\n'prints \n
%
格式化 - 执行字符串格式
See at next section
万恶的字符串拼接:
pythom中的字符串在C语言中体现为师一个字符数组,每次创建字符串的时候需要在内存中开辟一块连续的空间,并且一旦修改字符串的话,就需要在次开辟一块新的连续空间,万恶的加号(+)每出现一次,就会在内存中重新开辟一块新的空间。
下面是一套完整的符号可用%的列表:
格式符号
转换含义
%c
character
%s
string conversion via str() prior to formatting
%i
signed decimal integer
%d
signed decimal integer
%u
unsigned decimal integer
%o
octal integer
%x
hexadecimal integer (lowercase letters)
%X
hexadecimal integer (UPPERcase letters)
%e
exponential notation (with lowercase 'e')
%E
exponential notation (with UPPERcase 'E')
%f
floating point real number
%g
the shorter of %f and %e
%G
the shorter of %f and %E
其他支持的符号和功能下表中列出:
符号
功能
*
argument specifies width or precision
-
left justification
+
display the sign
leave a blank space before a positive number
#
add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether 'x' or 'X' were used.
0
pad from left with zeros (instead of spaces)
%
'%%' leaves you with a single literal '%'
(var)
mapping variable (dictionary arguments)
m.n.
m is the minimum total width and n is the number of digits to display after the decimal point (if appl.)
字符串的常用操作:
移除空白 strip
分割 split
长度 len(obj)
索引 obj[1]
切片 obj[:]
4.列表
列表简介:
列表是序列对象,可包含任意的Python数据信息,如字符串、数字、列表、元组等
列表的数据是可变的,我们可通过对象方法对列表中的数据进行增加、修改、删除等操作
可以通过list(seq)函数把一个序列类型转换成一个列表
列表常用操作:
索引 index
切片 :
追加 append
删除 del;remove;pop
长度 len
循环 for;while;(foreach)
break;continue;pass;return;exit(0...)
包含 in __contains__
5.元组
元组元素不可修改,元祖元素的元素可以被修改。
索引 index
切片 :
长度 len
循环 for;while;(foreach)
break;continue;pass;return;exit(0...)
包含 in __contains__
6.字典
索引 通过key来索引
新增 d[key] values
删除 del d[key]
键,值,键值对
keys values items
循环 for;while
长度 len
详细操作请点击此处
7.文件操作
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
- r,只读模式(默认)。
- w,只写模式。【不可读;不存在则创建;存在则删除内容;】
- a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
- r+,可读写文件。【可读;可写;可追加】
- w+,写读
- a+,同a
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
- rU
- r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
- rb
- wb
- ab
class file(object): def close(self): # real signature unknown; restored from __doc__
关闭文件
"""
close() -> None or (perhaps) an integer. Close the file. Sets data attribute .closed to True. A closed file cannot be used for
further I/O operations. close() may be called more than once without
error. Some kinds of file objects (for example, opened by popen())
may return an exit status upon closing.
""" def fileno(self): # real signature unknown; restored from __doc__
文件描述符
"""
fileno() -> integer "file descriptor". This is needed for lower-level file interfaces, such os.read().
"""
return 0 def flush(self): # real signature unknown; restored from __doc__
刷新文件内部缓冲区
""" flush() -> None. Flush the internal I/O buffer. """
pass def isatty(self): # real signature unknown; restored from __doc__
判断文件是否是同意tty设备
""" isatty() -> true or false. True if the file is connected to a tty device. """
return False def next(self): # real signature unknown; restored from __doc__
获取下一行数据,不存在,则报错
""" x.next() -> the next value, or raise StopIteration """
pass def read(self, size=None): # real signature unknown; restored from __doc__
读取指定字节数据
"""
read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given.
"""
pass def readinto(self): # real signature unknown; restored from __doc__
读取到缓冲区,不要用,将被遗弃
""" readinto() -> Undocumented. Don't use this; it may go away. """
pass def readline(self, size=None): # real signature unknown; restored from __doc__
仅读取一行数据
"""
readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF.
"""
pass def readlines(self, size=None): # real signature unknown; restored from __doc__
读取所有数据,并根据换行保存值列表
"""
readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned.
"""
return [] def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
指定文件中指针位置
"""
seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to
0 (offset from start of file, offset should be >= 0); other values are 1
(move relative to current position, positive or negative), and 2 (move
relative to end of file, usually negative, although many platforms allow
seeking beyond the end of a file). If the file is opened in text mode,
only offsets returned by tell() are legal. Use of other offsets causes
undefined behavior.
Note that not all file objects are seekable.
"""
pass def tell(self): # real signature unknown; restored from __doc__
获取当前指针位置
""" tell() -> current file position, an integer (may be a long integer). """
pass def truncate(self, size=None): # real signature unknown; restored from __doc__
截断数据,仅保留指定之前数据
"""
truncate([size]) -> None. Truncate the file to at most size bytes. Size defaults to the current file position, as returned by tell().
"""
pass def write(self, p_str): # real signature unknown; restored from __doc__
写内容
"""
write(str) -> None. Write string str to file. Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.
"""
pass def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
将一个字符串列表写入文件
"""
writelines(sequence_of_strings) -> None. Write the strings to the file. Note that newlines are not added. The sequence can be any iterable object
producing strings. This is equivalent to calling write() for each string.
"""
pass def xreadlines(self): # real signature unknown; restored from __doc__
可用于逐行读取文件,非全部
"""
xreadlines() -> returns self. For backward compatibility. File objects now include the performance
optimizations previously implemented in the xreadlines module.
"""
pass文件操作源码
方法一:
文件写入
#打开模式列表:
#w 以写方式打开,
#a 以追加模式打开 (从 EOF 开始, 必要时创建新文件)
#r+ 以读写模式打开
#w+ 以读写模式打开 (参见 w )
#a+ 以读写模式打开 (参见 a )
#rb 以二进制读模式打开
#wb 以二进制写模式打开 (参见 w )
#ab 以二进制追加模式打开 (参见 a )
#rb+ 以二进制读写模式打开 (参见 r+ )
#wb+ 以二进制读写模式打开 (参见 w+ )
#ab+ 以二进制读写模式打开 (参见 a+ )
f = open('tpm.txt', 'a+') for i in range(10) :
f.write(time.strftime('%Y-%m-%d %H:%M:%S'))
f.write(' ' + str(random.randint(0, i)) + '\n') f.close()文件写入
文件读取
f = open('tpm.txt')
# read方式读取
s = f.read()
print(s, '\n\n\n')
print(f.tell())
#上面读取完后指针移动到最后,通过seek将文件指针移动到文件头
f.seek(0)
#使用readline每次读取一行
while(True):
line = f.readline()
print(line)
if(len(line) == 0):
break f.close()文件读取
方法二:
with open ("文件路径",“打开模式”) as b:
b.write()使用with
主文件通过__name__ = "__main__"来标识
python学习day2(一)的更多相关文章
- Python学习-day2
这周时间充裕,把第一周的两个作业登陆验证和三级菜单做完后又用零零散散的时间看完了第二周的课程,不得不说老男孩这个教育方式感觉还是不错的,其实说白了就是花钱找个人监督自己学习呗,而且还强行让我们养成一些 ...
- python学习day2
一.模块初识 python模块 模块让你能够有逻辑地组织你的Python代码段. 把相关的代码分配到一个 模块里能让你的代码更好用,更易懂. 模块也是Python对象,具有随机的名字属性用来绑定或引用 ...
- python学习day2(二)
1.类与对象的关系 对于Python,一切事物都是对象,对象基于类创建 type是获取类的 dir是获取这个类里面的成员 2.int内部功能介绍 bit_length:返回表示当前数字占用的最少位数: ...
- python学习Day2 python 、pycharm安装及环境变量配置
复习 进制转换:二进制&十六进制转换(从左往右1248机制,每四位二进制对应一位16进制) 二进制&十进制转换 2n-1幂次方相加 十进制到二进制转化 将十进制除以2,把余数记下 ...
- python学习 day2 (3月2日)
.if if else 和 if elif else 的区别是: 前者 判断第一个 判断完第二个 之后还会执行else: 后者是只有满足条件(即都不符合if.elif里的条件时才会进入else) 不清 ...
- Python学习Day2笔记(字符编码和函数)
1.字符编码 #ASCII码里只能存英文和特殊字符 不能存中文 存英文占1个字节 8位#中文编码为GBK 操作系统编码也为GBK#为了统一存储中文和英文和其他语言文字出现了万国码Unicode 所有一 ...
- Python学习Day2笔记(集合和文件操作)
1.集合的使用 列表是有序的可包含重复内容的 集合是无序的不可包含重复内容的 1) 集合关系测试 #列表去重list_1=[1,4,5,6,7,8,9,7,5,4,23,2] #有重复数据 list_ ...
- Python学习day2 while循环&格式化输出&运算符
day2 运算符-while循环 1.while循环 while循环基本结构; while 条件: 结果 # 如果条件为真,那么循环则执行 # 如果条件为假,那么循环不执行 de ...
- Python学习日记 --day2
Python学习日记 --day2 1.格式化输出:% s d (%为占位符 s为字符串类型 d为数字类型) name = input('请输入姓名') age = int(input('请输入年龄 ...
随机推荐
- 正确合理的建立MYSQL数据库索引
写在前面:索引对查询的速度有着至关重要的影响,理解索引也是进行数据库调优的起点.考虑如下情况,假设数据库中一个表有10^6条记录,DBMS的页面大小为4K,并存储100条记录.如果没有索引,查询将对整 ...
- canvas认识
1使用canvas绘制一个矩形 <canvas id="canvas" width="640" height="360">< ...
- 水池(DFS)
水池数目 点我 描述 南阳理工学院校园里有一些小河和一些湖泊,现在,我们把它们通一看成水池,假设有一张我们学校的某处的地图,这个地图上仅标识了此处是否是水池,现在,你的任务来了,请用计算机算出该地图中 ...
- Nginx学习之一-第一个程序Hello World
本例子实现了一个简单的hello world程序.运行效果: 虚拟机Ubuntu中: win7中chrome浏览器: 一.config文件编写 Nginx提供了一种简单的方式将第三方的模块编译到Ngi ...
- progressbar样式
http://www.oschina.net/question/8676_11797 http://blog.csdn.net/ouyangtianhan/article/details/656576 ...
- 如何自定义MVC控件?
今天公司要写学习总结,想着想着还是先写一篇关于MVC内部什么东东的博客整理整理再发表吧,一举两得. 之前写过了路由.过滤器等.今天就研究一下怎么自定义MVC控件吧. 本人技术小菜,不喜勿喷.....( ...
- 浅析 C++里面的宏
说到宏,恐怕大家都能说出点东西来:一种预处理,没有分号(真的吗?).然后呢?嗯.......茫然中......好吧,我们就从这开始说起.最常见的宏恐怕是#include 了,其次就是#define 还 ...
- ubuntu设置系统时间与网络时间同步和时区
Linux的时间分为System Clock(系统时间)和Real Time Clock (硬件时间,简称RTC). 系统时间:指当前Linux Kernel中的时间. 硬件时间:主板上有电池供电的时 ...
- 启动Tomcat自动加载(运行)类
其实这是紧跟着我上次写的java计时器Timer的,因为Timer的测试类写好后,不可能要通过什么东西去触发,对已经存在的时间点进行监控 所以,在启动项目是自动运行此类 方法如下: 一.在web.xm ...
- Android UI目录
Android UI目录 序:最近一直想进阶android应用开发,虽然对一些相关的android知识都大体熟悉,但是自己的android知识体系,经不起推敲.经不起高手的垂问.经过几个月的努力学习, ...