3.3 Type casting in Python

mohit355

Mohit Raj

Posted on December 7, 2019

3.3 Type casting in Python

Type casting:

  1. In computer science, type conversion, type casting, type coercion, and type juggling are different ways of changing an expression from one data type to another.
  2. In Python input() function the input taken by the user is a string.
  3. If we want to take a integer as an input then we have to convert the input into the integer. for this we can use int() function in python.

int function:

  1. The int() function converts the specified value into an integer number.
    for example,
    i have to string variable and we want to add together then it will generally concatenate both the value .Alt Text

  2. Now if we want to add them because 12 and 13 is simple an integer value and after adding it 12+13=25. here we can use int() function to convert '12'(string 12) into 12(integer 12).

  3. Syntax : int(x)

x='12'
print(type(x))

Output- <class str>
Enter fullscreen mode Exit fullscreen mode

For converting into an int value

int_value=int(x)
print(type(int_value))

output - <class int>
Enter fullscreen mode Exit fullscreen mode


Alt Text

Similarly you can convert y into an integer value.
Now add both and printAlt Text

  1. This is generally known as type cast (converting an expression of one data type into other)

float() function:

  1. The float() method is used to return a floating point number from a number or a string.
  2. As we convert a variable into int similarly we can type cast a variable into float.
  3. Syntax: float(x)
  4. floating numbers are like 12.23 ,34.00,123.9 etc means all number which contain decimal For example
x=12
print(type(x)
y=float(x)
print(type(y)
print(x," is " ,type(x)," value")
print(y," is ",type(y)," value")
Enter fullscreen mode Exit fullscreen mode

Output

<class int>
<class float>
12 is <class int> value
12.0 is <class float> value
Enter fullscreen mode Exit fullscreen mode

There are too many inbuilt function for type casting in python like str(),list(),dict(),tuple(),set() etc i will discussed this all in upcoming tutorials.

If you have any problem then put it in the comment box.

Thank you

💖 💪 🙅 🚩
mohit355
Mohit Raj

Posted on December 7, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related