PDA Assignments
  • Python For Data Analytics
    • 1.Python
      • 1.Python Documents
        • 1.Data Types
        • 2.Variables In Python
        • 3.Operators In Python
        • 4.User Input In Python
        • 5.TypeCasting In Python
        • 6.Strings In Python
        • 7.Conditional Statements In Python
        • 8.Branching using Conditional Statements and Loops in Python
        • 9.Lists In Python
        • 10.Sets In Python
        • 11.Tuples In Python
        • 12.Dictionary In Python
        • 13.Functions In Python
        • 14.File Handling In Python
        • 15.Numerical Computing with Python and Numpy
      • 2.Python Assignments
        • Data Type & Variables
        • Operators Assignment
        • User Input & Type Casting
        • Functions- Basic Assignments
        • String Assignments
          • String CheatSheet
        • Conditional Statements Assignments
        • Loops Assignments
        • List Assignments
          • List Cheatsheet
        • Set Assignments
          • Sets Cheatsheet
        • Dictionary Assignments
          • Dictionary Cheatsheet
        • Function Assignments
        • Functions used in Python
      • 3.Python Projects
        • Employee Management System
        • Hamming distance
        • Webscraping With Python
          • Introduction To Web Scraping
          • Importing Necessary Libraries
          • Basic Introduction To HTML
          • Introduction To BeautifulSoup
          • Flipkart Web Scraping
            • Scraping Step By Step
        • Retail Sales Analysis
        • Guess the Word Game
        • Data Collection Through APIs
        • To-Do List Manager
        • Atm-functionalities(nested if)
        • Distribution of Cards(List & Nested for)
        • Guess the Number Game
      • 4.Python + SQL Projects
        • Bookstore Management System
    • 2.Data Analytics
      • 1.Pandas
        • 1.Pandas Documents
          • 1.Introduction To Pandas
          • Reading and Loading Different Data
          • 2.Indexing and Slicing In Pandas
          • 3.Joining In Pandas
          • 4.Missing Values In Pandas
          • 5.Outliers In Pandas
          • 6.Aggregating Data
          • 7.DateTime In Pandas
          • 8.Validation In Pandas
          • 9.Fetching Data From SQL
          • 10. Automation In Pandas
          • 11.Matplotlib - Data Visualization
          • 12. Seaborn - Data Visualization
          • 13. Required Files
        • 3.Pandas Projects
          • Retail Sales Analysis
            • Retail Sales Step By Step
          • IMDB - Dataset Analysis - Basic
        • 2. Pandas Assignments
          • 1. Reading and Loading the Data
          • 2. Data frame Functions and Properties
          • 3. Series - Basic Operations
          • 4. Filtering in Pandas
          • 5. Advance Filtering
          • 6. Aggregate Functions & Groupby
          • 7. Pivot Tables
          • 8. Datetime
          • 9. String Functions
Powered by GitBook
On this page
  • What is Type-Casting?
  • Functions used for Type-Casting
  • int(): Converting any Data Type to integer data type
  • float(): Converting any Data Type to float data type
  • str(): Converting any Data Type to string data type
  • bool(): Converting any Data Type to boolean data type
  • Converting Zero Values to boolean gives False:
  • Converting Non Zero Values to boolean gives True:
  • Why do we use Type Casting ?
  1. Python For Data Analytics
  2. 1.Python
  3. 1.Python Documents

5.TypeCasting In Python

What is Type-Casting?

Type Casting is the method to convert the variable data type into a certain data type in order to the operation required to be performed by users.

In more simple terms, type casting means converting operand's data type to another data type.

Functions used for Type-Casting

There are 4 important Functions used for Data Type Conversion:

  • int() - int() converts any data type to integer data type.

  • float() - float() converts any data to float data type.

  • str() - str() converts any data type to string data type

  • bool() - bool() converts any data type to boolean data type

int(): Converting any Data Type to integer data type

Converting float value in integer:

In [13]:

float_var = 2.5
int_var = int(float_var) 
print(int_var)
print(type(int_var))
2
<class 'int'>

Converting boolean value in integer:

In [2]:

bool_var = True
int_var = int(bool_var)
print(int_var)
1

In [3]:

bool_var = False
int_var = int(bool_var)
print(int_var)
0

Note:Converting boolean value into integer will give 1 if boolean is True and 0 if false. In more simpler terms True means 1 and False means 0.

Converting string value in integer:

Note:String can only be converted in integer , if it is possible mathematically or if the string is a number. This means that string "ConsoleFlare" can not be converted to integer data type as it is not possible, but string "123" can be converted to 123.See Below:

Characters as a String: Will not convert

In [4]:

string_var = "ConsoleFlare"
int_var = int(string_var)
print(int_var)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-88b966b818d7> in <module>
      1 string_var = "ConsoleFlare"
----> 2 int_var = int(string_var)
      3 print(int_var)

ValueError: invalid literal for int() with base 10: 'ConsoleFlare'

Integer as a String: Will convert

In [5]:

string_var = "123"
int_var = int(string_var)
print(int_var)
123

float(): Converting any Data Type to float data type

Converting integer data type in float:

In [6]:

int_var = 2
float_var = float(int_var) 
print(float_var)
2.0

Converting boolean data type in float:

In [8]:

int_var = False
float_var = float(int_var) 
print(float_var)
0.0

Converting String data type in float:

Note:String can only be converted in float , if it is possible mathematically or if the string is a number. This means that string "ConsoleFlare" can not be converted to integer data type as it is not possible, but string "123.5" can be converted to 123.5.See Below:In [14]:

string_var = "123.5"
float_var = float(string_var)
print(float_var)
print(type(float_var))
123.5
<class 'float'>

Note:Can we convert a String Float (float number in string) in integer data type directly?In [15]:

string_var = "123.5"
int_var = int(string_var)
print(int_var)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-15-9ccd5336658c> in <module>
      1 string_var = "123.5"
----> 2 int_var = int(string_var)
      3 print(int_var)

ValueError: invalid literal for int() with base 10: '123.5'

This will give an error, We cannot convert String float Directly into an integer data type. But there is a WorkAround that we can follow.

  • Convert string float to float data type.

  • Convert the float value to integer.

In [16]:

string_var = "123.5"
float_var = float(string_var)
int_var = int(float_var)
print(int_var)
123

str(): Converting any Data Type to string data type

Note:str() can convert data type of any variables or values to string data type with no obstacles and no workaround needed.In [17]:

int_var = 4
string_var = str(int_var)
print(string_var)
print(type(string_var))
4
<class 'str'>

bool(): Converting any Data Type to boolean data type

To Convert Data type of a particular operand in boolean , we must know what that particular value represents , does it represent 0(False) or 1(True).

While converting any value in boolean , outcome will be either non-zero value which is True or zero-value which is false.

Zero-Values: Zero-values are the values that is equal to nothing or 0. Because 0 in its total sense is nothing.

Zero-values: 0 , "" , '','''''' and more where the value is nothing.

Non Zero-Values: Non Zero-values are the values that is not equal nothing. Any value that is not zero or nothing is Non-Zero Value.

Non - Zero-values: "0",123,123.5," "(there is a space between quotes), "12321","ConsoleFlare"

Converting Zero Values to boolean gives False:

In [18]:

value = 0
bool_value = bool(value)
print(bool_value)
False

In [19]:

value = ""
bool_value = bool(value)
print(bool_value)
False

In [20]:

value = ''''''
bool_value = bool(value)
print(bool_value)
False

Converting Non Zero Values to boolean gives True:

In [21]:

value = " "
bool_value = bool(value)
print(bool_value)
True

In [22]:

value = "ConsoleFlare"
bool_value = bool(value)
print(bool_value)
True

In [23]:

value = 123
bool_value = bool(value)
print(bool_value)
True

In [ ]:

value = "0"
bool_value = bool(value)
print(bool_value)

Note:You must have seen in examples that converting 0 (integer type) gives False, but converting "0" gives True. It's because string type 0 is not equal to 0.

Why do we use Type Casting ?

Sometimes we need to do a particular operation on values but their data type does not allow us to perform such operations, in that case we need to convert its data type to perform desired operation.

Previous4.User Input In PythonNext6.Strings In Python

Last updated 2 years ago