🐍
Python For Starters
  • Overview
  • Python for starters
  • Content
  • Foreword
  • Introduction To Python
    • Python Installation
    • Variables
    • Python Data Types
    • Python Data Structures
    • Python numbers
    • Python strings
    • Python Boolean
    • Python constants
    • Python Comments
    • Type Conversion
    • Control flow in python
  • Python Functions
    • Function Definition
    • Function Parameter
    • Recursive Functions
    • Using Global Variables in Functions
    • Lambda Functions
  • What are Data Structures
    • Python Lists
    • Python Tuples
    • Python Dictionaries
    • Python Sets
    • Iterable in python
    • Python Map, Filter & Reduce Functions
  • Error handling in Python
  • Loop ... Else Clause, Partial Functions & Type Hints
    • Partial Functions
    • Type Hints
  • Python Modules
  • Python Libraries & Packages
    • Python Packages
  • Directory & IO
    • Python IO Module
  • Pyenv
  • Virtual Environments
    • Pipenv
    • Virtualenv
  • Object Oriented Programming in Python
    • Class
    • Class Methods
    • Python Class Inheritance
    • Python Class Polymorphism
    • Python special methods
  • Appendix
  • Contributing
Powered by GitBook
On this page
  1. Introduction To Python

Type Conversion

Type Conversion

Type conversion is the process of converting a data type into another data type. Implicit type conversion is performed by a Python interpreter only. Explicit type conversion is performed by the user by explicitly using type conversion functions in the program code. Explicit type conversion is also known as typecasting

# file name type_conversion1.py

x: int = 20
y: str = str(x)

Run Code:

python type_conversion1.py

The code returns a string type showing that the variable x was converted to a string type.

Let's try another example:

# file_name - type_conversion2.py

name = "John Doe"
conv_name = int(name)

print(type(name))

Run Code:

python type_conversion2.py

The code returns an error ValueError: invalid literal for int() with base 10: 'John Doe'.

We got the ValueError because the value John Doe is not a valid number therefore converting a string type to a number type is only possible if the string can become a valid number.

PreviousPython CommentsNextControl flow in python

Last updated 1 year ago