Nested functions & scope

Lesson Details:
June 29, 2020


I: Introduction

Python is a high-level programming language that was created by Guido Van Rossum. It is an interpreted language that can be used for object-oriented programming. Here, we will discuss how python differs from other programming languages and the advantages of using this language.

A: Python has a small memory footprint

Unlike Java, Python uses a dynamic type system rather than a static type system. This means that it is up to the programmer to assign a value to a variable what will later allow them to check if it is of a particular type. While this may seem like a negative aspect of the language, it actually allows for code to run much more quickly since you do not need to spend time assigning values.

The memory footprint is also smaller due to the fact that the programmer must explicitly define variables and their scope. For example, using python, if you wish to define a function, you must define it at the top of the file. If you already have variables defined under this function, they cannot be accessed outside of the function. This allows the variables to be allocated only as much memory as they need and also helps to prevent errors such as “variable redefinition” which occur when you try to access a variable that has been previously defined but with a different value.

B: Python is easy to install and learn

Python is an open source language which means that it can be installed and run on any operating system and platform free of charge. The benefit of using python as opposed to some other open source languages such as Perl or PHP is that the syntax is very simple and easy to learn. This makes it easy for new programmers to begin coding without having to spend too much time on learning how to write code.

C: Python has graphics capabilities

Another advantage of python is that it has built-in graphics capabilities that allow users to create programs that display information graphically. Because of the simplicity of its syntax, python is also an ideal language for creating web applications because it can be embedded in HTML code to make it easier for users to create visual demonstration websites.

D: Python supports many databases

Because of its simplicity and ease of use, many database engines such as MySQL and PostgreSQL support python as a scripting language. This allows users to easily create web applications which connect directly with databases and retrieve data. The ability to connect with databases through python also allows for maximum flexibility in writing programs since users do not need to worry about creating interfaces between each application program and the database engine.

E: Python is portable

As mentioned earlier, one of the benefits of the open source nature of python is that it can run on any platform and operating system without modification or special installation procedures. Not only can it run across many platforms but it also provides a way for users to write their own module so that they can customize existing functionality so that it works better within their environment. It does this through its C-based extensibility model. This extensibility model allows users to add functions and data structures through C bindings in order to add their own functionality into python. In addition, there are many other modules that have been developed by third parties that you can simply download from the internet and add into your own code base in order to add functionality that you might not otherwise have access to. This allows users to extend python in a way that would not be possible in languages such as Java.

II: Body

A: Nested functions & scope

In python you can nest functions within one another in order to create a hierarchy of functions or objects within a program. The syntax for doing this is fairly simple and involves just putting parentheses after the nested function definition instead of before it like in C++ or Java. In addition, every function has its own scope which means that if you have multiple functions within a program, they will not have access to variables defined outside of their own scope unless they are explicitly passed in through a variable or function call. This feature makes debugging simpler since you don’t have to worry about trying to figure out where a variable got changed or why it isn’t being used correctly within a program. This scoping model also prevents variable redefinition which occurs when you try to use an already defined variable with different values or you try to use two different variables with the same name in the same scope; this often leads to bugs in other languages since they do not always catch variable redefinition errors when compiling code. The only exception to this rule is the Global Scope which allows all functions within your program to access any variable that is defined outside of them; you can specify whether or not your function opens up into the global scope by adding either an ‘*’ (for all global variables) or an empty set (for no global variables). The following shows an example of nested functions in action:

#!/usr/bin/python3 # Function 1 def get_data( ): return {'id':1,'name':'Python','description':'High level programming language','language_family':'Python','created_on':'December 3,'} def get_data2( ): return {'id':2,'name':'Java','description':'High level programming language','language_family':'Java','created_on':'December 10,'} # Function 2 def get_data3( ): return {'id':3,'name':'C','description':'Low level programming language','language_family':'C','created_on':'December 15,'} def main( ): data=get_data( ) data2=get_data2( ) data3=get_data3( ) print(data['name'],'has',data['language_family'], 'generations.') print(data2['name'],'has',data2['language_family'], 'generations.') print(data3['name'],'has',data3['language_family'], 'generations.') main()

The above code outputs the following when run: Quick Tip: Functions in Python are considered objects themselves which means that they have methods just like any other object in python. These methods are called by prepending ‘@’ before the name within parenthesis after the function name. For example, you could pass an array into one of your functions by prepending ‘@’ before the array name in the parenthesis after the function name. The following shows an example of how you would do this: #!/usr/bin/python3 import math def test(a): @a = [1 ,2] print('test( ) returns',a) print('test( ) returns',math.sqrt(*a)) test( ) returns [1 ,2] test( ) returns 1 .41421 test( ) returns 0 .81649 Since functions are just objects, we can also use them as parameters for other functions. #!/usr/bin/python3 def sum(x,y): return x+y def main( ): res=sum(5,6) print('sum(5,6) returns %d ' % res ) main() One problem with this method is that we must pass the entire function object as opposed to just passing its name or part of its definition as we usually do with normal objects. This can lead to problems if we try and pass functions around our program and we don’t want them executed immediately; therefore, we recommend passing function references whenever possible instead of executing them directly by name or passing around function objects directly which creates problems if we want them delayed or collected into groups for later execution (such as when we want to create queues). We can also create anonymous functions (or lambdas) by using square brackets instead of parenthesis after the function definition; these anonymous functions work exactly like normal ones except that there is no way for us to access their names afterwards. The following shows an example of using anonymous functions: #!/usr/bin/python3 def main(): res1 = sum(5,6) res2 = lambda x,y: x+y print('res1 %d ' % res1) print('res2 %d ' % res2) # Res1 returns 11 # Res2 returns 7 main() In addition, since lambdas always take at least one parameter, we can omit one or more arguments from them if we want them to match those defined in the function call so that we don’t have to worry about matching them ourselves. The following shows an example of using lambdas with abstract arguments: #!/usr/bin/python3 def main(): res1 = sum(*[1 ,2]) res2 = sum(*[1 ,2,3]) print('

loader
Course content