Type Conversion

Implicit vs. explicit conversion, why int() truncates instead of rounding, and why every raw input() value needs converting before you can do math with it.

Overview

This topic covers how Python handles type conversion โ€” both automatically (implicit) and manually (explicit) โ€” and how this directly affects taking user input with input(), since input() always returns a string.

Key Concepts

Detailed Explanation

1. Implicit Type Conversion

Python automatically promotes a "smaller"/simpler type to a "larger"/more complex type when combining them in an expression, following this general hierarchy:

int → float → complex

Examples:

4 + 5.5        # Out: 9.5        (int + float → float)
5 + 6+7j       # Out: (11+7j)    (int + complex → complex)
4.5 + 5+5j     # Out: (9.5+5j)   (float + complex → complex)
Note: No data is lost when Python does this automatically โ€” it always converts to the type that can safely hold the result (e.g., int โ†’ float doesn't lose precision, but float โ†’ complex just adds a zero imaginary part).

2. Explicit Type Conversion

You manually convert types using built-in functions when Python won't (or can't) do it automatically.

FunctionPurposeExampleOutput
int()Convert to integerint(4.5)4 (decimal part truncated, not rounded)
int()Convert numeric stringint('45')45
float()Convert to floatfloat(4)4.0
str()Convert to stringstr(5)'5'
bool()Convert to booleanbool(1)True
complex()Convert to complex numbercomplex(4)(4+0j)
list()Convert iterable (e.g. string) to listlist('Hello')['H', 'e', 'l', 'l', 'o']

Important โ€” int() truncates, it does not round:

int(4.5)   # Out: 4   (NOT 5 โ€” decimal part is simply dropped)

3. Errors During Explicit Conversion

int() can only convert a string to an integer if the string represents a valid whole number. It cannot parse decimal points or non-numeric text.

int('4.5')
# ValueError: invalid literal for int() with base 10: '4.5'

int('Kolkata')
# ValueError: invalid literal for int() with base 10: 'Kolkata'
int('45')
# Out: 45   โœ… works fine โ€” pure digit string
โš ๏ธ Key takeaway: int() works on strings only if they contain just digits (optionally with a sign). A decimal point or letters will cause a ValueError.

4. Type Conversion Does Not Modify the Original Variable

Calling int() (or any conversion function) on a variable returns a new value โ€” it does not change the variable itself, since these types are immutable.

a = 4.5
int(a)     # Out: 4      → conversion applied, new value returned
a          # Out: 4.5    → original variable is unchanged
Tip: If you want to keep the converted value, you must reassign it:
a = int(a)   # now a = 4

5. Why This Matters for input()

input() always returns a string, regardless of what the user types. If you don't convert it, using + on two inputs will concatenate them as strings instead of adding them as numbers.

โŒ Without conversion (string concatenation, not addition)

first_num = input("Enter the first number")
second_num = input("Enter the second number")
result = first_num + second_num
print(result)

If the user enters 45 and 67, this would just join the strings (e.g., '4567'), not add them numerically.

โœ… Correct approaches โ€” convert to int before or during the operation:

Option A โ€” Convert at input time

first_num = int(input("Enter the first number"))
second_num = int(input("Enter the second number"))

result = first_num + second_num
print(result)

Option B โ€” Convert at calculation time

first_num = input("Enter the first number")
second_num = input("Enter the second number")

result = int(first_num) + int(second_num)
print(result)

Output for both (input: 45, 67):

Enter the first number45
Enter the second number67
112

Both approaches give the same correct numeric result โ€” the difference is when you perform the conversion (right when reading input, vs. right before using it in a calculation).

Commands / Syntax Summary

# Implicit conversion (automatic)
4 + 5.5          # int + float -> float
5 + 6+7j         # int + complex -> complex

# Explicit conversion (manual)
int(x)           # convert to integer (truncates decimals)
float(x)         # convert to float
str(x)           # convert to string
bool(x)          # convert to boolean
complex(x)       # convert to complex number
list(x)          # convert iterable to list

# Safe pattern for numeric user input
num = int(input("Enter a number: "))

Things to Remember

Quick Revision

Python converts types implicitly during mixed-type operations (int + float โ†’ float, etc.), always promoting toward the "richer" type without losing data. For manual control, use explicit conversion functions (int(), float(), str(), bool(), complex(), list()) โ€” but be careful: int() can't parse decimal-point strings or non-numeric text (raises ValueError), and it truncates rather than rounds floats. Since input() always returns a string, any numeric input must be explicitly converted (either immediately at input() or later before using it in a calculation) โ€” otherwise + will concatenate strings instead of adding numbers.