What is function in computer programming

A function is a unit of code that is often defined by its role within a greater code structure. Specifically, a function contains a unit of code that works on various inputs, many of which are variables, and produces concrete results involving changes to variable values or actual operations based on the inputs.

Within a greater code structure, a function, which also may be called a subroutine or procedure, is "called" by the code, depending on a user event or as part of a greater operation. When called, the function operates on the inputs and produces the results.

A basic example is a function called "addone" that will take a variable x, which is defined as an integer, and add one. The code within addone would look something like this:

input "x" x = x + 1

output "x"

An example of a function that operates on inputs instead may look like this:

input "x" if x > 5 then print x

end

Here, the function may or may not print, depending on the value of "x."

Share this Term

A function f takes an input x, and returns a single output f(x). One metaphor describes the function as a "machine" or "black box" that for each input returns a corresponding output.[1]

We can control the flow of a program by calling a function. If we call a function, it executes, returns a value, and then resumes the program where it was called.

In programming, a named section of a program that performs a specific task is called a function. In this sense, a function is a type of procedure or routine. Some programming languages make a distinction between a function, which returns a value, and a procedure, which performs some operation but does not return a value.

Most programming languages come with a prewritten set of functions that are kept in a library. You can also write your own functions to perform specialized tasks. [2]

We use function so we don't need to repeat ourselves. Please watch the video below and remember the content.


The difference between returning and printing

Students often print from within a function. Please understand the difference between printing a result from a function and returning a result from a function.

print: gives the value to the user as an output string. print(3) would give a string '3' to the screen for the user to view. The program would lose the value.

return: gives the value to the program. Callers of the function then have the actual data and data type (bool, int, etc...) return 3 would have the value 3 put in place of where the function was called.[3]

In general, you should return a value from a function and not directly print from a function.

Example of a function

1# 2# this is a simple function that remembers who like hamburgers and who doesn't like hamburgers. 3# 4 5def likesHamburgers(name): 6 if name == "Alisher": 7 likes_hamburgers ="yes" 8 else: 9 likes_hamburgers="no" 10 return likes_hamburgers 11 12print likesHamburgers("Bill") 13print likesHamburgers("Alisher") 14print likesHamburgers("foo")

Another classic example of a function

# # this is a simple function # def calculator(number1, number2): answer = number1 + number2 return answer print calculator(12,43) print calculator(91,673) print calculator(1,3) print calculator(87,1098)

Some decent videos about functions in Python

See Also

References

This lesson introduces functions. A function is a block of organized code that is used to perform a single task. They provide better modularity for your application and reuse-ability. Depending on the programming language, a function may be called a subroutine, a procedure, a routine, a method, or a subprogram. The generic term, callable unit, is sometimes used. Using functions can allow you to be able to keep your code clean and organized, making it easy to read, and allows the debugging process to be easier.[1]

Objectives and skills for this lesson include:

  • Understand the benefits of modular programming
  • Understand functions, passed parameters, and return values
  • Understand variable scope
  • Use functions to implement program functionality
  • Use local variables, passed parameters, and return values
  • Apply standard coding style to source code
  • Functions
  • Parameters
  • Return Values
  • Scope
  • Style

Complete the following activities using a flowchart tool, pseudocode, or your selected programming language. Use separate functions for input, processing, and output. Avoid global variables by passing parameters and returning results.

  1. Create a program to prompt the user for hours worked per week and rate per hour and then calculate and display their weekly, monthly, and annual gross pay (hours * rate). Base monthly and annual calculations on 12 months per year and 52 weeks per year.[2]
  2. Create a program that asks the user how old they are in years, and then calculate and display their approximate age in months, days, hours, and seconds. For example, a person 1 year old is 12 months old, 365 days old, etc.
  3. Review MathsIsFun: US Standard Lengths. Create a program that asks the user for a distance in miles, and then calculate and display the distance in yards, feet, and inches, or ask the user for a distance in miles, and then calculate and display the distance in kilometers, meters, and centimeters.
  4. Review MathsIsFun: Area of Plane Shapes. Create a program that asks the user for the dimensions of different shapes and then calculate and display the area of the shapes. Do not include shape choices. That will come later. For now, just include multiple shape calculations in sequence.
  5. Create a program that calculates the area of a room to determine the amount of floor covering required. The room is rectangular with the dimensions measured in feet with decimal fractions. The output needs to be in square yards. There are 3 linear feet (9 square feet) to a yard.[3]
  6. Create a program that helps the user determine how much paint is required to paint a room and how much it will cost. Ask the user for the length, width, and height of a room, the price of a gallon of paint, and the number of square feet that a gallon of paint will cover. Calculate the total area of the four walls as 2 * length * height + 2 * width * height Calculate the number of gallons as: total area / square feet per gallon Note: You must round up to the next full gallon. To round up, add 0.9999 and then convert the resulting value to an integer. Calculate the total cost of the paint as: gallons * price per gallon.[4]
  7. Review Wikipedia: Aging in dogs. Create a program to prompt the user for the name of their dog and its age in human years. Calculate and display the age of their dog in dog years, based on the popular myth that one human year equals seven dog years. Be sure to include the dog's name in the output, such as:
        Spike is 14 years old in dog years.
  • Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.[5]
  • The hierarchy chart shows the relationship between various models. They are created by the programmer to help document a program.[6]
  • Functions allow you to break down programs into smaller, simpler, programs or "blocks" making it easier for the user to test and work on. Functions also allow the user to keep their programs organized and easy to read.[source?] A function acts as a miniature program, with its own input, processing, and output.[7]
  • The scope is the area of the program where an item that has an identifier name is recognized. It is an important concept for modularization. A Scope can be two types of a Global scope and a Local scope. Global scope occurs when a variable is "defined outside of the function". The local scope, from the other hand, is defined "inside of the function" and exist only until the function completes its task. [8]
  • A good rule of thumb for identifiers in procedural programs is to use verb-noun combinations for function identifiers and use a noun or adjective-noun combinations for constant and variable identifiers. If a function name requires two verbs or two nouns to fully describe the function, it should probably be split into separate functions.[9]
  • Programming style is a set of rules or guidelines of writing the code for a computer program. Almost all languages have their own set of guidelines that allow programmers to code efficiently. Following a programming style of a particular language will help programmers to read and understand source code confirming to the style set and help to avoid introducing errors. Code that is written well should have appropriate spacing and proper indentations and be free from grammar and spelling errors.([10]),[11]
argument In programming, a value that is passed between programs, subroutines or functions; which are provided as an input to a function. Arguments are independent items, or variables, that contain data or codes. When an argument is used to customize a program for a user, it is typically called a "parameter."[12] call-by-reference Arguments are passed to the subroutine by direct reference, typically using the argument's address. Which can be modified by called functions.[13] call-by-value Arguments are evaluated and a copy of the value is passed to the subroutine. Which cannot be modified by called functions.[14] function A section of a program designed to perform a specific procedure or task.[15] function header The header includes the name of the function and tells us (and the compiler) what type of data it expects to receive (the parameters) and the type of data it will return (return value type) to the calling function or program.[16] identifier name The name given by the programmer to identify a function or other program items such as variables.[17] modularization The ability to group code into a unit, most often being functions, that can be used as independent and self-contained sub-programs withing the main program.[18] parameter In computer programming, a parameter is a value that is passed into a function.[19] return statement Stops the function and returns a variable to the call location.[20] return value Return value is a variable or other information coming back from the subroutine.[21] scope Variables can only effect areas in which they are defined, their reach by default is local to the function in which they are defined.[22] subroutine In computer programming, a subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.[23] void A data type that represents a return of no value.[24]
  • Quizlet: Flash Cards
  • Quizlet: Quiz
  • Quizlet: Flash Cards

Postingan terbaru

LIHAT SEMUA