zoukankan      html  css  js  c++  java
  • 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(当前用户)AppDataLocalProgramsPythonPython35;

    环境变量配置:【右键计算机】—>【属性】—>【高级系统设置】—>【高级】—>【环境变量】—>【系统环境变量】修改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 中最常用的数据类型。我们可以使用引号来创建字符串。

    创建字符串很简单,只要为变量分配一个值即可。

    例如:

      1 var1 = 'Hello World!'
      2 var2 = "Python Programming"
    字符串

    访问字符串中的值

    Python不支持单字符类型,单字符也在Python也是作为一个字符串使用。

    Python访问子字符串,可以使用方括号来截取字符串,如下实例:

      1 #!/usr/bin/python
      2 
      3 var1 = 'Hello World!'
      4 var2 = "Python Programming"
      5 
      6 print "var1[0]: ", var1[0]
      7 print "var2[1:5]: ", var2[1:5]
      8 
      9 
     10 
     11 #结果:
     12 #var1[0]:  H
     13 #var2[1:5]:  ytho
     14 
    访问字符串

    字符串更新

    可以“update”现有的字符串(重新)分配到另一个字符串变量。其以前的值或一个完全不同的字串完全可以与新的价值。
    例如:

      1 #!/usr/bin/python
      2 
      3 var1 = 'Hello World!'
      4 
      5 print "Updated String :- ", var1[:6] + 'Python'
      6 
      7 
      8 #结果:
      9 #Updated String :-  Hello Pytho
    字符串更新

    转义字符

    下表是一个逃跑或反斜线符号可以代表的非打印字符的清单。
    注:在doublequoted字符串,转义字符被解释;在singlequoted字符串,转义字符被保留。

    反斜线 符号

    十六进制字符

    描述

    a

    0x07

    Bell or alert

    

    0x08

    Backspace

    cx

     

    Control-x

    C-x

     

    Control-x

    e

    0x1b

    Escape

    f

    0x0c

    Formfeed

    M-C-x

     

    Meta-Control-x

    0x0a

    Newline

    nn

     

    Octal notation, where n is in the range 0.7

    0x0d

    Carriage return

    s

    0x20

    Space

    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' ' prints and print R' 'prints

    %

    格式化 - 执行字符串格式

    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 或 r+ 模式同使用)

    • rU
    • r+U

    "b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

    • rb
    • wb
    • ab
      1 class file(object):
      2   
      3     def close(self): # real signature unknown; restored from __doc__
      4         关闭文件
      5         """
      6         close() -> None or (perhaps) an integer.  Close the file.
      7          
      8         Sets data attribute .closed to True.  A closed file cannot be used for
      9         further I/O operations.  close() may be called more than once without
     10         error.  Some kinds of file objects (for example, opened by popen())
     11         may return an exit status upon closing.
     12         """
     13  
     14     def fileno(self): # real signature unknown; restored from __doc__
     15         文件描述符  
     16          """
     17         fileno() -> integer "file descriptor".
     18          
     19         This is needed for lower-level file interfaces, such os.read().
     20         """
     21         return 0    
     22  
     23     def flush(self): # real signature unknown; restored from __doc__
     24         刷新文件内部缓冲区
     25         """ flush() -> None.  Flush the internal I/O buffer. """
     26         pass
     27  
     28  
     29     def isatty(self): # real signature unknown; restored from __doc__
     30         判断文件是否是同意tty设备
     31         """ isatty() -> true or false.  True if the file is connected to a tty device. """
     32         return False
     33  
     34  
     35     def next(self): # real signature unknown; restored from __doc__
     36         获取下一行数据,不存在,则报错
     37         """ x.next() -> the next value, or raise StopIteration """
     38         pass
     39  
     40     def read(self, size=None): # real signature unknown; restored from __doc__
     41         读取指定字节数据
     42         """
     43         read([size]) -> read at most size bytes, returned as a string.
     44          
     45         If the size argument is negative or omitted, read until EOF is reached.
     46         Notice that when in non-blocking mode, less data than what was requested
     47         may be returned, even if no size parameter was given.
     48         """
     49         pass
     50  
     51     def readinto(self): # real signature unknown; restored from __doc__
     52         读取到缓冲区,不要用,将被遗弃
     53         """ readinto() -> Undocumented.  Don't use this; it may go away. """
     54         pass
     55  
     56     def readline(self, size=None): # real signature unknown; restored from __doc__
     57         仅读取一行数据
     58         """
     59         readline([size]) -> next line from the file, as a string.
     60          
     61         Retain newline.  A non-negative size argument limits the maximum
     62         number of bytes to return (an incomplete line may be returned then).
     63         Return an empty string at EOF.
     64         """
     65         pass
     66  
     67     def readlines(self, size=None): # real signature unknown; restored from __doc__
     68         读取所有数据,并根据换行保存值列表
     69         """
     70         readlines([size]) -> list of strings, each a line from the file.
     71          
     72         Call readline() repeatedly and return a list of the lines so read.
     73         The optional size argument, if given, is an approximate bound on the
     74         total number of bytes in the lines returned.
     75         """
     76         return []
     77  
     78     def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
     79         指定文件中指针位置
     80         """
     81         seek(offset[, whence]) -> None.  Move to new file position.
     82          
     83         Argument offset is a byte count.  Optional argument whence defaults to
     84         0 (offset from start of file, offset should be >= 0); other values are 1
     85         (move relative to current position, positive or negative), and 2 (move
     86         relative to end of file, usually negative, although many platforms allow
     87         seeking beyond the end of a file).  If the file is opened in text mode,
     88         only offsets returned by tell() are legal.  Use of other offsets causes
     89         undefined behavior.
     90         Note that not all file objects are seekable.
     91         """
     92         pass
     93  
     94     def tell(self): # real signature unknown; restored from __doc__
     95         获取当前指针位置
     96         """ tell() -> current file position, an integer (may be a long integer). """
     97         pass
     98  
     99     def truncate(self, size=None): # real signature unknown; restored from __doc__
    100         截断数据,仅保留指定之前数据
    101         """
    102         truncate([size]) -> None.  Truncate the file to at most size bytes.
    103          
    104         Size defaults to the current file position, as returned by tell().
    105         """
    106         pass
    107  
    108     def write(self, p_str): # real signature unknown; restored from __doc__
    109         写内容
    110         """
    111         write(str) -> None.  Write string str to file.
    112          
    113         Note that due to buffering, flush() or close() may be needed before
    114         the file on disk reflects the data written.
    115         """
    116         pass
    117  
    118     def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
    119         将一个字符串列表写入文件
    120         """
    121         writelines(sequence_of_strings) -> None.  Write the strings to the file.
    122          
    123         Note that newlines are not added.  The sequence can be any iterable object
    124         producing strings. This is equivalent to calling write() for each string.
    125         """
    126         pass
    127  
    128     def xreadlines(self): # real signature unknown; restored from __doc__
    129         可用于逐行读取文件,非全部
    130         """
    131         xreadlines() -> returns self.
    132          
    133         For backward compatibility. File objects now include the performance
    134         optimizations previously implemented in the xreadlines module.
    135         """
    136         pass
    文件操作源码

    方法一:

    文件写入

      1 #打开模式列表:
      2 #w      以写方式打开,
      3 #a      以追加模式打开 (从 EOF 开始, 必要时创建新文件)
      4 #r+     以读写模式打开
      5 #w+     以读写模式打开 (参见 w )
      6 #a+     以读写模式打开 (参见 a )
      7 #rb     以二进制读模式打开
      8 #wb     以二进制写模式打开 (参见 w )
      9 #ab     以二进制追加模式打开 (参见 a )
     10 #rb+    以二进制读写模式打开 (参见 r+ )
     11 #wb+    以二进制读写模式打开 (参见 w+ )
     12 #ab+    以二进制读写模式打开 (参见 a+ )
     13 f = open('tpm.txt', 'a+')
     14  
     15 for i in range(10) :
     16     f.write(time.strftime('%Y-%m-%d %H:%M:%S'))
     17     f.write(' ' + str(random.randint(0, i)) + '
    ')
     18  
     19 f.close()
    文件写入

    文件读取

      1 f = open('tpm.txt')
      2 # read方式读取
      3 s = f.read()
      4 print(s, '
    
    
    ')
      5 print(f.tell())
      6 #上面读取完后指针移动到最后,通过seek将文件指针移动到文件头
      7 f.seek(0)
      8 #使用readline每次读取一行
      9 while(True):
     10     line = f.readline()
     11     print(line)
     12     if(len(line) == 0):
     13         break
     14  
     15 f.close()
    文件读取

    方法二:

    1 with open ("文件路径",“打开模式”) as b:
    2         b.write()
    使用with

    主文件通过__name__  =  "__main__"来标识

  • 相关阅读:
    Python学习笔记(6)-异常
    Python学习笔记(1)-基本概念
    自动化测试工具Sikuli的安装以及应用
    SoapUI添加断言
    SoapUI接口之间的数据传递
    Fitnesse初体验
    SoapUI5.1.2命令行执行https类型接口集成
    SoapUI命令行执行测试用例
    Jenkins集成AirTest不启动浏览器
    AirTest执行时不能输入汉字
  • 原文地址:https://www.cnblogs.com/spykids/p/5155569.html
Copyright © 2011-2022 走看看