Python_C3_变量【上】

来源:互联网 发布:网络教育学历有用吗 编辑:程序博客网 时间:2024/05/24 15:40

3.1  引用数据

  python中变量也叫做名称(name)

  给名称赋值

 >>> first_string="This is a string"
>>> second_string="This is another string"
>>> first_number=4
>>> second_number=5
>>> print("The first variables are %s,%s,%d,%d"%(first_string,second_string,first_number,second_number))
The first variables are This is a string,This is another string,4,5

#·当名称与其存储的值相关联时,就创建了一个非正式的索引。
    3.1.1 使用名称修改数据

 >>> pennies_saved=0

>>> pennies_saved=pennies_saved+1
>>> print(pennies_saved)
1
>>> print(pennies_saved+1)
2

   3.1.2 复制数据

 >>> pennies_saved=1
>>> pennies_earned=pennies_saved
>>> print(pennies_earned)
1

3.2更多的内置类型

  元组、列表、集合、字典

   3.2.1 元组——不可更改的数据列表,用小括号'( )',从0开始引用元素

          创建 元组

                  >>> filler=("string","filed","by a","tumple")
                  >>> print(filler)
                  ('string', 'filed', 'by a', 'tumple'
)

         访问元组中的单个值

                      >>> print("第一个值是%s"% filler[0])
                       第一个值是string  

          元组长度

                      >>> print("filler的长度%d"% len(filler))
                       filler的长度4

           元组的嵌套

                     >>> newfiller=(filler,"newfiller's second element")
                     >>> print(newfiller)
                   (('string', 'filed', 'by a', 'tumple'), "newfiller's second element")

                     >>> print(newfiller[1])
                      newfiller's second element
                     >>> print(newfiller[0][0])
                        string

           不可更改

                    >>> newfiller[1]=3
                    Traceback (most recent call last):
                     File "<pyshell#33>", line 1, in <module>
                       newfiller[1]=3
                    TypeError: 'tuple' object does not support item assignment


        说明:在创建只有一个元素的元组时,要在该元素后边加上一个逗号,否则将会创建一个字符串

                   >>> test=("abc",)
                   >>> print(test[0])
                    abc
                   >>> test0=("efg")
                   >>> print(test0[0])
                    e

    3.2.2  列表——可以更改的数据序列,用方括号'[ ]' ,从0开始引用元素

          >>> breakfast=["coffee","tea","toast","egg"]
          >>> count=0
          >>> print("%s"% breakfast[count])
           coffee

             可修改

           >>> breakfast[0]="meat"
           >>> print(breakfast[count])
           meat

             利用append()方法向列表末端添加一个元素

          >>> breakfast.append("waffles")
          >>> print(breakfast)
         ['meat', 'tea', 'toast', 'egg', 'waffles']

            利用extend()方法向列表末端添加>=1个元素

          >>> breakfast.extend(["juice","decaf"])
          >>> print(breakfast)
          ['meat', 'tea', 'toast', 'egg', 'waffles', 'juice', 'decaf']


0 0
原创粉丝点击