Type Conversion and Input/Output
Overview
Learn how to convert data between different types and make your programs interactive by getting input from users and displaying formatted output.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- Why type conversion is needed: Understand when and why you need to convert between data types.
- How to convert types: Master functions like
int(),float(), andstr(). - How to get user input: Use the
input()function to make your programs interactive. - How to format output: Combine strings and variables to create user-friendly messages.
Why This Matters
Real programs need to interact with users. They get input, process it, and show results. Type conversion ensures your data is in the right format for calculations and operations.
Step 1: Why Convert Types?
Sometimes you have data in one format but need it in another. For example, you might get a number as text from a user, but you need it as an actual number to do math. Type conversion solves this problem.
age = "25" # This is a string (text)
next_year = age + 1 # Error! Can't add string and number
age = "25" # String
age_number = int(age) # Convert to integer
next_year = age_number + 1 # Now it works!
Key Concept: Python is strict about types. You can't automatically mix strings and numbers. You must explicitly convert them when needed. This prevents errors and makes your code clearer.
Step 2: Type Conversion Functions
Python provides built-in functions to convert between types. These functions take a value and return it in the new type.
int() - Convert to Integer
Converts a value to a whole number. Works with strings that contain numbers and floats (rounds down).
int("42") # Returns 42
int(3.14) # Returns 3
int("25") # Returns 25
float() - Convert to Float
Converts a value to a decimal number. Works with strings and integers.
float("3.14") # Returns 3.14
float(5) # Returns 5.0
float("10") # Returns 10.0
str() - Convert to String
Converts any value to text. Useful for combining numbers with text.
str(42) # Returns "42"
str(3.14) # Returns "3.14"
str(True) # Returns "True"
bool() - Convert to Boolean
Converts a value to True or False. Empty values become False, non-empty become True.
bool(1) # Returns True
bool(0) # Returns False
bool("") # Returns False
Mini Practice #1: Type Conversion
Try It YourselfTry converting between different types. Notice how each conversion works:
What happened? You converted the string "42" to an integer 42, then added 8 to it. Without conversion, Python would give an error because you can't add a string and a number.
Step 3: Getting User Input with input()
The input() function lets your program get information from the user. When Python reaches an input() statement, it waits for the user to type something and press Enter.
name = input("What's your name? ")
print("Hello,", name)
Display a Prompt
The text inside input() is shown to the user. This tells them what to type.
input("Enter your age: ")
Wait for Input
Python pauses and waits for the user to type something and press Enter.
Store the Result
Whatever the user types is stored as a string. You can assign it to a variable.
age = input("Enter your age: ")
# age is now a string, like "25"
Important: input() always returns a string, even if the user types a number. If you need a number, you must convert it using int() or float().
Mini Practice #2: Getting Input
Try It YourselfTry getting input from the user. Note: In this online editor, you'll need to provide input in a special way. In a real Python program, it would wait for you to type.
Note: In a real Python program, you would use name = input("What's your name? ") and the program would wait for you to type. Here we're simulating it with a variable.
Step 4: Converting Input to Numbers
Since input() always returns a string, you need to convert it if you want to do math. This is one of the most common uses of type conversion.
age = input("How old are you? ")
next_year = age + 1 # Error! age is a string
age = input("How old are you? ")
age_number = int(age) # Convert string to integer
next_year = age_number + 1 # Now it works!
print("Next year you'll be", next_year)
Common Pattern
This pattern is very common: get input, convert it, then use it. You'll use this often when building interactive programs.
# Get input (always a string)
user_input = input("Enter a number: ")
# Convert to number
number = int(user_input)
# Use in calculation
result = number * 2
print(result)
Step 5: Formatting Output
When displaying results, you often want to combine text and variables. Python provides several ways to do this.
Method 1: Using Commas
Separate values with commas. Python adds spaces automatically.
name = "Alice"
age = 25
print("Hello,", name, "you are", age)
Output: Hello, Alice you are 25
Method 2: String Concatenation
Use + to join strings. Must convert numbers to strings first.
name = "Alice"
age = 25
print("Hello, " + name + " you are " + str(age))
Output: Hello, Alice you are 25
Tip: Using commas is easier because Python handles the spacing and type conversion automatically. String concatenation gives you more control but requires converting numbers to strings first.
Mini Practice #3: Formatting Output
Try It YourselfTry combining text and variables to create formatted output:
Notice: Python automatically adds spaces between the values when you use commas. This makes formatting output easy.
End-of-Lesson Exercises
Exercise 1: Convert and Calculate
Create a variable text_number with the value "10" (as a string). Convert it to an integer, multiply it by 5, and print the result.
Use int() to convert the string to a number.
Exercise 2: Format a Message
Create variables: name = "Alice", age = 25 (as an integer). Print a message that says "Hello, Alice! You are 25 years old."
Use commas in print() to combine text and variables.