datastructures-in-python
  • Home
  • Downloads & Misc-Assets
  • README
  • Navigation
  • Curriculum
    • Outline
      • General Content
      • Python-Data-Structures-Unit
    • wk17
      • Outline-w17
      • homework
      • D1-Module 01 - Python I
        • Configuring Ubuntu for Python Web Development
        • Install Python
      • D2- Module 02 - Python II
      • D3- Module 03 - Python III
      • D4-Module 04 - Python IV
    • wk18
      • Outline-W-18
      • D1- Module 01 - Number Bases and Character Encoding
      • D2- Module 02 - Hash Tables I
        • Hash Table / Hash Map In Python:
        • Hash Table Use Cases
        • Practice
      • D3-Module 03 - Hash Tables II
      • D4- Module 04 - Searching and Recursion
    • wk19
      • Outline-W-19
      • D1- Module 01 - Linked Lists
        • Homework
          • Helpful Resource
      • D2- Module 02 - Queues and Stacks
      • D3- Module 03 - Binary Search Trees
        • BST Definition:
      • D4- Module 04 - Tree Traversal
        • Tree Traversals (Inorder, Preorder and Postorder)
    • wk20
      • Outline-W-20
      • D1-Graphs I
      • D2-Graphs 2
      • DFS
      • D4
  • Utilities
    • Utilites
      • Python Libraries
      • YouTube
      • Code Lab Notebook Embeds From Lecture
    • Code lab Notebooks
    • Repl.IT
      • Trinket
  • Abstract Data Structures
    • Algorithms
      • Algo-Resources
        • List-Of-Solutions-To-Common-Interview-Questions
      • Dijkstra's algorithm
      • Calculate a Factorial With Python - Iterative and Recursive
      • DFS
      • BFS
        • BFS Examples
      • Palendrome
    • Data Structures Overview
      • General Data Structures Notes
        • DS-Explained-Simple
      • Untitled
      • Algorithms
      • Dictionary
    • Abstract Data Structures:
      • Array
        • Extra-Array
        • Array Practice
      • Binary Search
      • Binary Tree
        • Binary Tree Explained
        • Find the maximum path sum between two leaves of a binary tree
      • Binary Search Tree
        • BST Explained
        • BST Insert
        • BST-Largest-Sub-Tree
      • Exotic
        • Tire
        • Dynamic Programming
      • Graphs
        • Overflow Practice Problems
        • Graphs Explained
        • Earliest Ancestor
        • _Mini Graph-Projects
          • # Social Graph
          • number of 1 islands
          • Searching and Generating Graphs
        • Graph FAQ
          • Graph DFS
        • Connected Components
        • Randomness
        • Graph BFS
        • Topological Sort
      • Hash Table
        • Hashmap or Hash tables
        • Hash Table and HashMap in Python
      • Heap
        • Heap Examples
      • String
      • Map
        • Examples
      • Queue
        • Queue Continued...
        • Queue Sandbox
        • Dequeue
      • Tree
        • In Order Traversal
        • Tree Equal ?
        • Ternary-search-trees
        • Red_Black Tree
        • Tree Mirror:
        • Tree Traversal
      • Recursion
        • Recursion Explained
          • Recursion Examples
      • Linked List
        • Linked List Background
        • Double Linked List
        • List Example
        • Examples (LL) continued
        • List Operations
      • Set
        • Set
        • Set Intersection Union
        • Disjoint Set
      • Sorting
        • In JavaScript
        • Merge Sort
        • Iterative Sorting
        • Recursive Sorting
        • Graph Topological Sort
        • SelectionSort
        • Quick Sort
        • Merge Sort
        • Insertion Sort
      • Stack
        • Stack Continued
        • Stack Part 3
      • Searching
        • Binary Search
        • Searching & Sorting Computational Complexity (JS)
  • practice
    • GCA Sprint Prep:
      • Practice Problems
      • Code Signal CGA Sprint Resources
      • CGA-Sprint Prep
    • Supplemental Practice:
      • Practice
      • JavaScript Algorithms
      • Industry Standard Algorithms
        • Interview Practice Resources
        • Write a Program to Find the Maximum Depth or Height of a Tree
      • Random Examples
      • Prompts
      • JS_BASICS
  • Resources
    • Python Cheat Sheet
      • Cheatsheet-v2
      • List Of Python Cheat Sheets
    • Youtube
    • PDF Downloads
    • Intro 2 Python
    • Dictionaries
      • Dictionaries Continued
    • Python VS JavaScript
    • Misc. Resources
    • Things To Internalize:
      • Functions
    • Intro To Python w Jupyter Notebooks
    • Calculating Big O
    • Useful Links
      • Awesome Python
      • My-Links
      • Beginners Guide To Python
  • Docs
    • Docs
      • Strings
        • Strings Continued
      • Touple
      • Values Expressions & Statments
      • Dictionaries, sets, files, and modules
        • Modules
      • Built-in Types
      • Built In Functions
        • Zip Function
      • Functions
      • Classes and objects
        • Inheritance
        • Classes
          • Python Objects & Classes
          • index
      • Dictionaries
      • Conditionals and loops
      • Lists
        • Reverse A List
        • Python Data Structures
        • More On Lists
        • Examples
          • More-Examples
        • List Compehensions
      • Basic Syntax
      • String-Methods
    • Queue & Stacks
  • quick-reference
    • My Medium Articles
    • Free Python Books
    • WHY Python?
    • Debugging
    • Python Snippets
    • Python3 Regex
    • Python Module Index:
      • Requests Module
    • Creating Python Modules
    • Useful Info
    • Python Glossary
    • Python Snippets
  • MISC
    • Built-in Methods & Functions
    • Data Structures Types
    • Math
    • Unsorted Examples
    • Outline
    • About Python
      • Python VS JavaScript
      • Python Modules & Python Packages
      • Misc
      • Python's Default Argument Values and Lists
      • SCRAP
  • Interview Prep
    • Interview Resources
      • By Example
        • Algo-Prep
      • Permutation
      • How to Write an Effective Resume of Python Developer
      • Interview Checklist
      • 150 Practice Problems & Solutions
  • Installations Setup & Env
    • python-setup
    • Installing Python Modules
    • Set Up Virtual Enviornment
  • Aux-Exploration
    • Related Studies
      • Self-Organizing Maps: Theory and Implementation in Python with NumPy
      • List Directory Contents
      • Employee Manager
      • OS Module
      • server-side-scripting
      • Web Scraping
      • Reading and Writing to text files in Python
      • General Data Structures
      • Touple
      • How to round Python values to whole numbers?
      • Python Array Module
      • Data Structures In JavaScript
      • Dunder Methods
      • Python GitHub API
      • JS-Event Loop
      • JavaScript Event Loop
      • Manipulating Files & Folders
  • experiments
    • Untitled
Powered by GitBook
On this page
  • Creating functions #
  • Function with return value. #
  • Global variables vs local variables #
  • print(local_var) # you can't access local_var outside the function, because as soon as function ends local_var is destroyed
  • Argument with default values #
  • Keyword arguments #
  • Mixing Positional and Keyword Arguments #
  • Returning multiple values from Function #

Was this helpful?

Export as PDF
  1. Resources
  2. Things To Internalize:

Functions

PreviousThings To Internalize:NextIntro To Python w Jupyter Notebooks

Last updated 3 years ago

Was this helpful?

Functions are the re-usable pieces of code which helps us to organize structure of the code. We create functions so that we can run a set of statements multiple times during in the program without repeating ourselves.

Creating functions

Python uses def keyword to start a function, here is the syntax:

def function_name(arg1, arg2, arg3, .... argN):

 #statement inside function

note:

All the statements inside the function should be indented using equal spaces. Function can accept zero or more arguments(also known as parameters) enclosed in parentheses. You can also omit the body of the function using the pass keyword, like this:

Let's see an example.

def sum(start, end): result \= 0 for i in range(start, end + 1): result += i print(result)

sum(10, 50)

Expected output:

Above we define a function called sum() with two parameters start and end. The function calculates the sum of all the numbers starting from start to end.

Function with return value.

The above function simply prints the result to the console, what if we want to assign the result to a variable for further processing? Then we need to use the return statement. The return statement sends a result back to the caller and exits the function.

def sum(start, end): result \= 0 for i in range(start, end + 1): result += i return result

s \= sum(10, 50) print(s)

Expected Output:

Here we are using the return statement to return the sum of numbers and assign it to variable s.

You can also use the return statement without a return value.

def sum(start, end): if(start > end): print("start should be less than end") return # here we are not returning any value so a special value None is returned result \= 0 for i in range(start, end + 1): result += i return result

s \= sum(110, 50) print(s)

Expected Output:

start should be less than end None

In python, if you do not explicitly return value from a function, then a special value of None is always returned. Let's take an example:

def test(): # test function with only one statement i \= 100 print(test())

Expected Output:

As you can see, the test() function doesn't explicitly return any value, so None is returned.

Global variables: Variables that are not bound to any function , but can be accessed inside as well as outside the function are called global variables.

Local variables: Variables which are declared inside a function are called local variables.

Let's see some examples to illustrate this point.

Example 1:

global_var \= 12 # a global variable

def func(): local_var \= 100 # this is local variable print(global_var) # you can access global variables in side function

func() # calling function func()

print(local_var) # you can't access local_var outside the function, because as soon as function ends local_var is destroyed

Expected Output:

Example 2:

xy \= 100

def cool(): xy \= 200 # xy inside the function is totally different from xy outside the function print(xy) # this will print local xy variable i.e 200

cool()

print(xy) # this will print global xy variable i.e 100

Expected Output:

You can bind local variable in the global scope by using the global keyword followed by the names of variables separated by comma (,).

t \= 1

def increment(): global t # now t inside the function is same as t outside the function t \= t + 1 print(t) # Displays 2

increment() print(t) # Displays 2

Expected Output:

Note that you can't assign a value to variable while declaring them global .

1 2 3 4 5 6 7 8 9 10 11 12

t \= 1

def increment():

#global t = 1   # this is error
global t
t \= 100        \# this is okay
t \= t + 1
print(t) \# Displays 101

increment() print(t) # Displays 101

Expected Output:

In fact there is no need to declare global variables outside the function. You can declare them global inside the function.

def foo(): global x # x is declared as global so it is available outside the function x \= 100

foo() print(x)

Expected Output: 100

To specify default values of argument, you just need to assign a value using assignment operator.

def func(i, j \= 100): print(i, j)

Above function has two parameter i and j. The parameter j has a default value of 100, it means that we can omit value of j while calling the function.

func(2) # here no value is passed to j, so default value will be used

Expected Output:

Call the func() function again, but this time provide a value to the j parameter.

func(2, 300) # here 300 is passed as a value of j, so default value will not be used

Expected Output:

There are two ways to pass arguments to method: positional arguments and Keyword arguments. We have already seen how positional arguments work in the previous section. In this section we will learn about keyword arguments.

Keyword arguments allows you to pass each arguments using name value pairs like this name=value. Let's take an example:

def named_args(name, greeting): print(greeting + " " + name )

named_args(name\='jim', greeting\='Hello')

named_args(greeting\='Hello', name\='jim') # you can pass arguments this way too

Expected Value:

It is possible to mix positional arguments and Keyword arguments, but for this positional argument must appear before any Keyword arguments. Let's see this through an example.

def my_func(a, b, c): print(a, b, c)

You can call the above function in the following ways.

# using positional arguments only my_func(12, 13, 14)

# here first argument is passed as positional arguments while other two as keyword argument my_func(12, b\=13, c\=14)

# same as above my_func(12, c\=13, b\=14)

# this is wrong as positional argument must appear before any keyword argument # my_func(12, b=13, 14)

Expected Output:

12 13 14 12 13 14 12 14 13

We can return multiple values from function using the return statement by separating them with a comma (,). Multiple values are returned as tuples.

def bigger(a, b): if a > b: return a, b else: return b, a

s \= bigger(12, 100) print(s) print(type(s))

Expected Output:

(100, 12)

Global variables vs local variables

Argument with default values

Keyword arguments

Mixing Positional and Keyword Arguments

Returning multiple values from Function

#
#
#
#
#
#
#