Video 3: Python Input, Type Casting & Exception Handling
Channel Intro
Welcome back to B2D Channel – your shortcut to mastering Python step by step. In this video, we’ll cover
Input Handling, Type Casting, and Exception Management in Python, including how conversions work
and why exceptions matter.
Part 1: Getting User Input
Using input() Function
name = input("Enter your name: ")
print("Hello", name)
Note: input() returns data as a string by default.
age = input("Enter your age: ")
print(age, type(age)) # str
Part 2: Type Casting (Explicit Conversion)
Basic Conversion
age = int(input("Enter your age: ")) # string to int
pi = float("3.14") # string to float
text = str(100) # int to string
Boolean Casting
print(bool(0)) # False
print(bool(123)) # True
print(bool("")) # False
1
Part 3: Type Conversion Types
Widening Conversion (Safe)
• Smaller to bigger data type (e.g., int → float )
x = 10
y = float(x)
print(y) # 10.0
Narrowing Conversion (Risky)
• Bigger to smaller data type (e.g., float → int )
• Might lose data
pi = 3.14159
radius = int(pi)
print(radius) # 3
Part 4: Handling Exceptions in Python
Basic Try-Except
try:
num = int(input("Enter a number: "))
print("Double:", num * 2)
except ValueError:
print("Invalid input. Please enter a number.")
Part 5: Multiple Except Blocks
try:
a = int(input("a: "))
b = int(input("b: "))
result = a / b
print(result)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid number")
2
Part 6: else and finally
try:
val = int(input("Enter value: "))
except ValueError:
print("Wrong format")
else:
print("Conversion successful")
finally:
print("End of try block")
Part 7: Raising Exceptions
def divide(x, y):
if y == 0:
raise ZeroDivisionError("Cannot divide by zero!")
return x / y
print(divide(10, 2))
📊 else vs except in Python
Feature else except
Runs when no exception occurs in Catches and handles exceptions/
Purpose
try errors
Placement Comes after all except blocks Comes right after the try block
Optional Yes Yes, but at least one is usually needed
Typical Usage Code that should only run if no error Code to handle specific error types
Example Use
Logging success after successful input Catching invalid input or zero division
Case
3
Bonus Task Problems
Problem 1: Take integer input and square it
try:
num = int(input("Enter a number: "))
print("Square:", num ** 2)
except:
print("Please enter a valid integer")
Problem 2: Convert temperature
temp_c = float(input("Enter Celsius: "))
temp_f = (temp_c * 9/5) + 32
print("Fahrenheit:", temp_f)
Problem 3: Safe division
try:
a = float(input("a: "))
b = float(input("b: "))
print("Result:", a/b)
except ZeroDivisionError:
print("Can't divide by 0")
Problem 4: Detect input type
value = input("Enter something: ")
print("Type:", type(value))
Problem 5: Parse and Add Two Strings as Integers
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Sum:", a + b)
except:
print("Invalid input! Please enter integers only.")
4
Additional Practice Problems
Problem 6: Get first and last character of input string
text = input("Enter a word: ")
if len(text) >= 2:
print("First:", text[0], "Last:", text[-1])
else:
print("Please enter at least 2 characters")
Problem 7: Convert minutes to hours and minutes
try:
mins = int(input("Enter minutes: "))
print(mins // 60, "hour(s) and", mins % 60, "minute(s)")
except:
print("Invalid input")
Problem 8: Multiply string with number
text = input("Enter any word: ")
times = int(input("How many times to repeat? "))
print(text * times)
Problem 9: Check if string is a number
val = input("Enter something: ")
if val.isdigit():
print("Valid integer input")
else:
print("Not an integer")
Problem 10: Sum of float numbers input as strings
try:
a = float(input("Enter first float: "))
b = float(input("Enter second float: "))
print("Sum:", a + b)
except:
print("Invalid float input")
5
Summary
In this video, we covered:
• input() function and default string type
• Type casting: int() , float() , str() , bool()
• Type conversion: widening (safe), narrowing (risk)
• Exception handling with try , except , else , finally
• Difference between else and except
• Practical examples with user input and error checking
Keep practicing, and you'll master real-world Python input and exception handling in no time.
Leave your questions in the comments and Subscribe to the B2D Channel for more!