Python Lesson 1 :About list for if and function

简介: python 关于list、for、if、和function的语法

1.1 安装Python3

在Mac或Linux系统使用命令 python3 -V(Uppercase "v"by the way )。如果已经安装,则显示版本,否则提示命令不存在,访问官方网址安装 www.python.org ;If Python 3 is missing from your computer, download a copy for your favorite OS from the website.

安装Python 3时会自动安装IDLE(集成开发环境Integrated development environment)

2.1 Create simple python lists

python 定义list,直接使用数组的方式 语法如下:


ls=['a',65,'b',66,['c',['d',68,'it's ok']]] 

list可以嵌套list,最大限度不能超过1000.

print(ls4[2]) 命令将输出 it's ok ;4 2 1 形同数组偏移量(offset)

2.1.1 it's time to iterate

for命令循环list元素,语法如下:


for target identifer in list :
    processing code 

循环输入ls变量的内容:

for list_item in ls :
    print(list_item)

则输出结果为:a 65 b 66 ['c',['d',68,'it's ok]],其中最后一部分作为整体输出。

2.1.2 if语法

if语法如下:

if some condition holds :
    the "true" suite
elif some other holds:
    the "true" suite
else :
    the "false" suite

如果需要将list中的list元素输出,可以使用if语句

for list_item in ls :
    if isinstance(list_item,list) :
        for nested_item in list_item :
            print(nested_item)
    else :
        print(list_item)

2.1.3 def定义函数

定义函数语法如下:

def function name (arguments) :
    function code suite

对于ls变量,包含两层list,如果要将list中的每层list元素单独输出,则需要在2.1.2的循环判断基础上在加一层循环判断,则代码混乱且不易读,可以将list循环输出定义为方法,然后递归调用即可,实现代码如下:


def recursion_ls(list_param) :
    for list_item in list_param :
        if isinstance(list_item,list) :
            recursion_ls(list_item)
        else :
            ''' 这里可以添加
            多行注释 '''
             
            print(list_item)
            
recursion_ls(ls) 

function is a module in python;python 提供了一个中央库(简称PyPI)用于管理第三方的模块,和 perl语言的CPAN一样。

The Python Package Index (or PyPI for short) provides a centralized repository for third-party Python modules on the Internet. When you are ready, you’ll use PyPI to publish your module and make your code available for use by others. And your module is ready, but for one important addition.
给module添加注释(''' 注释内容 '''):

使用''' This is the standard way to include a multiple-line comment in your code. '''给module添加注释

目录
相关文章
|
1月前
|
Python
python中if语句(二)
python中if语句(二)
19 0
|
1月前
|
Python
python中if语句(一)
python中if语句(一)
17 0
|
1月前
|
Python
Python中 If语句条件测试
Python中 If语句条件测试
20 1
|
1月前
|
Python
python中if __name__ == '__main__'
python中if __name__ == '__main__'
17 3
|
3天前
|
索引 容器
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
|
12天前
|
索引 Python
Python标准数据类型-List(列表)
Python标准数据类型-List(列表)
41 1
|
1月前
|
Python
python中if语句(三)
python中if语句(三)
11 0
|
1月前
|
存储 安全 Java
Python教程第3章 | 集合(List列表、Tuple元组、Dict字典、Set)
Python 列表、无序列表、字典、元组增删改查基本用法和注意事项
50 1
|
1月前
|
存储 数据可视化 索引
Python中List列表的妙用
Python中List列表的妙用
18 0
|
1月前
|
Python
Python中如何使用if语句处理列表
Python中如何使用if语句处理列表
20 1