Type Conversion Functions

UpComing SoftWare Training Demos

๐Ÿš€ *Playwright With AI Testing Demo In Telugu*
๐Ÿ—“๏ธ *Date:* 28 Oct2026, 08:00 PM IST
๐Ÿ“ *Register Now!:*
https://www.vlrt.in/3r
๐Ÿ‘ฅ *Join WA Community:*
https://www.vlrt.in/3w
๐Ÿ’ก *Course Content:*
https://www.vlrt.in/3c
โ–ถ๏ธ *Demo Videos:*
https://www.vlrt.in/3v

๐Ÿš€ *Gen AI Engineer (Production Focused)*
๐Ÿ—“๏ธ *Date:* 29th Oct 2026, 06:00PM 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

๐Ÿš€ *Vulnerability Management Training Demo*
๐Ÿ—“๏ธ *Date:* 28th Oct 2026, 10: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

  • group() and groups()

    Python re group() and groups() Methods Explained The group() and groups() methods are used with match objects to extract captured groups from regex patterns. They work on the result of re.search(), re.match(), or re.finditer(). group() Method groups() Method Example 1: Basic Group Extraction python import retext = “John Doe, age 30, email: john.doe@email.com”# Pattern with multiple capture groupspattern = r'(\w+)\s+(\w+),\s+age\s+(\d+),\s+email:\s+([\w.]+@[\w.]+)’///The Pattern: r'(\w+)\s+(\w+),\s+age\s+(\d+),\s+email:\s+([\w.]+@[\w.]+)’Breakdown by Capture…

  • The print() Function

    The print() Function Syntax in Python ๐Ÿ–จ๏ธ The basic syntax of the print() function in Python is: Python Let’s break down each part: Simple Examples to Illustrate: ๐Ÿ’ก Python Basic print() Function in Python with Examples ๐Ÿ–จ๏ธ The print() function is used to display output in Python. It can print text, numbers, variables, or any…

  • Special Character Classes Explained with Examples

    Special Character Classes Explained with Examples 1. [\\\^\-\]] – Escaped special characters in brackets Description: Matches literal backslash, caret, hyphen, or closing bracket characters inside character classes Example 1: Matching literal special characters python import re text = “Special chars: \\ ^ – ] [” result = re.findall(r'[\\\^\-\]]’, text) print(result) # [‘\\’, ‘^’, ‘-‘, ‘]’] # Matches…

  • Lambda Functions in Python

    Lambda Functions in Python Lambda functions are small, anonymous functions defined using the lambda keyword. They can take any number of arguments but can only have one expression. Basic Syntax python lambda arguments: expression Simple Examples 1. Basic Lambda Function python # Regular function def add(x, y): return x + y # Equivalent lambda function add_lambda =…

  • math Module

    The math module in Python is a built-in module that provides access to standard mathematical functions and constants. It’s designed for use with complex mathematical operations that aren’t natively available with Python’s basic arithmetic operators (+, -, *, /). Key Features of the math Module The math module covers a wide range of mathematical categories,…

Leave a Reply

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