Lesson 4 of 2013 min read

Input, Output and Type Conversion

Share:WhatsAppLinkedIn

Prerequisites: Variables, Data Types, Operators


1. The input Function

The input function reads a line of text from the user via the keyboard.

Critical rule: input always returns a string, even if the user types a number.

Syntax

variable = input # without prompt
variable = input("prompt text") # with prompt message
# Example 1: Basic input
name = input("Enter your name: ")
print("Hello,", name)
print(type(name)) # <class 'str'> - always a string!

Output:

Enter your name: Priya
Hello, Priya
<class 'str'>

Input for Numbers

Since input always returns a string, you must convert the value to perform arithmetic.

# Example 2: Numeric input - THE MOST COMMON MISTAKE
# WRONG way:
num = input("Enter a number: ")
# result = num + 10 # TypeError! Cannot add str and int

# CORRECT way:
num = int(input("Enter a number: "))
print(num + 10) # Now it works!

# For decimal numbers:
price = float(input("Enter price: "))
print("With tax:", price * 1.18)

Output (for input 25 and 100.50):

Enter a number: 25
35
Enter price: 100.50
With tax: 118.59

Reading Multiple Values on One Line

# Example 3: Multiple inputs on one line
# Using split - splits a string by spaces (or given delimiter)
a, b = input("Enter two numbers (space-separated): ").split
print("You entered:", a, "and", b)
print(type(a)) # <class 'str'> - still strings!

# To convert both to integers:
a, b = input("Enter two numbers: ").split
a = int(a)
b = int(b)
print("Sum =", a + b)

# Shorter version using map:
x, y = map(int, input("Enter two numbers: ").split)
print("Product =", x * y)

Output:

Enter two numbers (space-separated): 10 20
You entered: 10 and 20
<class 'str'>
Enter two numbers: 10 20
Sum = 30
Enter two numbers: 5 8
Product = 40

2. The print Function

The print function displays output on the screen.

Syntax

print(value1, value2, ..., sep=' ', end='\n')

Basic Usage

# Example 4: Basic print
print("Hello World") # Hello World
print(42) # 42
print(3.14) # 3.14
print(True) # True

# Multiple values (separated by space by default)
print("Name:", "Aarav", "Age:", 16) # Name: Aarav Age: 16

# Printing expressions
a = 10
b = 20
print("Sum =", a + b) # Sum = 30
print("a =", a, "b =", b) # a = 10 b = 20

Output:

Hello World
42
3.14
True
Name: Aarav Age: 16
Sum = 30
a = 10 b = 20

The sep Parameter

Controls the separator between multiple values. Default is a single space ' '.

# Example 5: sep parameter
print("a", "b", "c") # a b c (default: space)
print("a", "b", "c", sep="-") # a-b-c
print("a", "b", "c", sep="***") # a***b***c
print("a", "b", "c", sep="") # abc (no separator)
print("a", "b", "c", sep="\n") # each on new line
print(10, 20, 30, sep=", ") # 10, 20, 30

# Practical use: formatting a date
day, month, year = 15, 8, 2025
print(day, month, year, sep="/") # 15/8/2025

Output:

a b c
a-b-c
a***b***c
abc
a
b
c
10, 20, 30
15/8/2025

The end Parameter

Controls what is printed at the end. Default is a newline '\n'.

# Example 6: end parameter
print("Hello", end=" ") # no newline after "Hello"
print("World") # continues on same line
# Output: Hello World

print("A", end="")
print("B", end="")
print("C")
# Output: ABC

print("Line 1", end="---")
print("Line 2")
# Output: Line 1---Line 2

# Practical use: printing on the same line in a loop
for i in range(1, 6):
 print(i, end=" ")
print # final newline
# Output: 1 2 3 4 5

Output:

Hello World
ABC
Line 1---Line 2
1 2 3 4 5

Combining sep and end

# Example 7: Using both sep and end together
print(1, 2, 3, sep="-", end="!\n") # 1-2-3!
print("A", "B", sep=":", end=" | ")
print("C", "D", sep=":")
# Output: A:B | C:D

Output:

1-2-3!
A:B | C:D

3. Type Conversion

Converting a value from one data type to another. There are two types:

3.1 Implicit Type Conversion (Automatic / Coercion)

Python automatically converts a "smaller" type to a "larger" type during operations to avoid data loss.

Conversion hierarchy: bool -> int -> float -> complex

# Example 8: Implicit type conversion
# int + float = float
a = 5 # int
b = 2.5 # float
c = a + b # Python converts 5 to 5.0, then adds
print(c) # 7.5
print(type(c)) # <class 'float'>

# int + bool = int
x = 10 + True # True is treated as 1
print(x) # 11
print(type(x)) # <class 'int'>

# float + bool = float
y = 3.14 + False # False is treated as 0
print(y) # 3.14
print(type(y)) # <class 'float'>

# int + complex = complex
z = 5 + (3+2j)
print(z) # (8+2j)
print(type(z)) # <class 'complex'>

Output:

7.5
<class 'float'>
11
<class 'int'>
3.14
<class 'float'>
(8+2j)
<class 'complex'>

Note: Python does NOT automatically convert between str and int/float. "5" + 3 gives TypeError, not "53" or 8.

3.2 Explicit Type Conversion (Type Casting)

The programmer manually converts data using built-in functions.

Function Converts to Example Result
int Integer int(3.9) 3
float Float float(5) 5.0
str String str(42) "42"
bool Boolean bool(0) False
list List list("abc") ['a', 'b', 'c']
tuple Tuple tuple([1,2,3]) (1, 2, 3)
dict Dictionary dict([(1,'a')]) {1: 'a'}
set Set set([1,2,2,3]) {1, 2, 3}
complex Complex complex(3,4) (3+4j)
ord ASCII value ord('A') 65
chr Character chr(65) 'A'
bin Binary string bin(10) '0b1010'
oct Octal string oct(10) '0o12'
hex Hex string hex(255) '0xff'
# Example 9: int conversions
print(int(3.9)) # 3 (truncates decimal, does NOT round!)
print(int(3.1)) # 3
print(int(-3.9)) # -3 (truncates toward zero)
print(int("25")) # 25 (string to int - string must contain valid integer)
print(int(True)) # 1
print(int(False)) # 0
print(int("0b1010", 2)) # 10 (binary string to int with base)
print(int("0xFF", 16)) # 255 (hex string to int with base)

# These will cause ERRORS:
# int("hello") # ValueError: invalid literal
# int("3.14") # ValueError: cannot convert string with decimal
# int("") # ValueError: invalid literal

Output:

3
3
-3
25
1
0
10
255
# Example 10: float conversions
print(float(5)) # 5.0
print(float("3.14")) # 3.14
print(float("25")) # 25.0
print(float(True)) # 1.0
print(float("1.5e2")) # 150.0 (scientific notation)

# Error:
# float("hello") # ValueError

Output:

5.0
3.14
25.0
1.0
150.0
# Example 11: str conversions
print(str(42)) # "42"
print(str(3.14)) # "3.14"
print(str(True)) # "True"
print(str(None)) # "None"
print(str([1, 2, 3])) # "[1, 2, 3]"

# str never fails - it can convert anything to a string

Output:

42
3.14
True
None
[1, 2, 3]
# Example 12: bool conversions - Falsy values
print(bool(0)) # False
print(bool(0.0)) # False
print(bool("")) # False (empty string)
print(bool([])) # False (empty list)
print(bool()) # False (empty tuple)
print(bool({})) # False (empty dict)
print(bool(None)) # False
print(bool(False)) # False

# Everything else is True
print(bool(42)) # True
print(bool(-1)) # True
print(bool("Hi")) # True
print(bool([0])) # True (list is not empty, even if it contains 0)
print(bool(" ")) # True (string has a space character - not empty!)

Output:

False
False
False
False
False
False
False
False
True
True
True
True
True
# Example 13: ord and chr
print(ord('A')) # 65 (ASCII value of 'A')
print(ord('a')) # 97 (ASCII value of 'a')
print(ord('0')) # 48 (ASCII value of '0')
print(chr(65)) # A (character for ASCII 65)
print(chr(97)) # a
print(chr(48)) # 0

Output:

65
97
48
A
a
0

4. String Formatting

Three ways to insert variables/values into strings.

4.1 f-Strings (Formatted String Literals), Recommended

Available from Python 3.6+. Prefix the string with f and put expressions inside {}.

# Example 14: f-strings
name = "Aarav"
age = 16
marks = 92.567

print(f"Name: {name}") # Name: Aarav
print(f"Age: {age}") # Age: 16
print(f"Next year: {age + 1}") # Next year: 17
print(f"Marks: {marks:.2f}") # Marks: 92.57 (2 decimal places)
print(f"{'Python':>10}") # ' Python' (right-aligned, width 10)
print(f"{'Python':<10}!") # 'Python !' (left-aligned, width 10)
print(f"{'Python':^10}") # ' Python ' (center-aligned, width 10)
print(f"Binary of 10: {10:b}") # Binary of 10: 1010
print(f"Percentage: {0.856:.1%}") # Percentage: 85.6%

Output:

Name: Aarav
Age: 16
Next year: 17
Marks: 92.57
 Python
Python !
 Python
Binary of 10: 1010
Percentage: 85.6%

4.2 format Method

# Example 15: format method
name = "Priya"
marks = 92.567

print("Name: {}".format(name)) # Name: Priya
print("Name: {0}, Age: {1}".format("Priya", 16)) # Name: Priya, Age: 16
print("Marks: {:.2f}".format(marks)) # Marks: 92.57
print("{0} got {1} in {2}".format("Aarav", 95, "Maths")) # Aarav got 95 in Maths
print("{name} is {age}".format(name="Riya", age=15)) # Riya is 15

Output:

Name: Priya
Name: Priya, Age: 16
Marks: 92.57
Aarav got 95 in Maths
Riya is 15

4.3 % Formatting (Old Style)

# Example 16: % formatting (older style, less preferred)
name = "Aarav"
age = 16
marks = 92.567

print("Name: %s" % name) # Name: Aarav
print("Age: %d" % age) # Age: 16
print("Marks: %.2f" % marks) # Marks: 92.57
print("Name: %s, Age: %d" % (name, age)) # Name: Aarav, Age: 16

Output:

Name: Aarav
Age: 16
Marks: 92.57
Name: Aarav, Age: 16

Format specifiers: %s = string, %d = integer, %f = float, %.2f = float with 2 decimal places.


5. Types of Errors

Understanding errors is essential for debugging programs and is tested in exams.

5.1 Syntax Error

A violation of the grammar rules of Python. Detected before the program runs (at parse time).

# Example 17: Syntax errors (each line would cause SyntaxError)

# Missing colon after if
# if x > 5
# print("Hello")

# Missing closing parenthesis
# print("Hello"

# Invalid assignment
# 5 = x

# Misspelled keyword
# whille True:
# pass

# Missing quotes
# print(Hello) # NameError, but conceptually a syntax-level mistake

Actual error message:

 File "test.py", line 1
 if x > 5
 ^
SyntaxError: expected ':'

5.2 Logical Error (Semantic Error)

The program runs without crashing but produces wrong results. Hardest to find because Python does not report them.

# Example 18: Logical error
# Task: Calculate average of 3 numbers
a, b, c = 10, 20, 30

# WRONG (logical error - division before addition)
average = a + b + c / 3
print("Average:", average) # 40.0 (WRONG! Should be 20.0)

# CORRECT
average = (a + b + c) / 3
print("Average:", average) # 20.0

Output:

Average: 40.0
Average: 20.0

5.3 Runtime Error (Exception)

The program starts running but crashes during execution due to an illegal operation.

# Example 19: Runtime errors

# Division by zero
# print(10 / 0) # ZeroDivisionError

# Wrong type conversion
# print(int("hello")) # ValueError

# Using undefined variable
# print(x) # NameError (if x not defined)

# Wrong index
# lst = [1, 2, 3]
# print(lst[5]) # IndexError

# Wrong type operation
# print("age: " + 25) # TypeError (cannot add str and int)

# Wrong key in dictionary
# d = {"a": 1}
# print(d["b"]) # KeyError

Summary Table of Error Types

Error Type When Detected Example Python Reports?
Syntax Error Before execution print("Hello" Yes (SyntaxError)
Runtime Error During execution 10 / 0 Yes (ZeroDivisionError)
Logical Error After checking output Wrong formula No (you must find it)

Complete Programs

Program 1: Temperature Converter

# Convert Celsius to Fahrenheit
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C = {fahrenheit}°F")

Output:

Enter temperature in Celsius: 37
37.0°C = 98.6°F

Program 2: Area and Perimeter of Rectangle

# Calculate area and perimeter of a rectangle
length = float(input("Enter length: "))
width = float(input("Enter width: "))

area = length * width
perimeter = 2 * (length + width)

print(f"Area = {area}")
print(f"Perimeter = {perimeter}")

Output:

Enter length: 10
Enter width: 5
Area = 50.0
Perimeter = 30.0

Program 3: Swapping Two Numbers (with output)

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

print(f"Before swap: a = {a}, b = {b}")
a, b = b, a
print(f"After swap: a = {a}, b = {b}")

Output:

Enter first number: 10
Enter second number: 25
Before swap: a = 10, b = 25
After swap: a = 25, b = 10

Common Mistakes

  1. Not converting input to int/float: num = input("Number: ") gives a string. num + 5 causes TypeError
  2. Using int on a float string: int("3.14") causes ValueError. Use int(float("3.14")) or just float("3.14")
  3. Confusing int truncation with rounding: int(3.9) = 3, not 4. For rounding, use round(3.9) = 4
  4. Forgetting that int(-3.9) = -3: Truncates toward zero, not toward negative infinity
  5. Printing without print: In script mode, x + 5 alone does not display anything. You must use print(x + 5)
  6. Confusing sep and end: sep controls what goes between values; end controls what goes after all values
  7. Expecting input to handle multiple types: input always returns one string. Split and convert manually
  8. Not understanding implicit conversion direction: 5 + 2.0 = 7.0 (int becomes float, not the other way)
  9. Wrong format specifier in % formatting: Using %d for a float truncates it; use %f
  10. Thinking logical errors are reported by Python: They are not. The program runs fine but gives wrong output

$1$2 Quick Tips

  1. "input always returns string" (1-2 marks): This is asked almost every year. Explain with example showing why conversion is needed
  2. Find the output with print(sep, end) (2-3 marks): Very common. Practice various combinations of sep and end
  3. Type conversion questions (2-3 marks): "What is the output of int(3.9)?", "What is float('5')?", "What does str(True) return?"
  4. Implicit vs Explicit conversion (2 marks): Give definitions and examples of each
  5. Error identification (2-3 marks): Given code with errors, identify the type (syntax/runtime/logical) and fix it
  6. f-string / format output (1-2 marks): Given a formatted print, predict the output
  7. bool conversion (1-2 marks): What is bool(0), bool(""), bool([0])?
  8. ord and chr (1-2 marks): Convert character to ASCII and vice versa
  9. split for multiple inputs (2 marks): How to read two numbers on the same line
  10. Write a program (3-5 marks): Simple calculation programs requiring input, processing, and formatted output

Test Your Knowledge

Take a quick quiz on this lesson

Start Quiz →

Prefer watching over reading?

Subscribe for free.

Subscribe on YouTube