Python Input & Type
Conversion: A Beginner's
Learning Guide
Great job on mastering variables and data types! Now let's learn something
really exciting - how to get information FROM the user and work with it. This is
where your programs become interactive! ï
Part 1: Getting Input from Users ô
So far, we've been putting information directly into our programs. But what if we want to ask the user for their name, age, or favorite
color? That's where input() comes in!
Your First Interactive Program Try These Examples
name = input("What is your name? ") # Example 1: Getting a favorite color
print("Hello, " + name + "!") color = input("What is your favorite color? ")
print(f"Wow! {color} is a beautiful color!")
What happens when you run this?
# Example 2: Getting a city
Python shows: "What is your name? "
city = input("Which city do you live in? ")
It waits for you to type something print(f"I heard {city} is a great place to live!")
You type your name and press Enter
Python stores what you typed in the name variable
It prints a greeting!
Important Discovery U
Try this code and see what happens:
age = input("How old are you? ")
print(f"You are {age} years old")
print(f"The type of age is: {type(age)}")
Surprise! Even when you type a number like 16, Python treats it as text (string)!
This is very important to remember: input() always gives you text, even if you type numbers!
Part 2: The Problem with Input ÿ
Let's see what happens when we try to do math with input:
age = input("How old are you? ")
next_year_age = age + 1
print(f"Next year you will be {next_year_age}")
Oops! You'll get an error that looks scary but just means: "I can't add text and numbers together!"
This is because:
age is text (string) like "16"
1 is a number (integer)
Python can't add text + number
So how do we fix this? We need to convert the text to a number!
Part 3: Type Conversion (Typecasting) L
Type conversion means changing data from one type to another. It's like translating between different languages!
Converting Text to Numbers
1 2
int() - Converting to Whole Numbers float() - Converting to Decimal Numbers
# Get input and convert to integer height = float(input("What is your height in feet? "))
age_text = input("How old are you? ") print(f"Your height is {height} feet")
age_number = int(age_text) print(f"That's {height * 12} inches!")
print(f"You are {age_number} years old") print(f"Type: {type(height)}")
print(f"Next year you will be {age_number + 1}")
print(f"Type of age_number: {type(age_number)}")
Shorter way (combining steps):
age = int(input("How old are you? "))
print(f"Next year you will be {age + 1}")
Converting Numbers to Text
str() - Converting to String
age = 16
score = 95.5
# Convert numbers to text for concatenation
message = "I am " + str(age) + " years old and my score is " + str(score)
print(message)
# Or use f-strings (easier!)
message = f"I am {age} years old and my score is {score}"
print(message)
Visual Summary of Conversions
# Starting with different types
text_number = "25" # This is text
whole_number = 42 # This is an integer
decimal_number = 3.14 # This is a float
# Converting TO integers
print(int("25")) # "25" ³ 25
print(int(3.14)) # 3.14 ³ 3 (removes decimal!)
print(int(text_number)) # "25" ³ 25
# Converting TO floats
print(float("25")) # "25" ³ 25.0
print(float("3.14")) # "3.14" ³ 3.14
print(float(42)) # 42 ³ 42.0
# Converting TO strings
print(str(25)) # 25 ³ "25"
print(str(3.14)) # 3.14 ³ "3.14"
print(str(True)) # True ³ "True"
Part 4: Common Type Conversion Mistakes ¦
Mistake 1: Converting Mistake 2: Losing Decimal Mistake 3: Forgetting to
Invalid Text Places Convert Input
# This will cause an ERROR: price = 19.99 # Wrong way:
# age = int("hello") # Can't whole_price = int(price) num1 = input("Enter first
convert "hello" to a number! print(whole_price) # Shows: 19 number: ") # This is text!
(the .99 is gone forever!) num2 = input("Enter second
# This works: number: ") # This is text!
age = int("25") # "25" can be When converting a float to an int, result = num1 + num2 # This
converted to 25 Python simply truncates the decimal will stick them together, not
part. It does NOT round! add!
Always ensure the text actually # If you enter 5 and 3, result will
represents a number, otherwise be "53" not 8!
Python will raise a ValueError.
# Correct way:
num1 = int(input("Enter first
number: "))
num2 = int(input("Enter second
number: "))
result = num1 + num2 # Now
this adds properly!
This is perhaps the most common
mistake for beginners. Always
typecast your input if you intend to
perform numerical operations!
Part 5: Interactive Programs - Let's Build! ª
Now let's create some fun interactive programs using everything we've learned:
Program 1: Personal Information Program 2: Simple Calculator
Collector
print("=== Simple Calculator ===")
print("=== Personal Information ===") # Get numbers from user
# Get information from user num1 = float(input("Enter the first number: "))
name = input("What's your name? ") num2 = float(input("Enter the second number: "))
age = int(input("How old are you? "))
height = float(input("What's your height in feet? ")) # Perform calculations
favorite_subject = input("What's your favorite subject? ") addition = num1 + num2
subtraction = num1 - num2
# Calculate some fun facts multiplication = num1 * num2
birth_year = 2025 - age division = num1 / num2
height_in_inches = height * 12
# Display results
# Display everything nicely print(f"\n=== Results ===")
print("\n=== Your Information ===") print(f"{num1} + {num2} = {addition}")
print(f"Name: {name}") print(f"{num1} - {num2} = {subtraction}")
print(f"Age: {age} years old") print(f"{num1} × {num2} = {multiplication}")
print(f"You were born in: {birth_year}") print(f"{num1} ÷ {num2} = {division}")
print(f"Height: {height} feet ({height_in_inches} inches)")
print(f"Favorite subject: {favorite_subject}") Program 3: Grade Calculator
# Check data types
print("=== Grade Calculator ===")
print(f"\nData types:")
# Get student information
print(f"name: {type(name)}")
student_name = input("Student name: ")
print(f"age: {type(age)}")
subject = input("Subject: ")
print(f"height: {type(height)}")
# Get grades (as floats for more precision)
test1 = float(input("Test 1 score: "))
test2 = float(input("Test 2 score: "))
test3 = float(input("Test 3 score: "))
# Calculate average
average = (test1 + test2 + test3) / 3
# Display results
print(f"\n=== Grade Report ===")
print(f"Student: {student_name}")
print(f"Subject: {subject}")
print(f"Test 1: {test1}")
print(f"Test 2: {test2}")
print(f"Test 3: {test3}")
print(f"Average: {average:.2f}") # .2f shows 2 decimal
places
Part 6: Boolean Conversion L
We can also convert other types to True/False using bool():
# Converting to boolean with bool()
print(bool("hello")) # True (any non-empty text is True)
print(bool("")) # False (empty text is False)
print(bool(42)) # True (any non-zero number is True)
print(bool(0)) # False (only 0 is False)
print(bool(0.0)) # False (0.0 is also False)
Key idea: In Python, "empty" values (empty strings, the number 0, empty lists/tuples/dictionaries, and None) are considered
"falsy" (evaluate to False). Everything else is "truthy" (evaluates to True).
Interactive Example
user_input = input("Type something (or press Enter for nothing): ")
has_content = bool(user_input)
print(f"You typed something: {has_content}")
This is super useful for checking if a user actually provided input or left a field blank!
Part 7: Handling Multiple Inputs &
Sometimes you want to get several pieces of information quickly from the user. Here are a couple of ways:
Method 1: One at a Time Method 2: All in One Line (Advanced)
name = input("Name: ") # This is more advanced - don't worry if it seems
age = int(input("Age: ")) confusing now!
city = input("City: ") name, age, city = input("Enter name, age, city
separated by spaces: ").split()
This is the most straightforward method, prompting the user age = int(age) # Convert age to number
for each piece of information sequentially. It's clear and easy print(f"Name: {name}, Age: {age}, City: {city}")
to follow for beginners.
The .split() method breaks a string into a list of substrings
based on a delimiter (by default, spaces). This allows users to
enter multiple values on a single line.
While Method 2 is more concise, Method 1 is generally recommended for beginners as it avoids common pitfalls and provides clearer
user prompts.
Part 8: Practice Exercises í
It's time to put your new Python skills to the test! Work through these exercises to solidify your understanding of input and type
conversion.
Exercise 1: Age Calculator Exercise 2: Temperature Converter
# Ask for current age and calculate age in different # Convert Celsius to Fahrenheit
years
Exercise 3: Shopping Calculator Exercise 4: Type Conversion Practice
# Calculate total cost with tax # Try converting these and see what happens
print("=== Conversion Practice ===")
# Get input
user_input = input("Enter any number: ")
print(f"As text: '{user_input}' (type: {type(user_input)})")
# Convert to different types
as_int = int(user_input)
as_float = float(user_input)
as_bool = bool(user_input)
print(f"As integer: {as_int} (type: {type(as_int)})")
print(f"As float: {as_float} (type: {type(as_float)})")
print(f"As boolean: {as_bool} (type: {type(as_bool)})")
Part 9: Debugging Common Input Problems ð
Even experienced programmers encounter issues. Here's how to recognize and solve common problems when working with user input
and type conversion.
Problem 1: "ValueError" when converting Problem 2: Unexpected behavior with math
# This might crash if user doesn't enter a number: # Wrong:
# age = int(input("Age: ")) num1 = input("Number 1: ") # Gets "5"
num2 = input("Number 2: ") # Gets "3"
# For now, just make sure to tell users what to enter: result = num1 + num2 # Result is "53" (text joining)
age = int(input("Please enter your age as a number: "))
# Right:
Solution: Provide clear instructions to the user. Later, you'll num1 = int(input("Number 1: ")) # Gets 5
learn about try-except blocks to handle invalid input num2 = int(input("Number 2: ")) # Gets 3
gracefully. result = num1 + num2 # Result is 8 (math)
Solution: Always remember that input() returns a string.
Convert it to the appropriate numeric type (int() or float())
BEFORE performing mathematical operations.