Cara menggunakan python call nested function

Dalam bahasa pemrograman Python, struktur data yang paling dasar adalah urutan atau lists. Setiap elemen-elemen berurutan akan diberi nomor posisi atau indeksnya. Indeks pertama dalam list adalah nol, indeks kedua adalah satu dan seterusnya.

Python memiliki enam jenis urutan built-in, namun yang paling umum adalah list dan tuple. Ada beberapa hal yang dapat Anda lakukan dengan semua jenis list. Operasi ini meliputi pengindeksan, pengiris, penambahan, perbanyak, dan pengecekan keanggotaan. Selain itu, Python memiliki fungsi built-in untuk menemukan panjang list dan untuk menemukan elemen terbesar dan terkecilnya.

Membuat List Python

List adalah tipe data yang paling serbaguna yang tersedia dalam bahasa Python, yang dapat ditulis sebagai daftar nilai yang dipisahkan koma (item) antara tanda kurung siku. Hal penting tentang daftar adalah item dalam list tidak boleh sama jenisnya.

Membuat list sangat sederhana, tinggal memasukkan berbagai nilai yang dipisahkan koma di antara tanda kurung siku. Dibawah ini adalah contoh sederhana pembuatan list dalam bahasa Python.

#Contoh sederhana pembuatan list pada bahasa pemrograman python
list1 = ['kimia', 'fisika', 1993, 2017]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]

Akses Nilai Dalam List Python

Untuk mengakses nilai dalam list python, gunakan tanda kurung siku untuk mengiris beserta indeks atau indeks untuk mendapatkan nilai yang tersedia pada indeks tersebut.

Berikut adalah contoh cara mengakses nilai di dalam list python :

#Cara mengakses nilai di dalam list Python

list1 = ['fisika', 'kimia', 1993, 2017]
list2 = [1, 2, 3, 4, 5, 6, 7 ]

print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])

Setelah Anda mengeksekusi kode diatas, hasilnya akan seperti dibawah ini :

list1[0]: fisika list2[1:5]: [2, 3, 4, 5]

Anda dapat memperbarui satu atau beberapa nilai di dalam list dengan memberikan potongan di sisi kiri operator penugasan, dan Anda dapat menambahkan nilai ke dalam list dengan metode append (). Sebagai contoh :

list = ['fisika', 'kimia', 1993, 2017]
print ("Nilai ada pada index 2 : ", list[2])

list[2] = 2001
print ("Nilai baru ada pada index 2 : ", list[2])

Hapus Nilai Dalam List Python

Untuk menghapus nilai di dalam list python, Anda dapat menggunakan salah satu pernyataan del jika Anda tahu persis elemen yang Anda hapus. Anda dapat menggunakan metode remove() jika Anda tidak tahu persis item mana yang akan dihapus. Sebagai contoh :

#Contoh cara menghapus nilai pada list python

list = ['fisika', 'kimia', 1993, 2017]

print (list)
del list[2]
print ("Setelah dihapus nilai pada index 2 : ", list)

Operasi Dasar Pada List Python

List Python merespons operator + dan * seperti string; Itu artinya penggabungan dan pengulangan di sini juga berlaku, kecuali hasilnya adalah list baru, bukan sebuah String.

Sebenarnya, list merespons semua operasi urutan umum yang kami gunakan pada String di bab sebelumnya. Dibawah ini adalah tabel daftar operasi dasar pada list python.

Python ExpressionHasilPenjelasanlen([1, 2, 3, 4])4Length[1, 2, 3] + [4, 5, 6][1, 2, 3, 4, 5, 6]Concatenation
#Cara mengakses nilai di dalam list Python

list1 = ['fisika', 'kimia', 1993, 2017]
list2 = [1, 2, 3, 4, 5, 6, 7 ]

print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
0
#Cara mengakses nilai di dalam list Python

list1 = ['fisika', 'kimia', 1993, 2017]
list2 = [1, 2, 3, 4, 5, 6, 7 ]

print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
1Repetition
#Cara mengakses nilai di dalam list Python

list1 = ['fisika', 'kimia', 1993, 2017]
list2 = [1, 2, 3, 4, 5, 6, 7 ]

print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
2
#Cara mengakses nilai di dalam list Python

list1 = ['fisika', 'kimia', 1993, 2017]
list2 = [1, 2, 3, 4, 5, 6, 7 ]

print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
3Membership
#Cara mengakses nilai di dalam list Python

list1 = ['fisika', 'kimia', 1993, 2017]
list2 = [1, 2, 3, 4, 5, 6, 7 ]

print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
4
#Cara mengakses nilai di dalam list Python

list1 = ['fisika', 'kimia', 1993, 2017]
list2 = [1, 2, 3, 4, 5, 6, 7 ]

print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
5Iteration

Indexing, Slicing dan Matrix Pada List Python

Karena list adalah urutan, pengindeksan dan pengiris bekerja dengan cara yang sama untuk list seperti yang mereka lakukan untuk String.

Functions are one of the "first-class citizens" of Python, which means that functions are at the same level as other Python objects like integers, strings, modules, etc. They can be created and destroyed dynamically, passed to other functions, returned as values, etc.

Python supports the concept of a "nested function" or "inner function", which is simply a function defined inside another function. In the rest of the article, we will use the word "inner function" and "nested function" interchangeably.

There are various reasons as to why one would like to create a function inside another function. The inner function is able to access the variables within the enclosing scope. In this article, we will be exploring various aspects of inner functions in Python.

Defining an Inner Function

To define an inner function in Python, we simply create a function inside another function using the Python's def keyword. Here is an example:

Output

Hello from outer function
Hello from inner function

In the above example,

def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))
0 has been defined inside
def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))
1, making it an inner function. To call
def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))
0, we must first call
def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))
1. The
def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))
1 will then go ahead and call
def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))
0 as it has been defined inside it.

It is important to mention that the outer function has to be called in order for the inner function to execute. If the outer function is not called, the inner function will never execute. To demonstrate this, modify the above code to the following and run it:

The code will return nothing when executed!

Here is another example:

def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))

Output

50

The code returns the multiplication of the two numbers, that is, 10 and 5. The example shows that an inner function is able to access variables accessible in the outer function.

So far, you have seen that it is possible for us to access the variables of the outer function inside the inner function. What if we attempt to change the variables of the outer function from inside the inner function? Let us see what happens:

Output

2
9

The output shows that it is possible for us to display the value of a variable defined within the outer function from the inner function, but not change it. The statement

def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))
6 helped us create a new variable
def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))
7 inside the inner function
def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))
0 rather than changing the value of variable
def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))
7 defined in the outer function
def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))
1.

In the next section, we will be discussing the main reasons as to why we use inner functions in Python.

Why use Inner Functions?

Encapsulation

A function can be created as an inner function in order to protect it from everything that is happening outside of the function. In that case, the function will be hidden from the global scope. Here is an example:

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Output

Traceback (most recent call last):
  File "C:/Users/admin/inner.py", line 7, in 
    inner_increment(5)
NameError: name 'inner_increment' is not defined

In the above code, we are trying to call the

50
1 function, but instead we got an error.

Now, comment out the call to

50
1 and uncomment the call to
50
3 as shown below:

Output

5 7

The script above shows that the inner function, that is,

50
1 is protected from what is happening outside it since the variable
def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))
7 inside the
50
6 function is not affected by the value passed to the parameter
def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))
7 of the outer function. In other words, the variables inside the inner function is not accessible outside it. There is a great advantage with such a design pattern. After checking all arguments in the outer function, we can safely skip error checking within the inner function.

Closures and Factory Functions

All the examples we have seen till now just contain ordinary functions that have been nested inside other functions. It is possible for us to write such functions in another way instead of nesting them inside other functions. We don't have a specific reason as to why we should nest them.

However, for the case of closures, one must use the nested functions.

We can bind/pass data to a function without necessarily passing the data to the function via parameters. This is done using a closure. It is a function object that is able to remember values in the enclosing scopes even when they are not available in the memory. This means that we have a closure when a nested function references a value that is in its enclosing scope.

The purpose of a closure is to make the inner function remember the state of its environment when it is called, even if it is not in the memory. A closure is caused by an inner function, but it's not the inner function. The closure works by closing the local variable on the stack, which stays around after the creation of the stack has finished executing.

The following are the conditions that are required to be met in order to create a closure in Python:

  • There must be a nested function
  • The inner function has to refer to a value that is defined in the enclosing scope
  • The enclosing function has to return the nested function

Consider the following example:

def function1(name):
    def function2():
        print('Hello ' + name)
    return function2

func = function1('Nicholas')
func()

Output

Hello Nicholas

The above code demonstrates that with closures, we are able to generate and invoke a function from outside its scope via function passing. The scope of

def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))
0 is only inside
def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))
1. However, with the use of closures, it was possible for us to extend this scope and invoke it from outside its scope.

Inner functions help us in defining factory functions. A factory function is a function that creates another object. For example:

Output

256
81

In the script above, from the

2
9
0 function, we have created two other objects,
2
9
1 and
2
9
2. This makes
2
9
0 a factory function since it generates the
2
9
1 and
2
9
2 functions for us using the parameter we pass it.

Conclusion

An inner function is simply a function that is defined inside another function. The inner function is able to access the variables that have been defined within the scope of the outer function, but it cannot change them. There are a number of reasons as to why we may need to create an inner function. For instance, an inner function is protected from what happens outside it. Inner functions are also a good way of creating closures in Python.