Python parameter types and functions implemented isOdd, isNum function, multi function, isPrime function

Python parameter type and implemented isOdd function, scanned using the ISNUM function, Multi function, the isPrime function

 

A, Python Parameter Type

Parameter: the parameter variables defined function.

Arguments: variable parameter used when calling the function.

 

Process parameters passed, is to pass a reference to the argument of the parameter, the process is performed using the value of the function body argument.

In Python , the argument of function / return values are to be passed by reference.

In the function call, typically pass parameters, different parameters of different data processing. Generally have common parameters, default parameters, variable position parameters, variable keyword parameters.

 

1. Common parameters : location according to the parameter, the parameter passed in turn.

def add(x,y):
    return x + y

print(add(3,4))

 

 

2. The default parameters : when you define a function, you can assign a default value for a parameter.

When you call the function, if the value of the default parameter is not passed, the default parameter values ​​within the function.

The most common value to use as the default value, simplifying the calling function.

If a value of the parameter can not be determined, it should not set the default values, specific values ​​transmitted from the outside when calling the function. When calling the function, if there is more than one default parameters, you need to specify the parameter name, so the interpreter to be able to know the relationship between parameters.

 

def add(x,y=1):
    return x+y

print(add(2))
print(add(2,3))

 

When a parameter has a default value, when you call if you do not pass this parameter, you will use the default value.

Note: With the default value of the parameter must be preceded with no default value of the parameter , otherwise it will error.

 

 

3. The variable position parameters :

When defining parameters before the parameter plus a * indicates that the parameter is variable, you can accept any number of parameters that constitute a tuple, only by the position parameter passing. Examples are as follows:

 

Maximum, minimum, the number of parameters to find a set of numbers:

DEF max (* A): 
    m = n-= A [0]
     for X in A:
         IF X> = m: 
            m = X
         the else : 
            n- = X
     return m, n-, len (A) 

B = INPUT ( ' enter several numbers, separated by spaces: ' ) .split ()
 Print (max (B *))

 

operation result:

 

 

About the last line: Print (max (* b)) , * b role is unpacked, otherwise transfer is the entire list .

If not * , the output results are as follows:

 

 

 

4. Variable keyword arguments :

When defining parameters, preceded by ** , this parameter represents a variable can accept any number of parameters that constitute a dictionary, can only pass through the keyword parameter .

 

Mix parameters used:

#位置参数可以和关键字参数一起使用。
#当位置可变参数和关键字可变参数一起使用的时候,可变位置参数必须在前。

def fn(*args,**kwargs):
    print(args)
    print(kwargs)

fn(1,2,3,x=4,y=5)

 

 

#普通参数可以和可变参数一起使用,但是传参的时候必须匹配 

def fn(x,y,*args,**kwargs):
    print(x)
    print(y)
    print(args)
    print(kwargs)

fn(1,2,3,4,5,a=6,b=7)

 

 

#关键字可变参数不允许在普通参数之前
#下面的方式定义会出错

def fn(**kwargs,x):
    print(x)

fn(a=1,2)

 

 

#默认参数可以在可变位置参数之前

def fn(x=5,*args):

    print(x)

fn()

 

 

参数解构(拆包)

参数解构发生在函数调用的时候,可变参数发生在函数定义的时候。

 

解构有两种形式:

1.解构符号:*,解构的对象:可迭代对象。解构后的结果:位置参数。

2.解构符号:**,解构的对象:字典。解构的结果:关键字参数。

 

关键字参数解构,key必须是str类型

def add(a,b):
    return a+b

data = [4,3]
print(add(*data))#位置参数解构
data1 = {'a':3,'b':4}
print(add(**data1))#关键字参数解构

 

 

 

 

 二、程序练习题

 

5.2 实现 isOdd()函数,参数为整数,如果整数为奇数,返回True,否则返回False

 

实现代码如下:

def isOdd(num):

    if num%2!=0:

        return True

    else:

        return False


s=eval(input("请输入一个整数:"))

print(isOdd(s))        

 

运行结果:

 

 

 

 

 

5.3 实现 isNum()函数,参数为一个字符串,如果这个字符串属于整数、浮点数或复数的表示,则返回True,否则返回False

 

实现代码如下:

def isNum(num):

    try:        

        n=type(eval(num))

        if n==type(1):#输入为整型

            return True

        elif n==type(1.0):#输入为浮点型

            return True

        elif n==type(1+1j):#输入为复数

            return True       

    except:

        return False


n=input("请输入一个字符串:")

print(isNum(n))

 

运行结果:

 

 

 

 

 

 

 

 

 

5.4 实现 multi()函数,参数个数不限,返回所有参数的乘积。

 

实现代码如下:

def multi(s):

    m = 1

    for i in s:

        m *= int(i)

    return m


n=input("请输入若干整数:").split()

print(multi(n))

 

运行结果:

 

 

 

5.5 实现 isPrime()函数,参数为整数,要有异常处理。如果整数是质数,返回True,否则返回False

 

实现代码如下:

def isPrime(num):   

    try:

        num = eval(num)

        if type(num) == type(1):#判断输入是否为整型

            if num<=1:#判断一个数字是否是质数:质数是一个只能被自己和1整除的大于1的正整数。注意1不是质数。

                return False

            elif num==2:#2是质数,这里单独作为一个条件是为了与下面的判断条件区分

                return True

            else:

                for i in range(2,num):#这里考虑的是大于2的正整数num,将这个数依次除以从2到num-1的整数进行取模运算,只要有一个数使它余数为0就说明它不是质数

                    if num % i == 0:

                        return False

                    else:

                        return True                     

        else:
    
            raise ValueError#引发ValueError异常

    except ValueError:#传入参数异常处理

        return "输入有误!请输入整数!"#这里没有使用print语句,如果没有给定return一个返回值,则函数的返回值为None

    except:#其他异常处理

        return "输入有误!请输入整数!"


n = input("请输入一个整数:")

print(isPrime(n))        

 

运行结果:

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/BIXIABUMO/p/11667801.html