Maths in Python
Maths in Python - Bytesize Python
Source of Image
Why do maths in python?
Python can be used to solve many different types of maths problems. When starting out it may seem pointless to learn how to calculate in python when you can do the sums yourself, but in the long run, computers can solve maths problems more efficiently and accurately than humans. Here we will cover the basics.
Simple calculations
In python, simple calculations can be calculated on the shell window. Python will deliver the answer straight away, meaning the 'print()' function will not be needed.(you cant divide by 0, so an error will be displayed)
- is used for subtraction
* is used for multiplication
/ is used for division
% gives you the remainder of a division
** used to represent exponents
Order of operations
If python is given a multistep problem, it will follow the order of operations (BIDMAS /BODMAS /PEMDAS /BEDMAS ) Inserting brackets/parentheses can be used to instruct which part of the sum, python needs to do first.
Storing answers in variables
If variables are assigned number values, you can use them within sums. When a variable is assigned to a sum, the answer will be what the variable is assigned to, not the whole sum.
The following program adds together apples and oranges, and puts the answer into the variable fruits.
You can change the value of the apples and oranges later, but remember to assign the variable fruits again, after you have changed them, or else fruits will still be the sum previous values.
Random Numbers
To pick a random number, you first need to load the 'randint' function into python. To do this, use the 'import' command. The 'randint' function is already programmed to pick a random integer(You can find out more about integers and other data types at 'Data Types in Python')