![]() |
| ||||||||||||||||||
![]() |
| ||||||||||||||||||
|
It is easily possible to perform an operation with two operands of different datatypes. In this case,
the result gets the datatype of the left operand. Example:
a = 2 b = 1.7 # Result is a float Print (b+a) 3.7 # Result is an integer, 3.7 rounded to 4 Print (a+b) 4 This simple rule permits a large number of useful applications:
pi = 3.14159265359 Print (0.00+pi) 3.14 pi = 3.14159265359 a = 0+pi Print (a) 3 And another example to check if a rounded number is odd or even,
which considers the fact that the modulo operator '%' can only be applied to integers:
a = 7.6 if (0+a)%2 print 'a is odd' else print 'a is even' a is even
a = "2" b = 5+a Print (b) 7 a = 2 b = "5"+a Print (b) "52" a = 5 b = "2"*a Print (b) "22222" Remember to be careful when writing more complicated mathematical expressions:
Examples for calculating the average of two numbers:
If b and c are integers and you want to obtain a float result,
put the 0.5 on the left side:
a=0.5*(b+c) If b and c are high precision floats, put the
0.5 on the right side (or use 5e-1) to prevent it from reducing the precision of the result to one decimal:
a=(b+c)*0.5
| ||||||||||||||||||