Page 389 - Ai_417_V3.0_C9_Flipbook
P. 389
print(result) # Output: 7.0
print(type(result)) # Output: <class 'float'>
2. Explicit Type Conversion: Explicit type conversion, also known as type casting, is performed by the
programmer using predefined functions to convert one data type to another. This is necessary when you
need to ensure that a specific type is used for an operation or when Python does not automatically convert
the types.
Common Functions for Explicit Type Conversion
• int(): Converts a value to an integer.
• float(): Converts a value to a float.
• str(): Converts a value to a string.
• bool(): Converts a value to a boolean.
• list(), tuple(), set(), etc.: Convert to respective data structures.
Examples:
>>> float(12)
12.0
>>> int(15.5)
15
>>> str(12)
'12'
>>> int(True)
1
>>> bool(0)
False
You can get the data type of any object by using type( ) function. For example,
>>> type(10)
<class 'int'>
>>> type("abc")
<class 'str'>
>>> type(14.5)
<class 'float'>
Comments in Python
Comments are used to increase the readability of the code. We use them to give a proper understanding of the
code in simple English statements. They are completely ignored by the Python interpreter. It is always a good
practice to add comments in your code so that if anybody in the future wishes to understand or modify your
code, then through comments it will be easy to interpret the instructions. There are two different ways of writing
comments in Python. Let us learn about them in detail.
Single Line Comment
Single line comment starts with hash symbol # followed by the text to be written as a comment that lasts until
the end of the line.
Introduction to Python 387

