0% found this document useful (0 votes)
39 views7 pages

Understanding Fruitful Functions in Python

The document explains fruitful functions in Python, which return results after computation, enhancing code modularity and maintainability through reusable code. It covers the importance of parameters in these functions, methods for calculating square roots, aliasing and cloning lists, creating histograms with Numpy, and file operations including opening, reading, writing, and closing files safely. The document emphasizes the dynamic interaction between parameters and arguments, as well as best practices for file handling in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views7 pages

Understanding Fruitful Functions in Python

The document explains fruitful functions in Python, which return results after computation, enhancing code modularity and maintainability through reusable code. It covers the importance of parameters in these functions, methods for calculating square roots, aliasing and cloning lists, creating histograms with Numpy, and file operations including opening, reading, writing, and closing files safely. The document emphasizes the dynamic interaction between parameters and arguments, as well as best practices for file handling in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Fruitful Python functions are those that yield a result after computation.

Unlike void
functions, which perform a job without returning a result, productive functions add to a
program's overall logic by generating an output. These routines include reusable pieces of
code, which improves code modularity and maintainability. Eg: def multiply_numbers(x, y):
result = x * y return result You can use this function, passing it two integers, and it will not
only execute the multiplication but also return the result.

Parameters in Fruitful Functions in Python

Understanding parameters in fruitful functions is key to crafting efficient and dynamic code.
Parameters serve as variables that get values when the function is invoked, enabling us to
tailor the function's behaviour. In a vast array of fruitful functions, parameters act as input
channels, allowing your functions to process a wide range of inputs. They behave as
placeholders, anxiously awaiting values when the function is called. Consider a function for
calculating the area of a rectangle. Here, length and width are parameters that require
particular values to get a valid outcome. Parameters are defined by declaring them within
the function's parentheses and providing their names and types. These inputs convert
simple programs into diverse tools capable of handling a variety of datasets. Python's
versatility shows through because it enables default parameter values, which adds an added
layer of adaptability. When you call the function, you pass the actual values (arguments) for
these parameters. This dynamic interaction of parameters and arguments enables your
functions to respond to individual demands, resulting in code that is both functional and
highly reusable. So, understanding arguments in useful functions allows you to write Python
code that is both powerful and customizable, making your programming experience more
straightforward and efficient.

def multiply_by_two(x):

return x * 2

def add_five(x):

return x + 5

def combined_function(x): return add_five(multiply_by_two(

Square Root of a Number The square root of a number x is a value


y such that when y is multiplied by itself, it equals x. ● Mathematical
Representation: √x = y where y × y = x Python has several methods to
find the square root of a [Link] method has its use case,
depending on whether you’re working with simple numbers, complex
numbers, or more advanced mathematical operations.
Exponentiation Operator (**) The ** operator in Python is the
exponentiation operator, used to raise a number to a power (e.g., a
** b computes a^b). This is the simplest method in Python for
calculating the square root of a given number. The square root of a
number is equivalent to raising the number to the power of 0.5.
[Link]() Function [Link]() is a function in Python’s math
module that returns the square root of a given non-negative number.
This method is helpful because it’s a dedicated function for this
operation and ensures precision. Square Root of a Number The
square root of a number x is a value y such that when y is multiplied
by itself, it equals x. ● Mathematical Representation: √x = y where y ×
y = x ● For Example: √25 = 5 because 5 × 5 = 25 Python has several
methods to find the square root of a number. Here are a few
common approaches, each with an explanation and example. Each
method has its use case, depending on whether you’re working with
simple numbers, complex numbers, or more advanced mathematical
operation
Aliasing and cloning list in python: Since variables refer to objects, if
we assign one variable to another, both variables refer to the same object:
Eg: a = [81, 82, 83]
b = a print(a is b)
Output: True In this case, the reference diagram looks like this: Because the
same list has two different names, a and b, we say that it is aliased. Changes
made with one alias affect the other.
In the codelens example below, you can see that a and b refer to the same list
after executing the assignment statement b = a.
a = [81, 82, 83]
b = [81, 82, 83]
print(a == b) print(a is b)
b = a print(a == b)
print(a is b)
b[0] = 5 print(a)
HISTOGRAM:

A histogram is the best way to visualize the frequency


distribution of a dataset by splitting it into small equal-sized
intervals called bins. The Numpy histogram function is similar
to the hist() function of matplotlib library, the only difference
is that the Numpy histogram gives the numerical
representation of the dataset while the hist() gives graphical
representation of the dataset. Creating Numpy Histogram
Syntax: [Link](data, bins=10, range=None,
normed=None, weights=None, density=None) EG: # import
libraries from matplotlib import pyplot as plt import numpy
as np # Creating dataset a = [Link](100, size
=(50)) # Creating plot fig = [Link](figsize =(10, 7)) [Link](a,
bins = [0, 10, 20, 30, 40, 50, 60, 70,80, 90, 100])
[Link]("Numpy Histogram") # show plot [Link]() Output:
FILES: File is a named location on disk to store related
information. It is used to permanently store data in a non-
volatile memory (e.g. hard disk). Since, random access
memory (RAM) is volatile which loses its data when computer
is turned off, we use files for future use of the data. When we
want to read from or write to a file we need to open it first.
When we are done, it needs to be closed, so that resources
that are tied with the file are freed. Hence, in Python, a file
operation takes place in the following order. 1. Open a file 2.
Read or write (perform operation) 3. Close the file Opening a
file Python has a built-in function open() to open a file. This
function returns a file object, also called a handle, as it is
used to read or modify the file accordingly. >>> f =
open("[Link]") # open file in current directory >>> f =
open("C:/Python33/[Link]") # specifying full path We
can specify the mode while opening a file. In mode, we
specify whether we want to read 'r', write 'w' or append 'a' to
the file. We also specify if we want to open the file in text
mode or binary mode. The default is reading in text mode. In
this mode, we get strings when reading from the file. On the
other hand, binary mode returns bytes and this is the mode
to be used when dealing with non-text files like image or exe
files.
f=
open("[Link]") # equivalent to 'r' or 'rt' f =
open("[Link]",'w') # write in text mode f =
open("[Link]",'r+b') # read and write in binary mode
Hence, when working with files in text mode, it is highly
recommended to specify the encoding type. f =
open("[Link]",mode = 'r',encoding = 'utf-8') Closing a File
When we are done with operations to the file, we need to
properly close it. Closing a file will free up the resources that
were tied with the file and is done using the close() method.
Python has a garbage collector to clean up unreferenced
objects but, we must not rely on it to close the file. f =
open("[Link]",encoding = 'utf-8') # perform file operations
[Link]() This method is not entirely safe. If an exception
occurs when we are performing some operation with the file,
the code exits without closing the file. A safer way is to use a
try...finally block. try: f = open("[Link]",encoding = 'utf-8') #
perform file operations finally: [Link]() This way, we are
guaranteed that the file is properly closed even if an
exception is raised, causing program flow to stop. The best
way to do this is using the with statement. This ensures that
the file is closed when the block inside with is exited. We
don't need to explicitly call the close() method. It is done
internally. with open("[Link]",encoding = 'utf-8') as f: #
perform file operations Reading and writing A text file is a
sequence of characters stored on a permanent medium like a
hard drive, flash memory, or CD-ROM. To write a file, you
have to open it with mode 'w' as a second parameter: >>>
fout = open('[Link]', 'w') >>> print fout If the file already
exists, opening it in write mode clears out the old data and
starts fresh, so be careful! If the file doesn’t exist, a new one
is created. The write method puts data into the file. >>> line1
= "This here's the wattle,\n" >>> [Link](line1) Again, the
file object keeps track of where it is, so if you call write again,
it adds the new data to the end. >>> line2 = "the emblem of
our land.\n" >>> [Link](line2) When you are done writing,
you have to close the file. >>> [Link]()

You might also like