Page - 43 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 43 -
Text of the Page - 43 -
2.2 Variables,ObjectsandExpressions 43
In [1]: x = 2
In [2]: y = 4.0
In [3]: s = βhelloβ
In [4]: type(x) # ...object named x is an integer
Out[4]: int
In [5]: type(y) # ...object named y is a float
Out[5]: float
In [6]: type(s) # ...object named s is a string
Out[6]: str
Type Conversion Objects may be converted from one type to another if it makes
sense. If, e.g.,x is thenameofanintobject,writing
In [1]: x = 1
In [2]: y = float(x)
In [3]: y
Out[3]: 1.0
shows thaty thenbecomesa floatingpoint representationofx. Similarly,writing
In [1]: x = 1.0
In [2]: y = int(x)
In [3]: y
Out[3]: 1
illustrates thatybecomesan integer representationofx. Note that theint function
rounds down, e.g., y = int(1.9) also makes y become the integer 1. Type
conversionmayalsooccurautomatically.
2.2.5 AutomaticTypeConversion
What if weaddafloat object to an intobject?We could,e.g.,write
In [1]: x = 2
In [2]: x = x + 4.0
In [3]: x
Out[3]: 6.0
What happens here, is that automatic type conversion takes place, and the new x
will have thevalue6.0, i.e., refer to anobjectof typefloat.
Programming for Computations β Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
- Title
- Programming for Computations β Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Volume
- Second Edition
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2020
- Language
- English
- License
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 356
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik