Python study notes --Day03

Python study notes --Day03

A few days ago because of a little thing delayed some time, today is the third day, the start of the exercise of the function.

Python functions

Function is a collection of reusable code that can perform certain functions, and help us write a function to write code more concise, beautiful. In fact, when we open the python world we have been exposed to a function --print function. We can define your own functions, called user-defined functions.

The definition of a function

Simple rules defined functions (taken from the rookie tutorial):

  • Function block def keyword beginning, followed by the name and function identifier parentheses ().
  • Any incoming parameters and arguments must be placed in the middle of parentheses. Between parentheses may be used to define the parameters.
  • The first statement function can be selectively used documentation string - for storing function instructions.
  • Start function contents colon, and indentation.
  • return [Expression] End function, selectively returns a value to the caller. return without an expression equivalent to return None.

Defined function syntax

def function_name(parameters):
	"""函数说明"""
	function_suite
	return [expression]

Examples

Defined function of a factorial

def factorial(num):
	"""
	求阶乘
	:param num:非负整数
	:return: num的阶乘
	"""
	result = 1
	for n in range(1, num +1):
		result *= n
	return result

Function parameters may be set to a default value, such as addition of a function defined below is calculated

def add(num1=1, num2=1):
	"""计算加法,如果不输入函数值,就会返回2"""
	return num1 + num2

As well as the number of uncertain parameters of time, we need to use variable parameters

def add(*args):
	total = 0
	for val in args:
		total += val
	return total

We can define a function with no parameters

def hello():
	print("hello, world!")

An anonymous function using lambda (taken from the rookie tutorial)

  • Just a lambda expression, function body is much simpler than def.
  • Lambda expression is a body, instead of a code block. We can only package a limited logic into the lambda expression.
  • lambda function has its own namespace, and can not be accessed outside of its own argument list or the global namespace parameters.
  • Although lambda function looks can only write a single line, but not equivalent to C or C ++ inline functions, which aims not take up the stack memory when calling small functions to increase operating efficiency.
    grammar
lambda [arg1 [,arg2,.....argn]]:expression

For example, the above we added two functions can be defined

    sum = lambda num1, num2: num1 + num2

When the call can be used in such a waysum(1, 2)

Module

My understanding is like module is a collection of methods, such as the module which I define several methods, respectively, are used to do, in other modules, we can import this module method by import, and different modules the method can not afford conflict, only when referring to the method named on it does not conflict
module1.py

def hello():
	print("hello, world!")

module2.py

def hello():
	print("hello, python!)

test.py

import module1 as m1
import module2 as m2
m1.hello()
m2.hello()

This is the case not afford conflict, the time when the conflict is introduced

from module1 import hello
form module2 import hello

hello()

This time we call a method module2, not module1 method, because it will be the second time references hello first reference overwritten.

I still remember how the modules are written in Well

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:


def main():
    pass


if __name__ == "__main__":
    main()

General framework is that, if we define the module can also be directly run the code, it will execute the code when you import the module, we may not want the code to be executed, so we need above this format, only run the module directly when, if the following methods will be implemented, that code to be executed in this module can be written in the main function.

String

The string that's quite a lot, and the method is special, so-called string is a finite sequence of zero or more characters. Here's a look at the basic use of the string

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:


def main():
    str1 = "hello, world!"
    # len函数计算长度
    print("%s的长度为:%d" % (str1, len(str1)))
    # 获得字符串首字母大写的拷贝
    print(str1.capitalize())
    # 获得字符串全部大写的拷贝
    print(str1.upper())
    # 从字符串中查找子串所在位置
    print(str1.find('orl'))
    print(str1.find('els'))
    # 返回子串的索引,若查找不到会有异常
    print(str1.index('or'))
    # print(str1.index('shit')) 异常
    # 检查字符串是否以指定的字符串开头
    print(str1.startswith('hell'))
    print(str1.startswith('sas'))
    # 检查字符串是否以指定的字符串结尾
    print(str1.endswith('!'))
    print(str1.endswith('123'))
    # 将字符串以指定的宽度居中并在两侧填充指定的字符
    print(str1.center(50, '*'))
    # 将字符串以指定的宽度靠右放置左侧填充指定的字符
    print(str1.rjust(50, ' '))
    str2 = 'abcd1234'
    # 获取指定位置的字符
    print(str2[2])
    # 字符串切片(从指定的开始索引到指定的结束索引)
    print(str2[2:6])
    print(str2[2:])
    print(str2[2::2])
    print(str2[::2])
    print(str2[::-1])
    print(str2[-3:-1])
    # 检查字符串是否由数字构成
    print(str2.isdigit())
    # 检查字符串是否以字母构成
    print(str2.isalpha())
    # 检查字符串是否以数字和字母构成
    print(str2.isalnum())
    # 修剪字符串两边的空格
    str3 = "    sdf    "
    print(str3.strip())


if __name__ == "__main__":
    main()

List

Code demonstrates much to say

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:


def main():
    list1 = [1, 2, 3, 4, 123]
    print(list1)
    list2 = ['hello'] * 5
    print(list2)
    # 计算列表长度(元素个数)
    print("list1的长度为:", len(list1))
    # 下标(索引)运算
    print(list1[0])
    print(list1[3])
    print(list1[-1])
    print(list1[-4])
    # 修改
    list1[2] = 123123
    print(list1)
    # 添加元素
    list1.append('11111')
    list1.insert(0, 8888)
    list1 += [400, 500]
    print(list1)
    # 删除元素
    list1.remove(2)
    del list1[0]
    print(list1)
    # 清空列表元素
    list1.clear()
    print(list1)


if __name__ == "__main__":
    main()

The above is the basic operation, followed by the presentation list slicing operations.

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:


def main():
    nums = [1, 2, 3, 4, 5, 6, 7]
    for num in nums:
        print(num, end=" ")
    print()
    # 列表切片
    nums1 = nums[2:5]
    print(nums1)
    # 通过切片进行复制列表
    nums2 = nums[:]
    print(nums2)
    nums3 = nums[-1:-3]
    print(nums3)
    # 反向切片进行列表倒转
    nums4 = nums[::-1]
    print(nums4)


if __name__ == "__main__":
    main()

List sorted

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:列表排序


def main():
    list1 = ['orange', 'apple', 'zoo', 'zebra', 'egg']
    list2 = sorted(list1)
    print(list2)
    # 倒置
    list2 = sorted(list1, reverse=True)
    print(list2)
    # 通过key关键字根据指定字符串长度进行排序而不是默认的字母表顺序
    list2 = sorted(list1, key = len)
    print(list2)
    # 对列表直接进行排序
    list1.sort()
    print(list1)


if __name__ == "__main__":
    main()

According to generative grammar to create a list of lists, as follows

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:列表的生成式语法创建列表

import sys

def main():
    list1 = [x for x in range(1, 15)]
    print(list1)
    list2 = [x + y for x in 'abcd' for y in '1234']
    print(list2)
    # 用列表的生成表达式语法创建列表容器
    # 用这种语法创建列表之后元素已经准备就绪所以需要耗费较多的内存空间
    f = [x ** 2 for x in range(1, 1000)]
    print(sys.getsizeof(f))  # 查看对象占用内存的字节数
    print(f)
    # 请注意下面的代码创建的不是一个列表而是一个生成器对象
    # 通过生成器可以获取到数据但它不占用额外的空间存储数据
    # 每次需要数据的时候就通过内部的运算得到数据(需要花费额外的时间)
    f = (x ** 2 for x in range(1, 1000))
    print(sys.getsizeof(f))  # 相比生成式生成器不占用存储数据的空间
    print(f)
    for val in f:
        print(val)


if __name__ == "__main__":
    main()

Tuple

Similar lists and tuples, except that the elements of the tuple can not be modified.

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:元组


def main():
    # 定义元组
    t = (1, 'abc', 1.2, [1, 2, 'a'])
    # 根据索引获取
    print(t[1])
    # 遍历元组中的值
    for item in t:
        print(item)
    # 元组转换列表
    list1 = list(t)
    print(list1)
    # 列表转换元组
    list1[1] = "哈哈"
    t = tuple(list1)
    print(t)


if __name__ == "__main__":
    main()

set

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:集合操作


def main():
    set1 = {1, 2, 3, 3, 2, 23, 12}
    print(set1)
    # len获取长度
    print('集合的长度是:', len(set1))
    # 列表转换集合
    list1 = [1, 2, 3, 4, 23, 1]
    set2 = set(list1)
    print(set2)
    # 元组转换集合
    tuple1 = (1, 2, 3, 12, 34)
    set2 = set(tuple1)
    print(set2)
    # 集合添加元素
    set2.add(123)
    set2.update([1, 1123])
    print(set2)
    # 集合删除元素
    set2.remove(123)
    set2.discard("abf")
    print(set2)
    # 遍历集合
    for item in set2:
        print(item)
    # 集合交集、并集、差集、对称差运算
    set3 = {1, }
    print(set1 & set2)
    # print(set1.intersection(set2))
    print(set1 | set2)
    # print(set1.union(set2))
    print(set1 - set2)
    # print(set1.difference(set2))
    print(set1 ^ set2)
    # print(set1.symmetric_difference(set2))
    # 判断子集和超集
    print(set2 <= set1)
    # print(set2.issubset(set1))
    print(set3 <= set1)
    # print(set3.issubset(set1))
    print(set1 >= set2)
    # print(set1.issuperset(set2))
    print(set1 >= set3)
    # print(set1.issuperset(set3))


if __name__ == "__main__":
    main()

dictionary

#!usr/bin/python
# -*- coding: utf-8 -*-
# author: 李爽
# description:字典


def main():
    dict1 = {'a': 1, 'b': 2, 'c': 3}
    print(dict1['a'])
    for elem in dict1:
        print(elem, dict1[elem])
    # 修改
    dict1['c'] = 'asdf'
    print(dict1)
    # 添加
    dict1['d'] = "ads"
    print(dict1)
    # 获取
    print(dict1["a"])
    print(dict1.get('a', 111))
    # 删除
    print(dict1.popitem())
    print(dict1.popitem())
    print(dict1.pop('a', 111))
    print(dict1)
    # 清空
    dict1.clear()
    print(dict1)


if __name__ == "__main__":
    main()

Epilogue

Because delayed a few days, so today regarded as the third day of school, lists, dictionaries, sets, tuples, strings, these types of data types is used to remember ah!

If you find my articles where there is an error or have any good ideas can contact me, we study together progress together, my email address is [email protected]

let’s do more of those!

Published 26 original articles · won praise 2 · Views 2346

Guess you like

Origin blog.csdn.net/qq_42909545/article/details/93595111