DEV Community

hebaShakeel
hebaShakeel

Posted on

Taking user input in Python and Type Conversion

-- input(prompt = "Enter your name: ")
or
-- input("Enter your name: ")

Whenever we take user input using the input function, then the user input is always returned in string format. This is because string is a universal format. It can hold other data types. The vice-versa is not true.

To check the datatype of a variable, we use the type() function as follows:

-- type([1,2,3,4])
output : list

To convert the datatype of a variable, we perform Type-Conversion .

Types of Type-Conversion:

  • Implicit: Python automatically performs type conversion behind the scenes.

  • Explicit:

Eg: int(4.5)
o/p : 4

Eg: float(4)
o/p : 4.0

Eg: str(4)
o/p : '4'

Eg: bool(4)
o/p : True

Eg: list('Hello')
o/p : ['H','e','l','l','o']

Type conversion is not a permanent operation.

Program to add two numbers:

first_num = int(input("Enter 1st number: "))
second_num = int(input("Enter 2nd number: "))

result = first_num + second_num
print(result)

Top comments (0)