Wednesday, August 15, 2018

Type Conversion or Casting in Python Programming Language


Type Conversion or Casting is an essential feature in all programming languages. Python also supports casting.

Implicit and Explicit Casting

Like C, C++ and Java, Python also supports implicit and explicit type conversion. Any type of expression can be done on same type of values only. What will happen if we use one integer type and another float type variable in any expression? The value of integer type variable will be automatically converted into float type value before the execution of the expression and this is known as implicit or automatic casting. In implicit casting, values in variables with lower hierarchical order are automatically converted into values of variable type with higher hierarchical order. 

Examples of Implicit Casting

num1=10
num2=10.5
num3=num1 + num2

Value of num3 would be 20.50

Explicit Casting

Explicit Casting in Python language is done using constructor functions:

int() - constructs an integer number from an integer literal, a float literal or a string literal. The string value should be a string version of an integer value. In case of float literal, the function eliminates the fractional value.

float() - constructs a float number from an integer literal, a float literal or a string literal.

str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals.

Examples on Integers

x = int(12)   # x will be 12
y = int(10.8) # y will be 10
z = int("200") # z will be 200

Examples on Floats

x = float(9)     # x will be 9.0
y = float(19.8)   # y will be 19.8
z = float("123")   # z will be 123.0
w = float("43.2") # w will be 43.2

Example on Strings

x = str("string1") # x will be 'string1'
y = str(23)    # y will be '23'
z = str(13.0)  # z will be '13.0'

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner