Friday, November 29, 2019

Using Python as a Calculator

Python shell can be used as mathematical calculator. Let’s take a look and understand how it works as a calculator.

First we have to start the Python shell and wait for the primary prompt “>>>” which is the symbol of three greater than sign. Once the Python Shell is ready (which shall not take long) with the prompt we can commence using some simple Python commands. 

Numbers


The Python interpreter serves as a simple mathematical calculator. We can type any expression, which will be calculated and the result will be displayed with one Enter. 

Syntax:

Operand  Operator  Operand

Example 1:

>>> 2 + 2
4
>>>

Parentheses can be used to group more than one operand

Example 2:

>>> 2 + 2
4
>>> 50 +5 * 2
60
>>> (50-5*2)/4
10.0 #Division always returns a floating point
>>> 9/5
1.8
>>>

The integer numbers like 1,2,3,4,9,5, have int data type while the numbers with the fractional part (e.g. 10.0, 1.8) are of float data type. As I have mentioned above in the code block that Division (/) always returns a float value irrespective of the decimal part in the result even if the result is whole number Python console will give a decimal point with zero. Though we can disregard the decimal part using double slash also called Floor Division (//) operator. and to calculate the reminder we can use modulus (%) operator. Below code block displays the examples of the same. Let's have a look.

Example 3:

>>> 9/5 #standard division returns a float
1.8
>>> 9//5 #floor division discards the fractional part
1
>>> 9%5 #the % operator returns the remainder of the division
4
>>> 1*5+4 #result * divisor + remainder
9
>>>

To calculate power for any number the symbol used is  double multiplication symbol **

Example 4:

>>> 5 ** 2 #Squared
25
>>>5 ** 4 #5 raise to the power 4
625
Python shell allows you to create variables on the shell and use them later on the script,

Note 1: No result will be displayed on the next line, rather next interactive prompt will be displayed.

Example 5:

>>> length =10
>>> width =5
>>> length * width
50
>>>

Note 2: if you will try to access a variable without declaring it, then an error will occur and it will be displayed on the prompt.

Example 6:


>>> m * 5 #Trying to access an undefined variable m
Traceback (most recent call last):
File "", line 1, in
m*5
NameError: name 'm' is not defined
>>>

Note 3: Mixed Data Type Operands can be used. but the int operand will be treated as float  operand because float operands always gives float result as discussed earlier.

Example 7:

>>> 4*5.5-8.1
13.9
>>>

Python shell can be used to Work with Strings. Click Here

No comments:

Post a Comment