美文网首页生活不易 我用python
Python Day17 list及tuple复习

Python Day17 list及tuple复习

作者: 读书的番茄 | 来源:发表于2017-04-28 16:33 被阅读0次

    之前学习while一直有纠结的地方,先整理下,还是以fishc的练习题为例。


    python004.jpg
    temp = input('Please enter an integer:') #请用户输入整数
    temp1 = int(temp)                                  #对用户输入的字符进行整数赋值
    while temp1:                                          #根据客户输入的整数进行倒序循环
        space = temp1                                  #设置空格变量,并赋值
        while space:                                      #空格循环
            print(' ', end='')                              #空格输出后不换行
            space -= 1                                    #每循环1次,空格数-1
        start = temp1                                    #设置星星变量,并赋值
        while start:                                        #星星循环
            print('*', end='')                             #星星输出后不换行
            start -= 1                                      #每循环1次,星星数-1
        temp1 -= 1                                      #客户输入的整数循环每循环1次数值-1
        print()                                              #循环一次后换行
    

    结果示例

    image.png

    1、list

    如果访问list时,索引值超出范围会提示错误,且list的索引值起始值是‘0’

    >>> pc = ['显示器', '鼠标', '键盘', '机箱', '电源']
    >>> len(pc)
    5
    >>> pc[0]
    '显示器'
    >>> pc[6]
    Traceback (most recent call last):
      File "<pyshell#14>", line 1, in <module>
        pc[6]
    IndexError: list index out of range
    

    所以最后一个元素的索引值肯定是len() - 1


    2、tuple

    定义tuple时,我个人认为2个重点:‘()’和‘,’

    >>> pc = (1)
    >>> pc1 = (1,)
    >>> pc
    1
    >>> pc1
    (1,)
    >>> type(pc)
    <class 'int'>
    >>> type(pc1)
    <class 'tuple'>
    

    可以看到,变量pc实际上是整数,而变量pc1才是tuple。tuple再显示时哪怕只有1个元素也会显示成"(1,)"

    相关文章

      网友评论

        本文标题:Python Day17 list及tuple复习

        本文链接:https://www.haomeiwen.com/subject/dpwozttx.html