Type Conversion Functions

UpComing SoftWare Training Demos

๐Ÿš€ *Gen AI Engineerย Telugu (Production Focused)*
๐Ÿ—“๏ธ *Date:* 30th Sept 2026, 07:00AM IST
๐Ÿ“ *Register Now!:*
https://www.vlrt.in/gr
๐Ÿ‘ฅ *Join WA Community:*
https://www.vlrt.in/gw
๐Ÿ’ก*Course Content:*
https://www.vlrt.in/ai
โ–ถ๏ธ *Demo Videos:*
https://www.vlrt.in/gv

๐Ÿš€ *Service now Admin/ Development (ITSM)FREE Demo in Telugu*
๐Ÿ—“๏ธ *Date:* 30th Sept 2026, 08:00AM IST
๐Ÿ“ *Register Now!:*
https://www.vlrt.in/7r
๐Ÿ‘ฅ *Join WA Community:*
https://www.vlrt.in/7w
๐Ÿ’ก*Course Content:*
https://www.vlrt.in/7c
โ–ถ๏ธ *Demo Videos:*
https://www.vlrt.in/7v

๐Ÿš€ *Vulnerability Management Training Demo*
๐Ÿ—“๏ธ *Date:* 30th Sept 2026, 09:00 AM IST
๐Ÿ“*Register Now!:*
https://www.vlrt.in/vr
๐Ÿ‘ฅ *Join Community:*
https://www.vlrt.in/cw
๐Ÿ’ก *Course Content:*
https://www.vlrt.in/vc
โ–ถ๏ธ *Demo Videos:*
https://www.vlrt.in/Vm

Type Conversion Functions in Python ๐Ÿ”„

Type conversion (or type casting) transforms data from one type to another. Python provides built-in functions for these conversions. Here’s a comprehensive guide with examples:


1. int(x) ๐Ÿ”ข

Converts x to an integer.

Python

print(int(3.14))        # 3 (float โ†’ int)
print(int("42"))        # 42 (str โ†’ int)
print(int(True))        # 1 (bool โ†’ int)
print(int("1010", 2))   # 10 (binary str โ†’ int)
# print(int("Hello"))   # โŒ ValueError (non-numeric string)

2. float(x) afloat

Converts x to a floating-point number.

Python

print(float(42))        # 42.0 (int โ†’ float)
print(float("3.14"))    # 3.14 (str โ†’ float)
print(float(False))     # 0.0 (bool โ†’ float)
# print(float("1a.5"))  # โŒ ValueError (invalid string)

3. str(x) ๐Ÿ’ฌ

Converts x to a string. Works with any data type.

Python

print(str(100))         # '100' (int โ†’ str)
print(str(7.8e-2))      # '0.078' (float โ†’ str)
print(str([1, 2, 3]))   # '[1, 2, 3]' (list โ†’ str)
print(str(True))        # 'True' (bool โ†’ str)

4. bool(x) โœ…โŒ

Converts x to a Boolean (True or False).

Falsy values: 0, 0.0, “”, [], (), {}, None

Truthy values: Everything else.

Python

print(bool(0))          # False (int)
print(bool("Hello"))    # True (non-empty str)
print(bool([]))         # False (empty list)
print(bool(3.14))       # True (non-zero float)

5. list(x) ๐Ÿ“‹

Converts iterable x to a list.

Python

print(list("abc"))      # ['a', 'b', 'c'] (str โ†’ list)
print(list((1, 2, 3)))  # [1, 2, 3] (tuple โ†’ list)
print(list({4, 5, 6}))  # [4, 5, 6] (set โ†’ list; order not guaranteed)
print(list({'a': 1}))   # ['a'] (dict โ†’ list of keys)

6. tuple(x) ๐Ÿ“ฆ

Converts iterable x to a tuple.

Python

print(tuple([1, 2, 3])) # (1, 2, 3) (list โ†’ tuple)
print(tuple("hi"))      # ('h', 'i') (str โ†’ tuple)

7. set(x) ๐Ÿ“š

Converts iterable x to a set (removes duplicates).

Python

print(set([1, 2, 2, 3])) # {1, 2, 3} (list โ†’ set)
print(set("apple"))      # {'a', 'p', 'l', 'e'} (str โ†’ set)

8. dict(x) ๐Ÿ—บ๏ธ

Converts iterable of key-value pairs to a dictionary.

Python

print(dict([('a', 1), ('b', 2)]))  # {'a': 1, 'b': 2} (list of tuples โ†’ dict)
print(dict(a=1, b=2))              # {'a': 1, 'b': 2} (keyword args โ†’ dict)

9. chr(x) & ord(x) ๐Ÿ…ฐ๏ธโžก๏ธ๐Ÿ”ข

  • chr(i): Converts Unicode code point i to a character.
  • ord(c): Converts character c to its Unicode code point.

Python

print(chr(65))          # 'A' (int โ†’ char)
print(ord('A'))         # 65 (char โ†’ int)
print(chr(128512))      # '๐Ÿ˜€' (emoji)

10. bin(x), oct(x), hex(x) ๐Ÿ”ขโžก๏ธ๐Ÿ”ก

Convert integers to string representations in different bases.

Python

print(bin(42))          # '0b101010' (int โ†’ binary str)
print(oct(42))          # '0o52' (int โ†’ octal str)
print(hex(42))          # '0x2a' (int โ†’ hexadecimal str)

Implicit vs. Explicit Conversion โžก๏ธ

โ†’ Implicit (Automatic) ๐Ÿค–

Python automatically converts types during operations:

Python

result = 3 + 4.5    # int(3) โ†’ float, result=7.5 (float)

โ†’ Explicit (Manual) โœ๏ธ

Programmer specifies the conversion:

Python

age = "25"
years_to_100 = 100 - int(age)  # Explicit str โ†’ int

Key Rules & Errors ๐Ÿšจ

  1. Compatibility:Python# int("12.3") # โŒ ValueError (float string โ†’ int) print(float("12.3")) # โœ… 12.3
  2. Collections:Python# list(123) # โŒ TypeError (int not iterable)
  3. Dictionary Conversion:Requires iterable of key-value pairs:Pythonprint(dict([('a', 1), ('b', 2)])) # โœ… Valid # dict([1, 2, 3]) # โŒ TypeError (not key-value pairs)

Practical Example ๐Ÿ’ก

Python

# Calculate average from user input (str โ†’ float)
scores = ["85.5", "90", "78.5"]
numeric_scores = [float(score) for score in scores]  # Convert list of str to float
average = sum(numeric_scores) / len(numeric_scores)
print(f"Average: {average:.2f}")  # Output: Average: 84.67

Mastering type conversions is essential for data processing and user input handling! ๐Ÿš€

Similar Posts

  • Default Arguments

    Default Arguments in Python Functions Default arguments allow you to specify default values for function parameters. If a value isn’t provided for that parameter when the function is called, Python uses the default value instead. Basic Syntax python def function_name(parameter=default_value): # function body Simple Examples Example 1: Basic Default Argument python def greet(name=”Guest”): print(f”Hello, {name}!”)…

  • What is Python library Complete List of Python Libraries

    In Python, a library is a collection of pre-written code that you can use in your programs. Think of it like a toolbox full of specialized tools. Instead of building every tool from scratch, you can use the tools (functions, classes, modules) provided by a library to accomplish tasks more efficiently.   Here’s a breakdown…

  • Unlock the Power of Python: What is Python, History, Uses, & 7 Amazing Applications

    What is Python and History of python, different sectors python used Python is one of the most popular programming languages worldwide, known for its versatility and beginner-friendliness . From web development to data science and machine learning, Python has become an indispensable tool for developers and tech professionals across various industries . This blog post…

  • circle,Rational Number

    1. What is a Rational Number? A rational number is any number that can be expressed as a fraction where both the numerator and the denominator are integers (whole numbers), and the denominator is not zero. The key idea is ratio. The word “rational” comes from the word “ratio.” General Form:a / b Examples: Non-Examples: 2. Formulas for Addition and Subtraction…

  • Positional-Only Arguments in Python

    Positional-Only Arguments in Python Positional-only arguments are function parameters that must be passed by position (order) and cannot be passed by keyword name. Syntax Use the / symbol in the function definition to indicate that all parameters before it are positional-only: python def function_name(param1, param2, /, param3, param4): # function body Simple Examples Example 1: Basic Positional-Only Arguments python def calculate_area(length,…

Leave a Reply

Your email address will not be published. Required fields are marked *