Functions in programming perform specific tasks or actions. They have a name, parentheses, and sometimes arguments specified within the parentheses. Arguments are values provided to a function that help it carry out its task. Examples from this section:
print()
float()
round()
When a function does its job, it often gives back a result. This result is called the return value. The return value may be saved to a variable or used in some expression.
"Hello, World!"
42
3.14159
print()
- Outputs text to the console and then moves the cursor to a new line, ready for the next output.+
Addition: Adds two numbers together.-
Subtraction: Subtracts one number from another.*
Multiplication: Multiplies two numbers./
Division: Divides one number by another and returns the quotient as a decimal.//
Integer Division: Divides one number by another and cuts off the decimal.%
Modulus (aka mod): Returns the remainder after division.input()
- Allows the user to input via the keyboard. Returns the input as a string value.
int()
- Converts a specified value to an integer. Returns the integer if successful.float()
- Converts a specified value to a floating-point (decimal) number. Returns the double if successful.round()
- Rounds a number to either an integer or to some decimal placemath.sqrt()
- Calculate the square root of a non-negative number.math.pow()
- Raise a base number to the specified exponent.math.pi
- Represents the constant value π (pi).random
module using import random
.randint()
function to generate a random integer within a specified range. For example, random.randint(1, 100)
generates a number between 1 and 100.