In this section you will find following topics:
- Float and integer data structures
- Basic mathematic operations
- Define variables
int (signed integers) − They are often called just integers or ints, are positive or negative whole numbers with no decimal point.
Ex:
-1000
20
41
2
float (floating point real values) − Also called floats, they represent real numbers and are written with a decimal point dividing the integer and fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250).
Ex:
3.14
3.55454
-234.56
Python Arithmetic Operators | ||
+ | Adds two values together | 5 + 2 = 7 |
– | Subtracts the right operand from the left operand | 5 – 2 = 3 |
* | Multiplies the right operand by the left operand | 5 * 2 = 10 |
/ | Divides the left operand by the right operand | 5 / 2 = 2.5 |
% | Divides the left operand by the right operand and returns the remainder | 5 % 2 = 1 |
** | Calculates the exponential value of the right operand by the left operand | 5 ** 2 = 25 |
// | Performs integer division, in which the left operand is divided by the right operand and only the whole number is returned (also called floor division) | 5 // 2 = 2 |
BASIC ARITHMETIC OPERATIONS
1 2 3 4 5 6 7 8 9 10 |
In[2]: 5 + 6 Out[2]: 11 In[3]: 23-54 Out[3]: -31 12*4 Out[4]: 48 36/9 Out[5]: 4.0 28/5 Out[6]: 5.6 |
DEFINING VARIABLES
As we know variables from previous chapter, we use them for some mathematic operations too. I will show you different examples about working with variables during mathematic operations.
1 2 3 4 5 |
i=10 i Out[8]: 10 i*i*i Out[9]: 1000 |
As you see in table 1, it multiplies left operand by right operand. To change value of i variable, reassign a new value.
1 2 3 4 5 |
i Out[10]: 10 i=15 i Out[12]: 15 |
Now, let’s try to solve a basic equation and find the value of c variable, after defining them python will calculate the value automatically.
1 2 3 4 5 |
a=4 b=3 c=a + 2*b c Out[16]: 10 |
Be carefull when assigning variables:
- Variable names can not have a number as first letter
- If variable names are strings, there should not be any spaces
- Following symbols can not be used within a variable, only “_” is allowed: :'”,<>/?|\()!@#$%^&*~-+
- Modules, variables,methods pre-defined in Python can not be used as user variables.
Another feature in Python is you can interchange assigned variables. Check this example:
1 2 3 4 5 6 7 8 9 10 |
In[17]: a=4 In[18]: b=3 In[19]: a,b Out[19]: (4, 3) In[20]: In[20]: a,b=b,a In[21]: a Out[21]: 3 In[22]: b Out[22]: 4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
In[23]: a=78 In[24]: a+=2 In[25]: a Out[25]: 80 In[26]: a-=70 In[27]: a Out[27]: 10 In[28]: a+10 Out[28]: 20 In[29]: a Out[29]: 10 # AS YOU SAW ABOVE EX, += OR -= DECREASE OR INCREASE THE VALUE AND ASSIGN THE NEW # VALUE TO THE SAME VARIABLE BUT WITHOUT = SIGN IT WILL ONLY CALCULATE. In[31]: a*=40 In[32]: a Out[32]: 400 |
Leave A Comment