Chapter 6-                       Type Casting and Type Conversion In Python
Type Conversion refers to the process of changing the value of one programming data type to another programming data type. Think of dividing two integers that lead to decimal numbers. In this case, it is necessary to convert force the conversion of an integer into a float number. Python programming language has two types of conversion: implicit type conversion and explicit conversion.
Implicit Conversion Type
In this case, Python automatically changes one data type to another data type, and the process does not require user involvement. Implicit type conversion is mainly used with the intent of avoiding data loss.
Example
Conversion of Integer to Float
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
number_int=451
number_flo=4.51
number_new=number_int+number_flo
print(“the type of data of number_int-“, type(number_int))
print(“the type of data of number_flo-“, type(number_flo))
print(“value of number_new-“number_new)
print(“type of data of number_new-“, type(number_new))
The programming is adding two variables one of data type integer and the other float and storing the value in a new variable of data type float. Python automatically converts small data types into larger data types to avoid prevent data loss. This is known as implicit type conversion.
Python programming language cannot, however, convert numerical data types into string data type or string data type into numerical data type implicitly. Attempting such a conversion will generate an error.
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
number_int=432        #lower data type
number_str=”241”        #higher data type
print(“The type of data of number_int-“, type(number_int))
print(“The type of data of number_str-“, type(number_str))
print(number_int+number_str)
Challenge: Can you guess why this is occurring? Python interpreter is unable to understand whether we want concatenation or addition precisely. When it assumes the concatenation, it fails to locate the other string. When it assumes the addition approach, it fails to locate the other number. The solution to the error above is to have an explicit type conversion.
Explicit Conversion
Here, programmers convert the data type of a named programming object to the needed data type. Explicit conversion is attained through the functions float(), int(), and str() among others.
The syntax for the explicit conversion is:
(needed_datatype) (expression)
Illustration
Summing of a string and integer using by using explicit conversion
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
number_int=431
number_str=”231”
print(“Type of data of number_int-“, type(number_int))
print(“Type of data number_str prior to Type Casting-“, type(number_str))
number_str=int(number_str)
number_sum=number_int+number_str
print(“Addition of number_int and number_str-“, number_sum)
print(“Type of data of the sum-“, type(number_sum))
One thing that we need to remember here is that running this program will display the data types and sum and display an integer and string.
In the above program, we added a number_str and number_int variable. We then converted number_str from string(higher data type) to integer(lower data type)type using int() function to perform the summation. Python manages to add the two variables after converting number_str to an integer value. The number_sum value and data type are an integer data type.
The conversion of the object from one data type to another data type is known as type conversion. The python interpreter automatically performs implicit type conversion. Implicit type conversion intends to enable Python to avoid data loss. Typecasting or explicit conversion happens when the data types of objects are converted using the predefined function by the programmer. Unlike implicit conversion, typecasting can lead to data loss as we enforce the object to a particular data type.
The previous explicit conversion/typecasting can be written as:
number_int=431                #int data type
number_str=”231”                #string data type
number_str=int(number_str)            #int function converting string into int data type
number_sum=number_int+number_str    #variable number_sum
print(“Addition of number_int and number_str-“, number_sum)
Note: Explicit conversion/Type casting requires some practice to master, but it is easy. The trick is that the variable name to convert=predefined function for the desired data type (variable name to convert)
Follow up work:
Use the knowledge of typecasting/explicit data conversion to write a program to compute the sum of:
a.    score_int=76
score_str=”61”
b.    count_str=231
count_str=”24”
Use the knowledge of typecasting/explicit data conversion to write a program find the product of:
c.    number_int=12
number_str=”5”
d.    odds_int=6
odds_str=”2”
e.    minute_int=45
minute_str=”7”
Formatting Output
It may become necessary to play around with the layout of the output to make it appealing, formatting. The str.format() method is used to format output and is visible/accessible to any string object.
Example:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
lucy=3; brian= 7
print(‘The age of lucy is {} and brian is {}’.format(lucy,brian))
Note: The expected output is “The age of lucy is 3 and brian is 7”.
Giving it a try
Given print(‘She studies {0} and {1}’.format(‘Health’, ‘ICT’))
a.                  Rewrite the Python program to display “She studies ICT and Health”.
b.    Rewrite the Python program to display “She studies Health and Health”
c.     Rewrite the Python program to display “She studies ICT and ICT”.
Challenge: of was in real life the concept above (tuple index/specifying order of display) may be useful where you don’t have to rewrite entire lines of codes. For instance, think of a website that asks users to register for an account but begins with asking surname before the first name. 
Now assume that the ICT team has recommended that the users should be asked their first name first before the surname. Write a simple Python simulation program to demonstrate how the tuple index concept can increase efficiency, readability, and maintainability of code.
Input in Python
So far our Python programs have been static meaning that we could not key in as everything was given to the variable before running the program. In real life, applications allow users to type in values to a program and wait for it to act on the values given. The input function (input()) is used to accept the information of benefits from the user.
Syntax/way of using it in Python
variable name=input(‘option to include a message to the user on what is happening/can leave it out’).
Example:
For this example, we are going to work on a program that accepts numerals from users
number=input(‘Type your number here:’)    #Will display: Type a name here:
Python interpreter at this stage will treat any numbers entered as a string. For Python interpreter to interpret the keyed-in number as the number, we must convert the number using type conversion functions for names which are int() and float().
To convert the number into an integer, after input from the user does the following:
int(‘number’)
To convert the number into afloat, after input from the user does the following:
float(‘number’)
Giving it a try
a.                  Write a Python program to accept numerical data from users for their age, to capture the age of a user
b.    Use explicit type conversion to convert the string entered into a floating value in a.
c.     Write a Python program to accept salary figure input from users.
d.    Use explicit type conversion to convert the string into a floating value in c.
e.     Write a program to accept the count of students/number of students’ in a class from users. 
f.       Use explicit type conversion to convert the string entered into an integer data type in e.
Import in Python
The programs we have run so far are small, but in reality, an application can be hundreds to ten thousand lines of code. In this case, an extensive program is broken into smaller units called modules. These modules are related but on different files usually ending with the extension .py. 
Python allows the importing of a module to another module using the keyword import. Analogy: You probably have some of your certificates scanned and stored in your Google drive, have your notebook in your desk, have a passport photo in your phone external storage, and a laptop in your room. When writing an application for an internship, you will have to find a way of accessing all these resources, but in normal circumstances, you will only work with a few even though all of them are connected. The same is true for programs.
Example:
Assume we need to access the math pi that is a different module. The following program will illustrate:
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
import.math        #referencing to the contents of math module
print(math.pi)      #Now utilizing the features found in that referenced math
Namespace in Python
When we start the Python interpreter, a namespace containing all inbuilt names is created as long the workspace remains application is active. Inbuilt functions such as print() and id() exist throughout the program. 
Built-in Namespace: These are functions, methods, and associated data that immediately accessible as soon the Python interpreter loads and as such are available to each instance and area of the workspace.
Variable Scope
Even though there might be several unique namespaces specified, it may not be possible to access all of the namespaces given because of scope. The concept of range refers to a segment of the program from where we access the namespace directly without any prefix. The following are the scope types:
i.        Extent containing local names, current function.
ii.    Scope containing global names, the range of the module.
iii.  Scope containing built-in names of the outermost scope.
Type Conversion refers to the process of changing the value of one data type to another data type. Think of dividing two integers that lead to decimal numbers. In this case, it is necessary to convert force the conversion of an integer into a float number. Python programming language has two types of conversion: implicit type conversion and explicit conversion. In Python input and output (I/O) tasks are performed by inbuilt functions. The print() performs output/display, while input() performs input tasks.