Python basic course (12 functions)

What is a function

According to the IT terminology dictionary, "function" is There is a "series of instructions that receives data called arguments, executes the specified processing and returns the result". A program is a collection of functions because the program itself processes the data and returns the results. If you write each time you use a program that does the same thing without using a function, the program becomes redundant. Also, if correction is necessary, all parts must be corrected. If you make it a function, you can shorten the amount of code in the program, and you can modify it by modifying only one function, so it does not take time. It is also indispensable when creating the "module" described later.

Function definition

Create a simple function. This is a program that uses a function that determines whether the year given as an argument is a leap year. A function that stores a favorite number in year on the 9th line (currently stores 2015) and determines a leap year Let's check that leap_year () works properly.

leap_year.py


def leap_year(year):
    if year % 400 == 0 or (year % 100 != 0 and year % 4 == 0) :
        leap = True
    else:
        leap = False

    return leap

year = 2015
print("{0} = {1}".format(year,leap_year(year)))

The function is defined in the following form.

** def ** * Function name * ** (** * Arguments * **): ** processing ** return ** * Return value *

By not writing a return statement, you can also define a function that has no return value.

leap_year2.py


def leap_year(year):
    if year % 400 == 0 or (year % 100 != 0 and year % 4 == 0) :
        print("{0} is leap year".format(year))
    else:
        print("{0} is not leap year".format(year))


year = 2015
leap_year(year)

argument

If you omit the normal function argument, an exception is thrown.

argment_ERRROR.py


def plus_4(arg1,arg2,arg3,arg4):
    return arg1+arg2+arg3+arg4

print("no arg:{0}".format(plus_4()))

TypeError: plus_4() takes exactly 4 arguments (0 given)

However, when the function is defined, * argument * ** = ** * default value * is written so that the argument is omitted. You can set the default value.

argment_ERRROR.py


def plus_4(arg1=2000,arg2=0,arg3=10,arg4=5):
    return arg1+arg2+arg3+arg4

print("no arg:{0}".format(plus_4()))

The following result is output. It's convenient. no arg:2015

Variadic argument

You can create a function that does not determine the number of arguments in advance.

argments.py


def spam(*args):
	print("{0}".format(args))

spam("arg1",2,3.4)

The output result is ('arg1', 2, 3.4) It will be. You can pass a value to the argument as a tuple by defining ** \ * variable name ** in the argument.

argments2.py


def spam(**args):
	print("{0}".format(args))

spam(taro=165,jiro=180,saburo=170)

Another way to define variadic arguments is to define the arguments as ** \ * \ * variable name **. You can pass a value as an argument as a dictionary.

global variable

A global variable is a variable that can be referenced from anywhere. By declaring it outside the function, it can be used inside or outside the function. Conversely, local variables, which are variables declared inside a function, cannot be used outside the function.

global_explain.py


var1 = "global"
def hoge(str):
    var2 = "local"
    return var1 + str + var2

print("{0}".format(hoge("-")))
print("{0}".format(var2))
#print("{0}".format(var1))

The above program will throw a run-time exception. You should see something like this:

global-local Traceback (most recent call last): print("{0}".format(var2)) NameError: name 'var2' is not defined

Since the variable var2 is a variable declared in the function hoge, it cannot be used from the outside. The variable var1 declared outside the function can be used inside and outside the function. Of the program Comment out "print (" {0} ".format (var2))" and Instead, uncomment "print (" {0} ".format (var1))" and run the program again. This time the exception does not occur.

Next, I will show you how to change the global variable in the function.

change_global_NG.py


var1 = "global"

def spam():

	var1 = "change global"
	var2 = "local"
	print(var1,var2)

spam()
print("var1 : {0}".format(var1))

ange global local var1 : change global

I expect it to be displayed, but in reality

ange global local var1 : global

It will be displayed. Why couldn't I change the global variable inside the function? Even if you store a value in a variable with the same name as a global variable in a function, it will be interpreted as a local variable with the same name. If you want to change a global variable in a function, specify that the variable is global as shown below and then change it.

change_global.py


def spam():
    global var1
    var1 = "change global"
    var2 = "local"
    print("{0}".format(var1+" "+var2))

spam()
print("var1 : {0}".format(var1))

change global local var1 : change global

The expected result was output.

Next: Python Basic Course (13 classes)

Recommended Posts

Python basic course (12 functions)
Python Basic Course (7 Dictionary)
Python basic course (2 Python installation)
Python basic course (9 iterations)
Python Basic Course (11 exceptions)
Python basic course (6 sets)
Python Basic Course (Introduction)
Python basic course (13 classes)
Python basic course (8 branches)
Python Basic Course (3 Python Execution)
Python basic course (10 inclusion notation)
Python functions
Python Basic Course (5 List Tuples)
Python Basic Course (1 What is Python)
Python Basic Course (14 Modules and Packages)
RF Python Basic_01
Basic Python writing
#Python basics (functions)
[Beginner] Python functions
Python3 basic grammar
RF Python Basic_02
Python Easy-to-use functions
Python basics: functions
Python Basic Course (at the end of 15)
Python basic course (4 numeric type / character string type)
Python Beginner's Guide (Functions)
Python I'm also basic
Python basic grammar / algorithm
Basic sorting in Python
[python] class basic methods
[Python] Memo about functions
Python3 cheat sheet (basic)
Python basic grammar (miscellaneous)
Python basic memorandum part 2
python basic on windows ②
Python basic memo --Part 2
Basic Python command memo
# 4 [python] Basics of functions
Python basic grammar note (4)
Python basic grammar note (3)
Basic knowledge of Python
Python built-in functions ~ Zip ~
Python basic grammar memo
Wrap Python built-in functions
OpenCV basic code (python)
Python basic memo --Part 1
python memorandum super basic
Python basic if statement
Python Basic --Pandas, Numpy-
Python basics basic course CSV processing (functions and classes, part 1 CSV is read and written)
Curry arbitrary functions with Python ....
Python> lambda> tiny functions / callback functions
Basic Python 3 grammar (some Python iterations)
Getting Started with Python Functions
Python application: Pandas Part 1: Basic
Python3 programming functions personal summary
Refactoring Learned in Python (Basic)
BASIC authentication with Python bottle
Python basic dict sort order
[Python] Using OpenCV with Python (Basic)
Python installation and basic grammar