Python 3home |
Introduction to Python
davidbpython.com
Math operators behave as you might expect.
var_int = 5
var2_float = 10.3
var3_float = var_int + var2_float # int plus a float: 15.3, a float
var4_float = var3_float - 0.3 # float minus a float: 15.0, a float
var5_float = var4_float / 3 # float divided by an int: 5.0, a float
Every operation or function call results in a predictable type.
With two integers, the result is integer. If a float is involved, it's always flot.
vari = 7
vari2 = 3
varf = 3.0
var3 = var * var2 # 35, an int.
var4 = var + var2 # 10.0, a float
When an integer is divided into another integer, the result is always a float.
var = 7
var2 = 3
var3 = var / var2 # 2.3333, a float
The exponentiation operator (**) raises its left operand to the power of its right operand and returns the result as a float or int.
var = 11 ** 2 # "eleven raised to the 2nd power (squared)"
print(var) # 121
var = 3 ** 4
print(var) # 81
The modulus operator (%) shows the remainder that would result from division of two numbers.
var = 11 % 2 # "eleven modulo two"
print(var) # 1 (11/2 has a remainder of 1)
var2 = 10 % 2 # "ten modulo two"
print(var2) # 0 (10/2 divides evenly: remainder of 0)
The plus operator (+) with two strings returns a concatenated string.
aa = 'Hello, '
bb = 'World!'
cc = aa + bb # 'Hello, World!'
Note that this is the same operator (+) that is used with numbers for summing. Python uses the type of the operands (values on either side of the operator) to determine behavior and result.
The "string repetition operator" (*) creates a new string with the operand string repeated the number of times indicated by the other operand:
aa = '!'
bb = 5
cc = aa * bb # '!!!!!!'
Note that this is the same operator (*) that is used with numbers for multiplication. Python uses the type of the operands to determine behavior and result.
Object types determine behavior.
int or float "added" to int or float: addition
tt = 5 # assign an integer value to tt
zz = 10.0 # assign a float value to zz
qq = tt + zz # compute 5 plus 10 and assign float 15.0 to qq
str "added" to str: concatenation
kk = '5' # assign a str value (quotes mean str) to kk
rr = '10.0' # assign a str value to rr
mm = kk + rr # concatenate '5' and '10.0'
# to construct a new str object, assign to mm
print(mm) # '510.0'
Again, object types determine behavior.
int or float "multipled" by int or float: multiplication
tt = 5 # assign an integer value to tt
zz = 10 # assign an integer value to zz
qq = tt * zz # compute 5 times 10 and assign integer 50 to qq
print(qq) # 50, an int
str "multiplied" by int: string repetition
aa = '5'
bb = 3
cc = aa * bb # '555'