• Home
  • HTML
    • HTML Introduction
    • HTML Basic
    • HTML Elements
    • HTML Attributes
    • HTML Headings
    • HTML Paragraphs
    • HTML Text Formatting
    • HTML Styles
    • HTML Comments
    • HTML Styles - CSS
    • HTML Links
    • HTML Images
    • HTML Tables
    • HTML Lists
    • HTML Block and Inline Elements
    • HTML class Attribute
    • HTML Forms
    • HTML Media
  • CSS
    • Introduction of CSS
    • CSS Syntax
    • CSS Selectors
    • How To Add CSS
    • CSS Comments
    • CSS Colors
    • CSS Backgrounds
    • CSS Borders
    • CSS Margins
    • CSS Text
    • CSS Lists
    • CSS Tables
    • CSS Box Model
    • CSS Dimension
    • CSS Padding
    • CSS Border
    • CSS Margin
    • CSS Outline
    • CSS Cursors
    • CSS Overflow
    • CSS Units
    • CSS Visual Formatting
    • CSS Display
    • CSS Visibility
    • CSS Position
    • CSS Layers
    • CSS Float
    • CSS Alignment
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS Media Types
    • CSS Sprites
    • CSS Opacity
    • CSS Attribute Selectors
    • CSS Validation
    • CSS3 Border
    • CSS3 Gradients
    • CSS3 Text Overflow
  • JavaScript
    • JS Introduction
    • JS Getting Started
    • JS Syntax
    • JS Variables
    • JS Generating Output
    • JS Data Types
    • JS Operators
    • JS Events
    • JS Strings
    • JS Numbers
    • JS If Else
    • JS Switch Case
    • JS Arrays
    • JS Sorting Arrays
    • JS Loops
    • JS Functions
    • JS Objects
    • JS DOM Nodes
    • JS DOM Selectors
    • JS DOM Styling
    • JS DOM Get Set Attributes
    • JS DOM Manipulation
    • JS DOM Navigation
    • JS Window
    • JS Screen
    • JS Location
    • JS History
    • JS Navigator
    • JS Dialog Boxes
    • JS Timers
    • JS Date and Time
    • JS Math Operations
    • JS Type Conversions
    • JS Event Listeners
    • JS Event Propagation
    • JS Borrowing Methods
    • JS Hoisting Behavior
    • JS Closures
    • JS Strict Mode
    • JS JSON Parsing
    • JS Error Handling
    • JS Regular Expressions
    • JS Form Validation
    • JS Cookies
    • JS AJAX Requests
    • JS ES6 Features
  • jQuery
    • jQuery Introduction
    • jQuery Syntax
    • jQuery Selectors
    • jQuery Events
    • jQuery Show/Hide
    • jQuery Fade
    • jQuery Slide
    • jQuery Animation
    • jQuery Stop
    • jQuery Chaining
    • jQuery Callback
    • jQuery Get/Set
    • jQuery Insert
    • jQuery Remove
    • jQuery CSS Classes
    • jQuery Style Properties
    • jQuery Dimensions
    • jQuery Traversing
    • jQuery Ancestors
    • jQuery Descendants
    • jQuery Siblings
    • jQuery Filtering
    • jQuery Ajax
    • jQuery Load
    • jQuery Get/Post
    • jQuery No-Conflict
  • PHP
    • PHP Introduction
    • PHP Install
    • PHP Syntax
    • PHP Comments
    • PHP Variables
    • PHP Echo / Print
    • PHP Data Types
    • PHP Strings
    • PHP Constants
    • PHP Operators
    • PHP If...Else...Elseif
    • PHP Switch
    • PHP Loops
    • PHP Functions
    • PHP Arrays
    • PHP Superglobals
    • PHP Date and Time
    • PHP Include
    • PHP File Handling
    • PHP File Upload
    • PHP Cookies
    • PHP Sessions
    • PHP Filters
    • PHP Callback Functions
    • PHP JSON
    • PHP Exceptions
    • PHP What is OOP
    • PHP Classes/Objects
    • PHP Constructor
    • PHP Destructor
    • PHP Access Modifiers
    • PHP Inheritance
    • PHP Abstract Classes
    • PHP Interfaces
    • PHP Traits
    • PHP Static Methods
    • PHP Namespaces
  • SQL
    • Introduction to SQL
    • SQL Create Command
    • SQL ALTER Command
    • SQL Truncate Drop Rename
    • INSERT SQL command
    • UPDATE SQL command
    • DELETE SQL command
    • SQL COMMIT command
    • SQL ROLLBACK command
    • SQL GRANT and REVOKE Command
    • SQL WHERE clause
    • SQL LIKE clause
    • SQL ORDER BY Clause
    • SQL Group By Clause
    • SQL HAVING Clause
    • SQL DISTINCT keyword
    • SQL AND OR operator
    • SQL Constraints
    • SQL Functions
    • SQL JOIN
  • Python
    • Getting started with Python
    • Introduction to IDLE
    • Python 2.x vs. Python 3.x
    • Syntax Rules and First Program
    • Numbers and Math Functions
    • Python Operators
    • Python Variables
    • Python Modules and Functions
    • Python Input and Output
    • Data Types in Python
    • String in Python
    • String Functions in python
    • Lists in Python
    • Utilizing List Elements by Iterating
    • Deleting List Elements & other Functions
    • Dictionaries in Python
    • Functions for Dictionary
    • Tuples in Python
    • Relational and Logical Operators
    • Conditional Statements in Python
    • Looping in Python
    • Define Functions in Python
    • Python-Introduction to OOP
    • Object Oriented Programming in Python
    • Classes in Python
    • The concept of Constructor
    • Destructors - Destroying the Object in Python
    • Inheritance in Python
    • Access Modifers in Python
    • Types of Inheritance
    • Method Overriding in Python
    • Polymorphism
    • static Keyword
    • Operator Overloading Python
    • Introduction to Error Handling
    • Exception Handling: try and except
    • Exeption Handling: finally
    • Exception Handling: raise
    • File Handling
    • Reading and Writing File
    • Introduction to Multithreading
    • Threading Module in Python
    • Thread Object
    • Lock Object
    • RLock Object
    • Event Object
    • Timer Object
    • Condition Object
    • Barrier Object
    • __name__ Variable in Python
    • Iterable and Iterator
    • yield Keyword
    • Python Generators
    • Python Closures
    • Python Decorators
    • @property Decorator in Python
    • Assert Statement
    • Garbage Collection
    • Shallow and Deep Copy
    • Introduction to Logging
    • Configure Log LEVEL, Format etc
    • Python Logging in a file
    • Python Logging Variable Data
    • Python Logging Classes and Functions
    • Python MySQL Introduction
    • Create Database - Python MySQL
    • Create Table - Python MySQL
    • Insert Data in Table
    • Select Data from Table
    • Update data in Table
    • Delete data from Table
    • Drop Table from Database
    • WHERE clause - Python MySQL
    • Order By clause - Python MySQL
    • Limit clause - Python MySQL
    • Table Joins - Python MySQL
  • MongoDB
    • MongoDB Introduction
    • Overview of MongoDB
    • MongoDB vs SQL Databases
    • Advantages of MongoDB
    • When to go for MongoDB
    • Data Modelling in MongoDB
    • Is MongoDB really Schemaless?
    • Installing MongoDB on Windows and Linux
    • Datatypes in MongoDB
    • Create and Drop Database in MongoDB
    • MongoDB: Creating a Collection
    • CRUD Operations in MongoDB
    • Data Relationships in MongoDB
    • Indexing in MongoDB
    • Sorting in MongoDB
    • Aggregation in MongoDB
    • Data Backup and Restoration in MongoDB
    • Sharding in MongoDB
    • Java Integration with MongoDB
  • Elixir
    • Elixir Overview
    • Elixir Environment
    • Elixir Basic Syntax
    • Elixir Data Types
    • Elixir Variables
    • Elixir Operators
    • Elixir Pattern Matching
    • Elixir Decision Making
    • Elixir Strings
    • Elixir Char Lists
    • Elixir Lists and Tuples
    • Elixir Keyword Lists
    • Elixir Maps
    • Elixir Modules
    • Elixir Aliases
    • Elixir Functions
    • Elixir Recursion
    • Elixir Loops
    • Elixir Enumerables
    • Elixir Streams
    • Elixir Structs
    • Elixir Protocols
    • Elixir File I/O
    • Elixir Processes
    • Elixir Sigils
    • Elixir Comprehensions
    • Elixir Typespecs
    • Elixir Behaviours
    • Elixir Errors Handling
    • Elixir Macros
    • Elixir Libraries
  • TypeScript
    • TypeScript Overview
    • Install TypeScript
    • First TypeScript Program
    • Type Annotation
    • TypeScript Variable
    • TypeScript Data Type Number
    • TypeScript Data Type String
    • TypeScript Data Type Boolean
    • TypeScript Arrays
    • TypeScript Tuples
    • TypeScript Enum
    • TypeScript Union
    • TypeScript Any Data Type
    • TypeScript Void Data Type
    • TypeScript Never Data Type
  • Home
  • Getting started with Python
  • Introduction to IDLE
  • Python 2.x vs. Python 3.x
  • Syntax Rules and First Program
  • Numbers and Math Functions
  • Python Operators
  • Python Variables
  • Python Modules and Functions
  • Python Input and Output
  • Data Types in Python
  • String in Python
  • String Functions in python
  • Lists in Python
  • Utilizing List Elements by Iterating
  • Deleting List Elements & other Functions
  • Dictionaries in Python
  • Functions for Dictionary
  • Tuples in Python
  • Relational and Logical Operators
  • Conditional Statements in Python
  • Looping in Python
  • Define Functions in Python
  • Python-Introduction to OOP
  • Object Oriented Programming in Python
  • Classes in Python
  • The concept of Constructor
  • Destructors - Destroying the Object in Python
  • Inheritance in Python
  • Access Modifers in Python
  • Types of Inheritance
  • Method Overriding in Python
  • Polymorphism
  • static Keyword
  • Operator Overloading Python
  • Introduction to Error Handling
  • Exception Handling: try and except
  • Exeption Handling: finally
  • Exception Handling: raise
  • File Handling
  • Reading and Writing File
  • Introduction to Multithreading
  • Threading Module in Python
  • Thread Object
  • Lock Object
  • RLock Object
  • Event Object
  • Timer Object
  • Condition Object
  • Barrier Object
  • __name__ Variable in Python
  • Iterable and Iterator
  • yield Keyword
  • Python Generators
  • Python Closures
  • Python Decorators
  • @property Decorator in Python
  • Assert Statement
  • Garbage Collection
  • Shallow and Deep Copy
  • Introduction to Logging
  • Configure Log LEVEL, Format etc
  • Python Logging in a file
  • Python Logging Variable Data
  • Python Logging Classes and Functions
  • Python MySQL Introduction
  • Create Database - Python MySQL
  • Create Table - Python MySQL
  • Insert Data in Table
  • Select Data from Table
  • Update data in Table
  • Delete data from Table
  • Drop Table from Database
  • WHERE clause - Python MySQL
  • Order By clause - Python MySQL
  • Limit clause - Python MySQL
  • Table Joins - Python MySQL
Home >> python >> Numbers and Math Functions

Numbers and Math Functions

Welcome to another tutorial, here you will learn about Numbers and various Math functions available in python language. 

In handling numbers, you will learn the commonly used math operators and how you can use them to perform various operations in python. You will also, learn about shortcuts referred to as functions, which help calculate some of the complex mathematical expressions such as sine/cosine, factorials, power, and so on.

As we begin, I’ll recommend you leave your IDLE open as you are reading the instructions here; so you can practice simultaneously.

 

Numbers  

There 6 basic mathematical operators in Python. 

  • Addition
  • Subtraction
  • Multiplication
  • Division
  • Modulo
  • Power

You must be familiar with most of the operators mentioned above apart from the modulo operator. In the course of this tutorial, you will learn how the modulo operator works.

 

Addition  

This is simply the addition of numbers. Now, let’s see how this actually works, so open your IDLE and type a number, then add the + sign and add another number to the first one, then hit the enter key. Check the example below:

>>> 10+11
21

Once the enter key is pressed, the answer will appear below the written code.

You can try out more examples with different numbers and the addition operator. 

 

Subtraction 

Its operation is quite similar to addition in terms of syntax. All you need to do is to use the – sign and with any random number. Check out the example below:

Example: We used 89.33 and 23.67, which gave the output of 65.55.

 

Multiplication 

For this operator, you will use the * ( also known as asterisk). So you can try it out. Check out the example below. 

Division 

For this operator, the / sign is used. You can use it with any set of random numbers. Check out the example below to better understand how this works. 

>>> 16/2
8

Let’s try another set of numbers say 15 and 2. What do you think the answer will be? In mathematics, the answer should be 7.5, however, when this is tried in the IDLE, the compiler will return 7 as the answer. This is because if any operation performs on an integer, then the answer would be an integer. Just like in the example here, 15 and 2 are integers and the answer returned is 7, which is an integer. The reason why it turned out to be 7 instead of another number is that the answer is determined as the closest smaller integer to the original answer. The original answer in the example is 7.5 and the nearest integer to it is 7 and 8, but we have to pick the smaller one which is 7. This attribute is known as floor function. This is in Python.

Check out the example below for more clarification.

 

Power 

However, Python is the known programming language that has this type of operator. Other languages make use of pre-defined functions (or shortcuts as mentioned earlier) to compute this. Now, to make use of the operator, use two asterisks (i.e. **) between any two numbers. Check out the example below:

>>> 2**10
1024

At this stage, it is time for you to combine multiple operators and make use of them. It is advisable to use brackets, as this will help Python to understand what you want as the answer. For instance, rather than writing 2-9.0/2, write 2 – (9.0/2). This goes with the normal BODMAS, how it is used to solve mathematical expressions with multiple operators.

Modulo 

For this operator, the ‘%’ (percentage) sign is used. In Modulo operator, if used with two operands, returns the remainder as the answer. Check out the example below: 

12%2 = 0, since 2 perfectly divides . 

13%2 = 1, since dividing 13 with 2 leaves 1 as remainder. 

19%5 = 4, because, again, 19/5 leaves 4 as the remainder. 

 

It is also explained in the example below:

 

This is the end of the number operators, let's continue the next session with the math function.

 

Math Functions in Python 

In your course of study as a python programmer, it might be necessary for you to create a scientific calculator for a project or something else. There might need for you to evaluate complex mathematical operations, such as trigonometric operations, logarithmic operations, and so on. Aside from developing a calculator, you can face other situations where you need to use these functions. For instance, developing software for civil engineers to calculate various parameters of any structure of buildings or software for aerospace. In summary, complex mathematical operations are used in various real-life programs and software, therefore, there is a need to know about them and their uses.

Interestingly, in Python, pieces of codes have already been created (that is what is known as libraries), for several mathematical functions. These codes can be used without any difficulties, and there is no need to rewrite them again. All that is needed is just some key information to be able to use them. 

Function 

This can be described as a piece of code that may or may not take some value(s) as input, process it, and lastly may or may not return any value as output.

From the above figure, the input x is given to a function f and it is given some value f(x) as the output. However, in general, programming, depending on the purpose of the function, input, and output is completely optional, but a mathematical function needs both. 

Now, for example, in the trigonometric function sin(x), there must be some value of x to calculate and return the answer, and this establishes the reason why math functions are both input and output.

There are two types of pre-defined functions in python.

  • Inbuilt functions: They are functions that do not require any external code file and are known as Modules or Library Files. These functions are part of the python core and are typically built within the Python compiler. Therefore, is no difficulties importing them into our code.
  • The second type of function requires an external file or module before it can be used. The process in which these external files are used is called importing. As such, all you need to do is to import the file into your code and then use the functions already existing in that file.

Now let's check out some of these functions and how they are used in the mathematical operation.

 

Power (pow(x,y))

We have done something like this in previous sessions of this tutorial, but, that one is an operator and was used to calculate power, but this one is an inbuilt function. It is an alternative way to calculate power. So, you do not need to import any other library file or modules for such calculation. 

We already know that for power, the power function needs two numbers (i.e. inputs) to perform the operation; that is base and exponent, therefore we have to provide two numbers to the function. Check out the example below:

>>> pow(3,2)

Now, after the python compiler has ensured that all the syntax is correct, it then looks for the implementation of the pow function and uses it to find 32. The output is shown below:

In the example above, we cleared up what function is. However, it can be generalized as:

>>> functionName(input1, optionalInput2, optionalInput3, ...)

As said earlier. The values inside brackets which are separated by commas, as input to the functions, are called Arguments. That is, in the example of pow(x,y), 3 and 2 were the arguments. Also, we can have any other number of arguments in a function.

 

Absolute - abs(x)

The Absolute function also referred to as Modulus, is different from Modulo. The Modulus returns the non-negative value of the argument value. As such, the absolute value of any non-negative number is the same, but in the case of negative numbers, their positive value is returned.

Syntax:

>>> abs(-99.99)

Check out the example below:

Now let's try some functions where we have to import some modules(or library files).

 

Sine - sin(x)

You already know that sine is a trigonometric function, therefore it accepts just one value as an argument. For instance, x should be in radians, so should not mistake it with a degree. Note that we cannot use this function directly so that we will not get an error response; such as the one shown in the example below:

 

From the example above, the compiler doesn't know what it is supposed to do when it encounters the sin() function, because it was not defined and we tried using it. Therefore, for us to use it we have to import the Python math module, which consists of the implementation of the sin() function and it is what will guide the compiler to know what to do when it encounters the sin().

In the example below, what we want to do is known as importing a module and it can be done by using available ready-made functions. This is shown below.

>>> import math

Press the enter key, and that is it. So for us to use the sin() function, go to a new line and type this below:

>>> math.sin(3.14159)

Since the value of π is approximately 3.14159, then the answer would be near zero.

 

In Python other functions available inside the math module, such as the floor() function, exp() (exponential function), log() (logarithmic function), and many more. 

  • Prev
  • Next


-Advertisement-


DeveloperTutorial
[email protected] © 2022-2023 Developers Tutorial All rights reserved.

Follow Us

Facebook Twitter LinkedIn Printerest Reddit

Announcement

Its a big achivement for us, We make a partnership with TutorialWithExample.com for the better content of our users.

Still Need Help ?

Let us now about your issue and a Professional will reach you out.