You are on page 1of 10

Learners’ Module in Computational Science

TYPE CONVERSION, TYPE CASTING,


I/O and IMPORT 5
INTRODUCTION
In this lesson, you will learn the concept of type conversion and type casting. In a
nutshell, type conversion and type casting are different ways of changing an expression
from one data type to another. An example would be the conversion of an integer value
into a floating-point value or its textual representation as a string, and vice versa. Type
conversions can take advantage of certain features of type hierarchies or data
representations.

You will also learn how to wait for user input and display the information using
appropriate statements. Lastly, you will learn the import function.

INTENDED LEARNING OUTCOMES

Upon the completion of this lesson, you should be able to:

1. understand the importance of type conversion and type


casting in Python;

2. discuss the I/O and import functions in Python; and

3. write a Python program applying these concepts.

LESSON PROPER

Lesson 5: Type Conversion and Type Casting 54 | Page


Learners’ Module in Computational Science

TYPE CONVERSION

The process of converting the value of one data type (integer, string, float, etc.) to
another data type is called type conversion. Python has two types of type conversion.

1. Implicit Type Conversion


2. Explicit Type Conversion

Implicit Type Conversion

In Implicit type conversion, Python automatically converts one data type to another data
type. This process doesn't need any user involvement.

Let's see an example where Python promotes the conversion of the lower data type
(integer) to the higher data type (float) to avoid data loss.

Example 1: Converting integer to float


num_int = 123
num_flo = 1.23

num_new = num_int + num_flo

print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))

print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))

When we run the above program, the output will be:


datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>

Value of num_new: 124.23


datatype of num_new: <class 'float'>

In the above program,

 We add two variables num_int and num_flo, storing the value in num_new.

 We will look at the data type of all three objects respectively.

Lesson 5: Type Conversion and Type Casting 55 | Page


Learners’ Module in Computational Science

 In the output, we can see the data type of num_int is an integer while the data
type of num_flo is a float.

 Also, we can see the num_new has a float data type because Python always
converts smaller data types to larger data types to avoid the loss of data.

Now, let's try adding a string and an integer, and see how Python deals with it.

Example 2: Addition of string(higher) data type and integer(lower) datatype


num_int = 123
num_str = "456"

print("Data type of num_int:",type(num_int))


print("Data type of num_str:",type(num_str))

print(num_int+num_str)

When we run the above program, the output will be:


Data type of num_int: <class 'int'>
Data type of num_str: <class 'str'>

Traceback (most recent call last):


File "python", line 7, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

In the above program,

 We add two variables num_int and num_str.

 As we can see from the output, we got TypeError. Python is not able to use
Implicit Conversion in such conditions.

 However, Python has a solution for these types of situations which is known as
Explicit Conversion.

Explicit Type Conversion

In Explicit Type Conversion, users convert the data type of an object to required data
type. We use the predefined functions like int(), float(), str(), etc. to perform explicit type
conversion.

This type of conversion is also called typecasting because the user casts (changes) the
data type of the objects.

Syntax :

Lesson 5: Type Conversion and Type Casting 56 | Page


Learners’ Module in Computational Science

<required_datatype>(expression)

Typecasting can be done by assigning the required data type function to the expression.

Example 3: Addition of string and integer using explicit conversion


num_int = 123
num_str = "456"

print("Data type of num_int:",type(num_int))


print("Data type of num_str before Type Casting:",type(num_str))

num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))

num_sum = num_int + num_str

print("Sum of num_int and num_str:",num_sum)


print("Data type of the sum:",type(num_sum))

When we run the above program, the output will be:


Data type of num_int: <class 'int'>
Data type of num_str before Type Casting: <class 'str'>

Data type of num_str after Type Casting: <class 'int'>

Sum of num_int and num_str: 579


Data type of the sum: <class 'int'>

In the above program,

 We add num_str and num_int variable.

 We converted num_str from string(higher) to integer(lower) type


using int() function to perform the addition.

 After converting num_str to an integer value, Python is able to add these two
variables.

 We got the num_sum value and data type to be an integer.

Key Points to Remember

1. Type Conversion is the conversion of object from one data type to another data
type.

Lesson 5: Type Conversion and Type Casting 57 | Page


Learners’ Module in Computational Science

2. Implicit Type Conversion is automatically performed by the Python interpreter.

3. Python avoids the loss of data in Implicit Type Conversion.

4. Explicit Type Conversion is also called Type Casting, the data types of objects are
converted using predefined functions by the user.

5. In Type Casting, loss of data may occur as we enforce the object to a specific data
type.

PYTHON OUTPUT USING PRINT() FUNCTION

We use the print() function to output data to the standard output device (screen). We
can also output data to a file, but this will be discussed later.
An example of its use is given below.

print('This sentence is output to the screen')


Output

This sentence is output to the screen


Another example is given below:
a=5
print('The value of a is', a)
Output

The value of a is 5

In the second print() statement, we can notice that space was added between
the string and the value of variable a. This is by default, but we can change it.
The actual syntax of the print() function is:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Here, objects are the value(s) to be printed. The sep separator is used between the
values. It defaults into a space character. After all values are printed, end is printed. It
defaults into a new line.

The file is the object where the values are printed and its default value
is sys.stdout (screen). Here is an example to illustrate this.
print(1, 2, 3, 4)

Lesson 5: Type Conversion and Type Casting 58 | Page


Learners’ Module in Computational Science

print(1, 2, 3, 4, sep='*')
print(1, 2, 3, 4, sep='#', end='&')
Output
1234
1*2*3*4
1#2#3#4&

Output formatting

Sometimes we would like to format our output to make it look attractive. This can be
done by using the str.format() method. This method is visible to any string object.
>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10
Here, the curly braces {} are used as placeholders. We can specify the order in which they
are printed by using numbers (tuple index).
print('I love {0} and {1}'.format('bread','butter'))
print('I love {1} and {0}'.format('bread','butter'))
Output
I love bread and butter
I love butter and bread
We can even use keyword arguments to format the string.
>>> print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'John'))
Hello John, Goodmorning
We can also format strings like the old sprintf() style used in C programming language.
We use the % operator to accomplish this.
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457

PYTHON INPUT
Up until now, our programs were static. The value of variables was defined or hard coded
into the source code. To allow flexibility, we might want to take the input from the user.
In Python, we have the input() function to allow this. The syntax for input() is:
input([prompt])
where prompt is the string we wish to display on the screen. It is optional.

Lesson 5: Type Conversion and Type Casting 59 | Page


Learners’ Module in Computational Science

>>> num = input('Enter a number: ')


Enter a number: 10
>>> num
'10'
Here, we can see that the entered value 10 is a string, not a number. To convert this into
a number we can use int() or float() functions.
>>> int('10')
10
>>> float('10')
10.0

This same operation can be performed using the eval() function. But eval takes it further.
It can evaluate even expressions, provided the input is a string
>>> int('2+3')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '2+3'
>>> eval('2+3')
5

PYTHON IMPORT

When our program grows bigger, it is a good idea to break it into different modules.

A module is a file containing Python definitions and statements. Python modules have a
filename and end with the extension .py.

Definitions inside a module can be imported to another module or the interactive


interpreter in Python. We use the import keyword to do this.

For example, we can import the math module by typing the following line:
import math
We can use the module in the following ways:
import math
print(math.pi)
Output

3.141592653589793

Lesson 5: Type Conversion and Type Casting 60 | Page


Learners’ Module in Computational Science

Now all the definitions inside math module are available in our scope. We can also
import some specific attributes and functions only, using the from keyword. For example:

>>> from math import pi


>>> pi
3.141592653589793

While importing a module, Python looks at several places defined in sys.path. It is a list
of directory locations.
>>> import sys
>>> sys.path
['',
'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']

SUMMARY

 Python has two types of type conversion: Implicit Type Conversion and Explicit Type
Conversion.
 In Implicit type conversion, Python automatically converts one data type to another
data type.
 In Explicit Type Conversion, users convert the data type of an object to required data
type.
 Use the print() function to output data to the standard output device (screen).
 Use the input() function to capture the data from users.
 We use the import() function to import external modules into our program.

Lesson 5: Type Conversion and Type Casting 61 | Page


Learners’ Module in Computational Science

SELF-LEARNING ASSESSMENT

Let us see how much you have learned from this lesson.
Answer the following questions.

TEST 1. Essay: Based on your understanding, discuss the following items using your own
words. Each item is 10 points.

1. What is the difference between explicit and implicit type conversion?

2. Why do you need to use the import() function?

Lesson 5: Type Conversion and Type Casting 62 | Page


Learners’ Module in Computational Science

ENRICHMENT ACTIVITY

Write a Python program that will convert any inputted values to integer.

Lesson 5: Type Conversion and Type Casting 63 | Page

You might also like