Getting Started with Python for PHPer-Functions

This is a continuation of the previous Super Basics. This time, I will summarize the differences and points to note about functions.

Function definition

As I explained in Super Basics, it's a review.

First of all, PHP code.

<?php

function func() {
	echo 'hoge';
}

func();

This is the Python code.

# coding=utf8

def func():  #Last: (colon)Don't forget!
	print('hoge')

func()

PHP uses function, but Python uses def. Python does not use {} to represent scopes, but uses indent.

How to pass a value to a function-Part 1

The basics of PHP and Python are not that different. However, Python's functions have something called keyword arguments. Let's take an example.

If you are using PHP, you may come across a function that has a large number of arguments that have a default value. Then, if you want to set only the last argument to a value other than the default value, you have to write as follows.

<?php

function func($hoge='hoge', $piyo='piyo', $foo='foo', $bar='bar') {
	echo $hoge . PHP_EOL;
	echo $piyo . PHP_EOL;
	echo $foo . PHP_EOL;
	echo $bar . PHP_EOL;	
}

//If you want to set the 4th value to something other than the default value, you have to write the 1st to 3rd items as well.
func('hoge', 'piyo', 'foo', 'fizz');

The keyword argument is useful in such cases! Only the specified arguments can be passed by writing in a special way that PHP does not have.

# coding=utf8

def func(hoge='hoge', piyo='piyo', foo='foo', bar='bar'):
    print(hoge)
    print(piyo)
    print(foo)
    print(bar)

#You can pass only the specified place!
func(bar='fizz')

Variadic argument

Normal variadic arguments

When implementing a function with variable length arguments, PHP looks like this:

<?php

function func() {
	$args = func_get_args();
	var_dump($args);
}

func('hoge');
func('hoge', 'piyo');

Expressing this in Python looks like this!

# coding=utf8

def func(*args):
	print(args)

func('hoge')
func('hoge', 'piyo')

Just add * to the beginning of the argument name. The argument name ʻargs is not fixed and can be any name. The ʻargs variable can be treated as a immutable array (tuple). It's very simple.

Handle keyword arguments with variable length

You can also receive the keyword argument that came out earlier with a variable length.

# coding=utf8

def func(**kwargs):
	print(kwargs)

func(hoge='hoge')
func(hoge='hoge', piyo='piyo')

For the keyword argument, just add**to the beginning of the argument name. In this case, it can be treated as a dictionary of pairs of argument names and values instead of tuple.

Handle both ordinary arguments and keyword arguments with variable length

You can even use them together!

# coding=utf8

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

func('hoge')
func('hoge', piyo='piyo')

How to pass a value to a function-Part 2

You can use lists (tuples) and dictionaries when passing values to functions.

Pass arguments as a list

# coding=utf8

def func(hoge, piyo):
	print(hoge)
	print(piyo)

args = ['foo', 'bar']

#The order of the arguments corresponds to the order of the list.
func(*args)

It's similar to the case of variable length arguments. By adding * to the name of the variable in which the list is stored and passing it to the function, you can handle the list element as an argument.

Pass arguments in a dictionary

# coding=utf8

def func(hoge, piyo):
	print(hoge)
	print(piyo)

kwargs = {
	'hoge': 'foo',
	'piyo': 'bar',
}

func(**kwargs)

Similar to the list method, if you add**to the name of the variable that stores the dictionary and pass it to the function, the value will be assigned to the argument corresponding to the key (subscript). To go. However, please note that if you write an argument name that does not exist in the key (subscript), an error will occur. ..

Do not specify a list / dictionary as the default value of the argument

I will introduce the part that I was a little addicted to. First look at the PHP code.

<?php

function func($hoge=array('foo')) {
	#in hoge array'bar'Added the element.
	$hoge[] = 'bar';
	var_dump($hoge);
}

func();
func();

The function that adds 'bar' to$ hoge = array ('foo')and outputs it is called twice. I think that the execution result of each function will be the same. When this is written in Python, it looks like the following.

# coding=utf8

def func(hoge=['foo']):
	#on the hoge list'bar'Added the element.
	hoge.append('bar')
	print(hoge)

func()
func()

In fact, this Python code ** doesn't work as expected! !! !! !! !! ** ** Those who actually executed and compared them should have confirmed that the execution results are different. I'll leave the detailed explanation to others, but here ** Do not use a list / dictionary as the default value of the argument! Please remember **.

Summary

Python functions are very flexible. Especially the keyword argument is powerful, so please remember it. Next, Explanation of classes!

Recommended Posts

Getting Started with Python for PHPer-Functions
Getting Started with Python for PHPer-Classes
1.1 Getting Started with Python
Getting Started with Python
Getting Started with Python
Getting Started with Python for PHPer-Super Basics
Getting Started with Python Functions
Getting Started with Python Django (1)
Getting Started with Python Django (4)
Getting Started with Python Django (3)
Getting Started with Python Django (6)
Python3 | Getting Started with numpy
Getting Started with Python Django (5)
[Translation] Getting Started with Rust for Python Programmers
Settings for getting started with MongoDB in python
Getting Started with Julia for Pythonista
Getting Started with Python Basics of Python
Getting Started with Google App Engine for Python & PHP
Getting Started with Python Genetic Algorithms
Getting started with Python 3.8 on Windows
Getting Started with Python Web Scraping Practice
Getting Started with Python Web Scraping Practice
Getting started with Dynamo from Python boto
Getting Started with Lisp for Pythonista: Supplement
Django 1.11 started with Python3.6
Getting started with Android!
Getting Started with Golang 2
Getting started with apache2
Getting Started with Golang 1
Getting Started with Django 1
Getting Started with Optimization
Getting Started with Golang 3
Getting Started with Numpy
Getting started with Spark
Getting Started with Golang 4
Getting Started with Jython
Getting Started with Django 2
Building a Windows 7 environment for getting started with machine learning with Python
Getting started with Python with 100 knocks on language processing
Getting started with AWS IoT easily in Python
Materials to read when getting started with Python
Translate Getting Started With TensorFlow
Getting Started with Tkinter 2: Buttons
Getting Started with Go Assembly
Getting Started with PKI with Golang ―― 4
Get started with Python! ~ ② Grammar ~
Get started with Python! ~ ① Environment construction ~
Link to get started with python
Getting Started with Git (1) History Storage
Getting started with Sphinx. Generate docstring with Sphinx
How to get started with Python
Getting Started with Mathematics Starting with Python Programming Challenges Personal Notes-Problem 1-1
Getting Started with Cisco Spark REST-API
started python
Getting started with USD on Windows
Get started with Python in Blender
Getting Started with CPU Steal Time
Getting Started with Heroku-Viewing Hello World in Python Django with Raspberry PI 3
[FastAPI] Getting started with FastAPI, an ASGI web framework made by Python
Easy keyword extraction with TermExtract for Python
INSERT into MySQL with Python [For beginners]