Python-Ref > Basic usage > Types > Type influence on operation result
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Type influence on operation result

For different types different behaviour is defined for an operation.
Expand/Shrink
Zdroj: (types2-1.py)
  1   i = 1  # small integers are commonly named i,j,k
  2   x = 0.05
  3   s1 = "hi"
  4   s2 = "2"
  5   s3 = '1.3'
  6   
  7   print i + x
  8   print s1 + s2  # + operator is used for string concatenation
  9   print s2 + s3
stdout:
1.05
hi2
21.3
Doba běhu: 21.1 ms
The type of operands also determines the type of the output of an operation.
Expand/Shrink
Zdroj: (types2-4.py)
  1   i1 = 1
  2   i2 = 2
  3   s1 = "1"
  4   s2 = "2"
  5   
  6   print type( i1), type( i2), type( i1 + i2)
  7   print type( s1), type( s2), type( s1 + s2)
stdout:
<type 'int'> <type 'int'> <type 'int'>
<type 'str'> <type 'str'> <type 'str'>
Doba běhu: 21.0 ms
Some operations defined for one type might be unsupported for other types.
Expand/Shrink
Zdroj: (types2-2.py)
  1   i = 1
  2   x = 0.05
  3   s1 = "hi"
  4   s2 = "2"
  5   s3 = '1.3'
  6   
  7   print i - x
  8   print s2 - s3
stdout:
0.95
stderr:
Traceback (most recent call last):
  File "types2-2.py", line 9, in ?
    print s2 - s3
TypeError: unsupported operand type(s) for -: 'str' and 'str'
Doba běhu: 21.0 ms
Mixing different types together usually does not work well. For example addition (+) of an integer and a string is not allowed.
Expand/Shrink
Zdroj: (types2-3.py)
  1   i = 1
  2   s = "2"
  3   
  4   print i + s
stderr:
Traceback (most recent call last):
  File "types2-3.py", line 5, in ?
    print i + s
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Doba běhu: 21.2 ms