Skip to main content
Chemistry LibreTexts

2: Functions

  • Page ID
    467319
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    Functions are blocks of code that perform specific tasks or sets of task. A typical function has an input (arguments or parameters) that it performs some kind of process on and then returns some kind of output. This can help organize code associated with a complex project and make it more readable.  Processes that are repeated often are ideal processes to make a function out of. Book 5 section 4 is devoted to functions and we will see that there are standard built-in functions like the print() statement that load everytime you run python, standard library functions that come with python but that you must import to your code to use, third party library functions like those that could be associated with reading values of a specific sensor and you can even make your own user-defined functions

    Anatomy of a Function

    • Input
      • Functions operate on data or perform some task that they operate on.
      • In python this information is enclosed in parenthes.is after the function name
      • Parameters are the types of variables a function operates on, it defines the kind of argument a function can accept
      • Arguments are the actual data values submitted to a function and upone which it operates on.
    • Function Body
      • Instructional programmatic steps the function performs on the data.
      • This is the program that is run when the function is called.
    • Output
      • This is the value or action that is returned when a function is called.

    Then all you need to do is call the function and pass it any arguments it needs.

    Python Example of User Defined Function

    In the following code we create a function called "molar_mass_fct" and gave it the code from the flowchart of the if-else statement associated with the pseudocode of the last activity.  All python functions must be followed by parenthesis.  Do not worry if you do not understand the syntax as we will get to that later this semester.  Right now you need to know what a function is and what it does.  But hit run, and try some values, and note that there are only two lines of code outside of the function, the input molar mass line, and the function call line.  Also note that in python a comment is indicated with a # sign, so the lines starting with a # are not run as code

    def molar_mass_fct(molar_mass):
        if molar_mass >= 2.0:
            print(f"The molar mass you entered is: {molar_mass}g/mol")
        else:
            molar_mass=float(input("Enter a molar mass greater than or equal to diatomic hydrogen "))
            print(f"The molar mass you entered is: {molar_mass}g/mol")
            
    #Input molar mass
    molar_mass=float(input("Enter the molar mass of a molecule in units of g\mol "))
    #call function
    molar_mass_fct(molar_mass)
    Hello world!

    The function in the above code was defined by this code block.  It is given the name "molar_mass_fct" and operates on the "molar_mass" variable

    def molar_mass_fct(molar_mass):
        if molar_mass >= 2.0:
            print(f"The molar mass you entered is: {molar_mass}g/mol")
        else:
            molar_mass=float(input("Enter a molar mass greater than or equal to diatomic hydrogen "))
            print(f"The molar mass you entered is: {molar_mass}g/mol")
    

    In the next line of code we input a value (the argument) that we assign to the variable molar mass. Note we used two built-in functions in this line of code.  The first was the input() function, but that returns a string value (letter) and we need to convert it to a floating number so we can sue the >= comparison operator within the function body, and so we placed that function inside of the float function.  the result is we have now assigned the variable molar_mass the value of the floating number input by the user

    molar_mass=float(input("Enter the molar mass of a molecule in units of g\mol "))
    

    In the last step we call the function and pass it the argument (value input by the user) and it then either says the value is too small to be a molar mass, or it outputs the value.

     molar_mass_fct(molar_mass)

     

    Flowchart Simplification

    In the following diagram we show how making a function to check the molar mass is larger than two simplyfies the flow chart to just an input statement and a function call statement.  The material on the top part of the image in red dots is the function, and this shows how a function can simplfy the code and make it more readable.

    clipboard_ea2c1282937779534fce38135c4563d55.pngclipboard_e7870919fc5cbfb30a7141dcec7fb94e9.pngFigure \(\PageIndex{1}\): Two flowcharts doing the same thing.  The top one does not use a function, while the bottom one calls a function that does the operations in the dotted box.  Once the function has been made, it can be used by multiple programs, and this is why there are libraries (or packages) in python containing functions and other features. (Belford CC-BY)

     


    2: Functions is shared under a not declared license and was authored, remixed, and/or curated by LibreTexts.

    • Was this article helpful?