More on Methods and Functions
More on Methods and Functions
How to use split( ) method
Split( ) method splits a string and returns it in list format. By default, it splits with space in between characters.
How to assign multiple values within one line
first, second, third, fourth = 0, 0, 0, 0
What is list comprehension
List comprehension is another way to define and create a list in python. List comprehension consists of:
- Output Expression
- Input Sequence
- A variable representing a member of the input sequence
- optional predicate part
## list of odd squares from 1 to 10 using list comprehension
odd_square = [x ** 2 for x in range(1,11) if x % 2 == 1]
print(odd_square)
[1, 9, 25, 49, 81]
## same as the code above
odd2 = []
for x in range(1,11):
if x % 2 == 1:
odd2.append(x**2)
print(odd2)
[1, 9, 25, 49, 81]
How to use map( ) function
Syntax: map(function, iter)
map( ) function returns a list of the results after applying the given function to each iterable item.
# proportion = input()
# prop = proportion.split()
# for i in range(len(prop)):
# prop[i] = float(prop[i])
# lines above can be simplified as
prop = list(map(float, input().split()))
How to use zip( ) function
Syntax: zip(*iterables)
zip( ) function returns an iterator; a series of tuples containing elements from each iterable.
First class functions in Python
A programming lnaguange is said to support first-class functions if it treats functions as first-class objects. Python supports the concept of First Class functions.
-
Functions are objects, meaning users can assign function to a variable and that will take the function object referenced by the original function create a second name pointing to it.
-
Functions can be passed as arguments to other functions
-
Functions can return another function
Nested Functions and Closures in Python
Nested function is a function that are able to access variables of enclosing scope.
Closure is a function object that remembers the values in enclosing scope even if they are not present in memory, a record that stores a function together with an envorinment. Unlike a plain function, closure allows the function to access those captured variables through the closure’s copies of their values or references, even when the function is invoked outside their scope.
As closures are used as callback functions, they provide some sort of data hiding, which allows to reduce the use of global variable.
When we have few functions in our code, closures prove to be an efficient way, but with many functions, then go for class (OOP).
# nested functions
def outerFunction(text):
text = text
def innerFunction():
print(text)
innerFunction()
if __name__ == '__main__':
outerFunction('Hey!')
Hey!
# closures
def outerFunction(text):
text = text
def innerFunction():
print(text)
# Note: returning function WITHOUT parenthesis
return innerFunction
if __name__ == '__main__':
myFunction = outerFunction('Hey!')
myFunction()
Hey!