zoukankan      html  css  js  c++  java
  • Python入门(基本概念一)

    1.1     输入/输出

    1.1.1            输入raw_input(),例:

    >>> user = raw_input('Enter login name: ')

    Enter login name: root

     

    >>> print 'Your login is:', user

    Your login is: root

     

    1.1.2            输出 print ,例:

    >>> print "Hello""

    Python is number 1!

     

    >>> print "%s is number %d!" % ("Python", 1)

    Python is number 1!

     

    1.2     注释

    # 符号标示注释,但能注释单行,还有一种叫做文档字符串的特别注释。你可以在模块、类或者函数的起始添加一个字符串,起到在线文档的功能。

    def foo():

    "This is a doc string."

    return True

    与普通注释不同,文档字符串可以在运行时访问,也可以用来自动生成文档。

    1.3     缩进

    空白在Python中是重要的。事实上行首的空白是重要的。它称为缩进。在逻辑行首的空白(空格和制表符)用来决定逻辑行的缩进层次,从而用来决定语句的分组。

    这意味着同一层次的语句必须有相同的缩进。每一组这样的语句称为一个块。我们将在后面的章节中看到有关块的用处的例子。你需要记住的一样东西是错误的缩进会引发错误。例如:

    i = 5

    print 'Value is', i # Error! Notice a single space at the start of the line

    print 'I repeat, the value is', i

    当你运行这个程序的时候,你会得到下面的错误:

    File "whitespace.py", line 4

    print 'Value is', i # Error! Notice a single space at the start of the line

    ^

    SyntaxError: invalid syntax

    注意,在第二行的行首有一个空格。Python指示的这个错误告诉我们程序的语法是无效的,即程序没有正确地编写。

    如何缩进,不要混合使用制表符和空格来缩进,因为这在跨越不同的平台的时候,无法正常工作。我 强烈建议 你在每个缩进层次使用 单个制表符 两个或四个空格 。选择这三种缩进风格之一。更加重要的是,选择一种风格,然后一贯地使用它,即 使用这一种风格。

    1.4   运算符

    1.4.1       算术运算符

    与大部分编程语言一样,+  -  *  /  //  %  **Python 有两种除法运算符,单斜杠用作传统除法,双斜杠用作浮点除法(对结果进行四舍五入),还有一个乘方运算符, 双星号(**)

    1.4.2       比较运算符

    <    <=    >    >=    ==    !=    <>

    >>> 2 < 4

    True

    >>> 2 == 4

    False

    >>> 2 > 4

    False

    >>> 6.2 <= 6

    False

    >>> 6.2 <= 6.2

    True

    >>> 6.2 <= 6.20001

    True

    1.4.3       逻辑运算符

        and or not

    >>> 2 < 4 and 2 == 4

    False

    >>> 2 > 4 or 2 < 4

    True

    1.5     变量赋值

    >>> counter = 0

    >>> miles = 1000.0

    >>> name = 'Bob'

    >>> counter = counter + 1

    >>> kilometers = 1.609 * miles

    >>> print '%f miles is the same as %f km' % (miles, kilometers)

     

    1000.000000 miles is the same as 1609.000000 km

    1.6     Python 类型

    1.6.1            数字

    Python 支持五种基本数字类型,其中有三种是整数类型。

    l   int (有符号整数)

    l   long (长整数)

    l   bool (布尔值)

    l   float (浮点值)

    l   complex (复数)

     

    1.6.2            字符串

    Python 中字符串被定义为引号之间的字符集合。Python 支持使用成对的单引号或双引号,三引号(三个连续的单引号或者双引号)可以用来包含特殊字符。使用索引运算符( [ ] )和切片运算符( [ : ] )可以得到子字符串。字符串有其特有的索引规则:第一个字符的索引是 0,最后一个字符的索引是 1,加号( + )用于字符串连接运算,星号( * )则用于字符串重复。下面是几个例子:

    >>> pystr = 'Python'

    >>> iscool = 'is cool!'

    >>> pystr[0]

    'P'

    >>> pystr[2:5]

    'tho'

    >>> iscool[:2]

    'is'

    >>> iscool[3:]

    'cool!'

    >>> iscool[-1]

    '!'

    >>> pystr + iscool

    'Pythonis cool!'

    >>> pystr + ' ' + iscool

    'Python is cool!'

    >>> pystr * 2

    'PythonPython'

     

    >>> pystr = '''python

    ... is cool'''

    >>> pystr

    'python\nis cool'

    >>> print pystr

    python

    is cool

    1.6.3            列表和元组

    可以将列表和元组当成普通的“数组”,它能保存任意数量任意类型的Python 对象。和数组一样,通过从0 开始的数字索引访问元素,但是列表和元组可以存储不同类型的对象,元组可以看成是只读的列表。通过切片运算( [ ] [ : ] )可以得到子集,这一点与字符串的使用方法一样。

    #创建列表

    >>> alist=['a','c','e','b','d']

    #向列表中添加元素

    >>> alist.append('f')

    >>> print alist

    ['a', 'c', 'e', 'b', 'd', 'f']

    #列表排序

    >>> alist.sort()

    >>> print alist

    ['a', 'b', 'c', 'd', 'e', 'f']

    #删除列表中的元素

    >>> del alist[1]

    >>> print alist

    ['a', 'c', 'd', 'e', 'f']

    #取列表的长度

    >>> len(alist)

    5

    #取列表中元素的索引值

    >>> alist.index('e')

    3

    #合成列表,相当于alist+['g','h']

    >>> alist.extend(['g','h'])

    >>> print alist

    ['a', 'c', 'd', 'e', 'f', 'g', 'h']

     

    #元组样例

    >>> a=('t1', 11, 22, 'try')

    >>> b=(a,'t2',33)

    >>> b

    (('t1', 11, 22, 'try'), 't2', 33)

    >>> b[1]

    't2'

    >>> b[0]

    ('t1', 11, 22, 'try')

    >>> b[0][0]

    't1'

    >>> b[0][1]

    11

     

    #元组输出

    >>> age=28

    >>> name= 'neo'

    >>> print '%s is %d years old' % (name,age)

    neo is 28 years old

    >>> print 'Why is %s playing with that python?' % name

    Why is neo playing with that python?

     

    1.6.4            字典

    字典是Python 中的映射数据类型,工作原理类似Perl 中的关联数组或者哈希表,由键-(key-value)对构成。几乎所有类型的Python 对象都可以用作键,不过一般还是以数字或者字符串最为常用,值可以是任意类型的Python 对象,字典元素用大括号({ })包裹。

    >>> member= { 'Swaroop' : 'swaroopch@byteofpython.info',

    'Larry' : 'larry@wall.org',

    'Matsumoto' : 'matz@ruby-lang.org',

    'Spammer' : 'spammer@hotmail.com'

    }

    #添加

    >>> member['Guido'] = 'guido@python.org'

     

    >>> member

    {'Swaroop': 'swaroopch@byteofpython.info', 'Matsumoto': 'matz@ruby-lang.org', 'Larry': 'larry@wall.org', 'Spammer': 'spammer@hotmail.com', 'Guido': 'guido@python.org'}

    #删除

    >>> del member['Spammer']

     

    >>> member

    {'Swaroop': 'swaroopch@byteofpython.info', 'Matsumoto': 'matz@ruby-lang.org', 'Larry': 'larry@wall.org', 'Guido': 'guido@python.org'}

     

    #显示

    >>> for name, address in member.items():

        print 'Contact %s at %s' % (name, address)

       

    Contact Swaroop at swaroopch@byteofpython.info

    Contact Matsumoto at matz@ruby-lang.org

    Contact Larry at larry@wall.org

    Contact Guido at guido@python.org

    1.6.5            序列

    列表、元组和字符串都是序列,但是序列是什么,它们为什么如此特别呢?序列的两个主要特点是索引操作符和切片操作符。索引操作符让我们可以从序列中抓取一个特定项目,切片操作符让我们能够获取序列的一个切片,即一部分序列。

    >>>shoplist = ['apple', 'mango', 'carrot', 'banana']

     

    #显示第一个

    >>>print 'Item is', shoplist[0]

    Item is apple

     

    #显示倒数第一个

    >>>print 'Item is', shoplist[-1]

    Item is banana

     

    #显示第一个,第三个

    >>>print 'Item is', shoplist[1:3]

    Item is ['mango', 'carrot']

     

    #显示从第二个开始的元素

    >>>print 'Item is', shoplist[2:]

    Item is ['carrot', 'banana']

     

    #显示第一个与倒数第一个

    >>>print 'Item is', shoplist[1:-1]

    Item is ['mango', 'carrot']

     

    #显示全部

    >>>print 'Item is', shoplist[:]

    Item is ['apple', 'mango', 'carrot', 'banana']

     

    2.        控制语句

    2.1     if语句

    语法:

    if expression1:

    if_suite

    elif expression2:

    elif_suite

    else:

    else_suite

    2.2     while语句

    语法:

    while expression:

    while_suite

    2.3     for循环语句

    Python 中的for 循环与传统的for 循环(计数器循环)不太一样, 它更象shell 脚本里的foreach 迭代。Python 中的for 接受可迭代对象(例如序列或迭代器)作为其参数,每次迭代其中一个元素。

    例:

    >>> for item in ['e-mail', 'net-surfing', 'homework','chat']:

       print item

     

    e-mail

    net-surfing

    homework

    chat

     

    3.        文件

    如何打开文件

    handle = open(file_name, access_mode = 'r')

    file_name 变量包含我们希望打开的文件的字符串名字, access_mode 'r' 表示读取,'w' 表示写入, 'a' 表示添加。其它可能用到的标声还有 '+' 表示读写, 'b'表示二进制访问. 如果未提供 access_mode 默认值为 'r'。如果 open() 成功, 一个文件对象句柄会被返回。所有后续的文件操作都必须通过此文件句柄进行。当一个文件对象返回之后, 我们就可以访问它的一些方法。

     

    poem = '''\

    Programming is fun

    When the work is done

    if you wanna make your work also fun:

    use Python!

    '''

    f = file('poem.txt', 'w') # open for 'w'riting

    f.write(poem) # write text to file

    f.close() # close the file

    4.        异常

    要给你的代码添加错误检测及异常处理, 只要将它们封装在 try-except 语句当中。 try之后的代码组, 就是你打算管理的代码。 except 之后的代码组, 则是你处理错误的代码。

    try:

    filename = raw_input('Enter file name: ')

    fobj = open(filename, 'r')

    for eachLine in fobj:

    print eachLine, fobj.close()

    except IOError, e:

    print 'file open error:', e

     

     

     

  • 相关阅读:
    Dubbo-2.7.3升级-依赖问题
    Foreach删除元素(ArrayList)报错分析
    Dubbo日志打印级别调整
    kafka分区和副本如何分配
    IDEA 不能正确反编译 class /* compile ... */
    Mybatis获取插入数据的主键时,返回值总是1
    python 3.7.2 安装 pycurl 遇到的坑
    安装Web模块tornado,启动一直报ModuleNotFoundError: No module named 'tornado.ioloop'; 'tornado' is not a package
    【C#】HTTP POST 上传图片及参数
    【WPF】将DataGrid内容导出到Excel
  • 原文地址:https://www.cnblogs.com/nick4/p/1602527.html
Copyright © 2011-2022 走看看