Using math in python

Math in Python

The Python distribution includes the Python interpreter, a very simple development environment, called IDLE, libraries, tools, and documentation.

Python is preinstalled on many (if not all) Linux and Mac systems, but it may be an old version.

Read Also: Python Program to Find Number of Rectangles in N*M Grid

Calculator

To begin using the Python interpreter as a calculator, simple type python in the shell.

>>> 2 + 2
4

>>> 4 * 2
8

>>> 10 / 2
5

>>> 10 - 2
8

Counting with variables

Put in some values into variables to count the area of a rectangle

>>> length = 2.20
>>> width = 1.10
>>> area = length * width
>>> area
2.4200000000000004

Counter

Counters are useful in programming to increase or decrease a value everytime it runs.

>>> i = 0
>>> i = i + 1
>>> i
1
>>> i = 1 + 2
>>> i
3

Counting with a While Loop

Here is an example showing when it’s useful to use counters

>>> i = 0
>>> while i < 5:
...     print i
...     i =  i + 1
... 
0
1
2
3
4

The program counts from 0 to 4. Between the word while and the colon, there is an expression that at first is True but then becomes False.

As long as the expression is True, the following code will run.

The code that needs to be run has to be indented.

The last statement is a counter that adds 1 to the value for everytime the loop runs.

Multiplication table

Making a multiplication table in Python is simple.

table = 8
start = 1
max = 10
print "-" * 20
print "The table of 8"
print "-" * 20
i = start
while i <= max:
    result = i * table
    print i, " * ", table, " =" , result
    i = i + 1
print "-" * 20
print "Done counting..."
print "-" * 20

>>Output:

——————–
The table of 8
——————–
1 * 8 = 8
2 * 8 = 16
3 * 8 = 24
4 * 8 = 32
5 * 8 = 40
6 * 8 = 48
7 * 8 = 56
8 * 8 = 64
9 * 8 = 72
10 * 8 = 80
——————–
Done counting…

Try More:

Nr4 And Nr7

Leave a Reply

Your email address will not be published. Required fields are marked *