Computer Science

Functions in Python

Functions in Python are reusable blocks of code that perform a specific task. They allow for better organization and reusability of code by breaking it into smaller, manageable pieces. Functions can take input parameters, perform operations, and return results. They are a fundamental concept in Python programming and are used extensively for modular and efficient code development.

Written by Perlego with AI-assistance

4 Key excerpts on "Functions in Python"

Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.
  • Geometric Computation: Foundations for Design
    • Joy Ko, Kyle Steinfeld(Authors)
    • 2018(Publication Date)
    • Routledge
      (Publisher)

    ...1.05 FUNCTIONS As first presented in Chapter 1.02, a function is a sequence of statements packaged as a unit which may be called upon elsewhere in a body of code. Our scripts have regularly invoked functions that are built into the Python language, such as len(), range(), and print(). We have also seen how to define stand-alone functions as well as those associated with a structured type, most of which related to one of the geometric types that make up the Decod.es library. A function associated with a type in this way is called a method, a programmatic construct that operates from the “inside”, enjoying access to the members of each instance of that class. For both methods and stand-alone functions, the basic definitional syntax is the same, and is demarcated by the keyword def followed by an indented block of code: def function_name(): do_some_things Beyond this very simple template, we have seen that functions and methods offer mechanisms for communicating with the “outside” context from which they are called. A function may receive data from its calling context via any number of defined arguments, and return data to its calling context via the return statement. def function_name(argument_one, argument_two, …): do_some_things return some_thing The expediency of this basic template, and of rudimentary understanding of how functions operate, has left open a number of questions regarding the nature of functions. What does it mean for some blocks of code to operate “inside” a function and others “outside” of it? What is the nature of this demarcation, and what are its real ramifications in terms of how we write code, both for our own use and to share with others? The simplicity of certain methods that we have encountered so far belies their sophistication when applied in practice. We have seen, for example, that there are multiple ways to construct a Decod.es Vec that are not accounted for in our presentation of the Vec.__init__() method...

  • Hands on Data Science for Biologists Using Python
    • Yasha Hasija, Rajkumar Chakraborty(Authors)
    • 2021(Publication Date)
    • CRC Press
      (Publisher)

    ...Functions are a block of statements that perform a task and have a name so that we can identify them later. A function can also take arguments and returns some values. Let us define a simple function below: Code: def BioLove(): print('I love Biology..!') BioLove() Output: I love Biology..! This is a simple function that just prints a few things. The “def” keyword is used to tell Python that we are going to define a function. After “def” keyword, we provide a name to the function with parenthesis; here the given name is “BioLove()”. Next, we put a colon, and by now we know what colon defines - a block of indented statements. The code block will run every time the function is called. The function is called by its name - in this case, like BioLove(). It will run the block of code under the “def” statement. Here it just prints “I love Biology…!”. We can pass values to a function. These values are known as the arguments of a function. Arguments are defined and passed inside the parenthesis of a function name. These arguments can be accessed inside the functions like variables. Code: #Functions with arguments #Pass one arguments def Drug(compound): print(compound,'is a Drug') Drug('Metformin') Output: Metformin is a Drug While defining a function, we have to choose the name of the argument. Arguments can be of any value or of any datatype. There, an argument “compound” is defined with the function, and this function prints the “compound is a Drug”. Later, we can call this function by any drug name, and it will do the rest for printing it. Likewise, functions can take any number of arguments. Code: #Pass two arguments def DrugDisease(Drug,Disease): print(Drug,'is used for treatment of',Disease) DrugDisease('Metformin','type 2 diabetes') Output: Metformin is used for the treatment of type 2 diabetes Types of Arguments Unlike other languages, Python treats functional arguments in a rather versatile way. Various types of arguments can be assigned while defining a function...

  • Bioinformatics Algorithms
    eBook - ePub

    Bioinformatics Algorithms

    Design and Implementation in Python

    • Miguel Rocha, Pedro G. Ferreira(Authors)
    • 2018(Publication Date)
    • Academic Press
      (Publisher)

    ...Being syntactically relevant, changes in indentation may affect the logic of the code. These rules can be summarized as follows: •  Code begins in the first column of the file. •  All lines in a block of code are indented in the same way, i.e. aligned by a fixed spacing. No brackets are required to delimit the beginning and the end of the block. •  A colon (:) opens a block of code. •  Blocks of code can be defined recursively within other blocks of code. The following pseudo-code represents a cascade of three nested blocks of code, where block_1 has N statements, block_2 has M statements and block_3 has K statements. 2.3.2 User-Defined Functions We have seen a number of pre-defined Python functions. Let us now proceed to defining our own functions. These are simply defined by the def keyword, the function name and a list of arguments, followed by a block of statements after the colon. The return statement is used to provide a result for the function, and typically is the last statement, although with more complex code this might not be the case. In case there is nothing to return, None can be returned. In case multiple values need to be returned, a tuple with the results can be returned. It is good practice to include at the beginning of the function one or more lines describing its purpose and usage. Documentation text is enclosed by triple quotes ‘‘‘ ’''. These lines are called documentation string (docstring). Programs that generate automatic code documentation use this information to document the different functions. As an example, a function that computes the square of an inputted value can be defined as follows: Or, more generally, we can define a function that receives the base of the exponential expression and the power to raise the base. The function syntax allows defining default values for its arguments. In that case, if the argument is omitted when calling the function, the default value is assumed for that argument...

  • Introduction to Digital Music with Python Programming
    eBook - ePub
    • Michael S. Horn, Melanie West, Cameron Roberts(Authors)
    • 2022(Publication Date)
    • Focal Press
      (Publisher)

    ...When a function produces a result, it’s called a return value. For example, the random function computes a random decimal number somewhere between 0.0 and 1.0. This can be particularly useful in music for creating a more human feel. In Python the random function is part of a module also called random that must be imported first. from random import random  # import the random function duration = random()        # set duration to a value between 0.0 and 1.0 playNote(60, duration + 1) # play a note with a randomized duration 5.4 Defining your own functions You can also define your own Functions in Python using the def keyword. Once you define a function, you can use it just like any other function. For example, the code below defines two functions called chorus and groove. You can give your functions any name you want as long as they’re one word long (no spaces) and consist only of letters, numbers, and the underscore character (_). Function names cannot start with a number. def chorus():     playNote(60)     playNote(61)     playNote(65) def groove():     playNote(0, beats = 0.5)     playNote(4, beats = 0.5)     playNote(2, beats = 0.5)     playNote(4, beats = 0.5)     playNote(0, beats = 0.5)     playNote([0, 4], beats = 0.5) # double kick with hat     playNote(2, beats = 0.5)     playNote(4, beats = 0.5) Python uses indentation to figure out which code is inside of a function and which code is outside. In the above examples, the code inside each function is indented by four spaces (Appendix A1.5). Once a function is defined, we can call it just like we would any other function: chorus() chorus() groove() 5.5 Defining functions with parameters You can also define functions that take parameter values. A parameter is like a special variable that you can use just inside of a function (see the next section for more on variables). Here’s a quick example of a function that takes two parameters as input values...