Functions and combinations of data types

I. Overview of functions

  • Understanding and definition of the function
  • Use and function of the calling process
  • Parameter transfer function
  • Function's return value
  • Local and global variables
  • letter lambda

II. Understanding and function definition

Every day

Code:

def dayUp(df):
    dayup = 1
    for i in range(365):
        if i % 7 in [6, 0]:
            dayup = dayup * (1 - 0.01)
        else:
            dayup = dayup * (1 + df)
    return dayup

dayfactor = 0.01
while dayUp(dayfactor) < 37.78:
    dayfactor += 0.001
print("工作日的努力参数是:{:.3f} ".format(dayfactor))

effect:

2.1 Definition of functions

Function is a piece of code

  • Function is a piece having a specific function, reusable statement group
  • Abstract function is one function, the specific function is generally expressed as a function
  • Two effects: reduce the difficulty of programming and code reuse
def <函数名>(<参数(0个或多个)>) :
    <函数体>
    return <返回值>

y = f(x)

  • When the function definition, the specified parameter is a placeholder
  • After the function definition, if not through the call, will not be executed
  • When the function definition, the parameter is input, processing body is a function, the result is output (IPO)

III. Function calls and use

3.1 function calls

Call function code is run

def fact(n):  # 函数的定义
    s = 1
    for i in range(1,n+1):
        s *= i
    return s
fact(10)  # 函数的调用
  • When call to be given actual parameters
  • Alternatively actual parameters defined in the parameter
  • After the function call to get the return value

3.2 function calls the process

Function can have arguments, or may not, but must retain the brackets

def <函数名>(<非可选参数>,<可选参数>) :
    <函数体>
    return <返回值>
  • Examples of a (general call):

Code:

def get_pi(num):
    import random

    count = 0
    for i in range(num):
        x, y = random.random(), random.random()
        dist = pow((x - 0) ** 2 + (y - 0) ** 2, 0.5)

        if dist < 1:
            count += 1

    print(4 * count / num)

get_pi(10)
get_pi(100)
get_pi(1000)
get_pi(10000)
get_pi(100000)

effect:

  • Examples of bis (return value):

Code:

def add_sum(num):

    count = 0
    for i in range(1, num):
        count += i
    return count

res1= add_sum(101)
print('res1:',res1)
res2 = add_sum(1001)
print('res2:',res2)
res3 = add_sum(10001)
print('res3:',res3)

effect:

IV. Set type

4.1 deduplication

Code:

# 大括号内用逗号隔开多个元素,集合(哈希表)是无序的,去重
s1 = {'nick', 'handsome', 'wuhao', 'dsb', 1231, 1.0, 1.0, 1.0, 'dsb', 'dsb'}
print(s1)

effect:

4.2 be installed for the collection of sequences

s2 = set('nick')
s3 = set(['1', 2, 3])

print(s2)
print(s3)

effect:

4.3 built-in method of collection

Code:

s1 = {'luowenxiang', 'handsome', 'hanye', 'beautiful'}
s2 = {'luowenxiang', 'handsome', 'hanye', 'beautiful','0.0','haha'}
s3 = {'520','1314'}
s1.add('5201314')
s2.remove('0.0')

print(s1)
print(s2)

s2.discard('haha')
print(s2)

s3.clear()
print(s3)

s4 = s1.copy()
print(s4)

effect:

V. sequence

5.1 Types of defined sequence

Sequence is a set of elements has a relationship with a

  • Sequence is the one-dimensional vector elements, it may be different types of elements
  • Similar mathematical sequence of elements: 0,1,2,3,4,5,6,7,8,9
  • Between elements guided by the number, sequence specific elements accessed by subscripts 0, 1, ......

5.2 Sequence handler and method

Code:

name = 'luowenxiang'
       #0123456789...
name2 = name[6:]         #切片  从第七个元素开始输出到最后一个元素
name3 = name[0]          #索引  输出第一个元素
name4 = name2 + name3    #s + t 连接两个序列s和t
name5 = name*5           # sn 或 ns  将序列s复制n次

print('len(name):',len(name))         # 长度
print('l' in name)                    # x in s      如果x是序列s的元素,返回True,否则返回False
print('l' not in name)                # x not in s  如果x是序列s的元素,返回False,否则返回True
print(name2)
print(name3)
print(name4)
print(name5)

effect:

VI. The basic statistic calculation

6.1 Analysis

Basic statistics

  • Requirements: given a set of numbers, they have a summary of understanding
  • how should I do it?

The total number, sum, average, variance, median ...

  • Total number: len ()
  • Sum: for ... in
  • Average: sum / total number
  • Variance: each data and the difference between the average and the average of the square
  • Median: Sort, and then ...
  • Get an intermediate odd, even-averaged to find the middle of two

6.2 examples to explain

A set of data input by the user (a user input), data and calculates the median / average / variance / summation

Code:

# 通过用户输入一组数据(用户一个一个输入),然后计算数据的中位数/平均值/方差/求和
#输入数据
nums = []
while True:
    num1 = input('请输入你需要输入的数字(输入 q 退出):')
    if num1 == 'q':
        break
    nums.append(int(num1))

#定义中位数
def get_median(nums):
    nums.sort()

    nums_len = len(nums)
    if nums_len % 2 == 0:
        print((nums[int(nums_len / 2 - 1)] + nums[int(nums_len / 2)]) / 2)
    else:
        print(nums[nums_len // 2])

median = get_median(nums)                   #输出中间数

#定义求和
def get_sum(nums):  # ['123', '123', '213', '234', '98234']
    count = 0
    for i in nums:
        count += int(i)
    return count
count = get_sum(nums)
print('count:',count)                        #输出求和数据

#定义平均数
def get_average(nums):
    count = get_sum(nums)
    average_count = count/len(nums)
    return average_count
average_count = get_average(nums)

print('average_count:',average_count)           #输出平均数


#定义方差
def get_variance(nums):
    average_count = get_average(nums)

    variance_count = 0
    for i in nums:
        variance_count += pow(i-average_count,2)

    return variance_count

variance_count = get_variance(nums)
print('variance_count:',variance_count)        #输出方差

effect:

VII. Dictionary

Creation and output 7.1 dictionary

Code:

dic1 = {'name':'lwx','lover':'hanye','time':'forever'}      
       #'键'  :'值'                     #创建一个字典
print(dic1)                             #输出字典
print(dic1['name'])                     #输出键:name中的值
print(dic1['lover'])                    #输出键:lover中的值
print(dic1.get('time'))                 #输出键:time中的值

effect:

7.2 Other operations

Code:

dic1 = {'name':'lwx','lover':'hanye','time':'forever'} 
for i in dic1:                #输出键
    print(i)
for i in dic1.values():       #输出值
        print(i)
for i in dic1.items():        #输出键和值
    print(i)

dic1.pop('time')              #删除操作
print(dic1)
dic1.setdefault('long','1314')        #增加数据操作
print(dic1)

effect:

Eight .jieba library

Code:

import jieba
a= jieba.lcut('我今天要好好学python')
print(a)
b = jieba.lcut_for_search('我今天要好好学python')
print(b)

effect:


作者:罗文祥
来源:祥SHAO
原文:https://www.cnblogs.com/LWX-YEER/p/11209387.html
版权声明:本文为博主原创文章,转载请附上博文链接!

Guess you like

Origin www.cnblogs.com/LWX-YEER/p/11209387.html