Type Casting and User Input in Python

·

2 min read

Type Casting and User Input in Python

Typecasting in Python

The conversion of one data type into the other data type is known as type casting in Python or type conversion in Python.

Python supports a wide variety of functions or methods like int(), float(), str(), ord(), hex(), oct(), tuple(), set(), list(), dict(), etc. for the type casting in python.

  1. Explicit Conversion (Explicit type casting in Python)

    The conversion of one data type into another data type, done by the developer or programmer's intervention with the help of Python’s built-in type conversion functions such as int(), float(), hex(), oct(), str(), etc.

    oct() gives the ASCII value of the element.

  2. Implicit Conversion (Implicit type casting in Python)

    According to the level, one data type is converted into another by the Python interpreter itself (automatically) to prevent data loss.

    Taking User Input in Python

    Sure, here's the syntax for taking input in Python:

     # To take input as string
     variable_name = input()
    
     # To take input as integer
     variable_name = int(input())
    
     # To take input as float
     variable_name = float(input())
    
     # Displaying a message with input
     variable_name = input("Enter your name: ")
    

    In the above code, input() function is used to take user input. It takes input as a string. If we want to take input as an integer or a float, we need to use the int() or float() function respectively to convert the input string into the desired data type.

    We can also display a message to the user while taking input using the input() function as shown in the last example.