All 57 lessons

Lesson 6 of 57 · Getting Started

Type Conversion, Input and Output

By Skillancy Editorial Team

Run the code in the free Python Compiler or on your own computer. Lessons that read files use the FreshBasket practice data: download the dataset (ZIP).

Data almost never arrives in the type you need. A CSV file stores every value as text, a web form returns "25" rather than 25, and a price might read "₹1,299.00". Before you can calculate with such values you must convert them. In the other direction, once your analysis is done you need to output the results clearly, whether on screen, in a log, or in a report.

This lesson closes Module 1. It teaches the conversion functions int(), float(), str() and bool(), shows what happens when a conversion fails, explains how input() works, and covers the options of print() that make your output readable. These skills are used in virtually every script you will ever write.

The conversion functions

FunctionConverts toExampleResult
int(x)whole numberint("42"), int(7.9)42, 7
float(x)decimal numberfloat("3.5"), float(2)3.5, 2.0
str(x)textstr(412)"412"
bool(x)True/Falsebool(""), bool(5)False, True

Conversion does not change the original variable; it returns a new value of the requested type. Two behaviours are worth remembering now: int() on a float truncates (cuts off) the decimals rather than rounding, and converting text that does not look like a number raises a ValueError.

Truthy and falsy values

When Python needs a yes/no answer (in an if, for example), it treats some values as false. The falsy values are: False, None, zero (0, 0.0), and empty containers ("", [], {}, (), set()). Everything else is truthy. This is why if orders: works as a quick "is there anything here?" test.

Worked examples

Example 1: Text to numbers

Question: A CSV delivered the values "412" and "486.5" as text. Calculate the revenue.

orders_text = "412"
basket_text = "486.5"

print(orders_text * 2)

orders = int(orders_text)
basket = float(basket_text)
print(orders * basket)
print(type(orders), type(basket))

Output

412412
200438.0
<class 'int'> <class 'float'>

How it works: The first print shows the danger of not converting: multiplying text by 2 repeats it ("412412"). After int() and float() the values are real numbers and the multiplication gives the revenue. We printed the types to confirm the conversion worked.

Reading the result: Revenue is 200438.0. Whenever a number behaves oddly, check whether it is secretly a string.

Example 2: Numbers to text

Question: Build the label "Order #5002 - total 349.5" from a number and a decimal.

order_no = 5002
total = 349.5

label = "Order #" + str(order_no) + " - total " + str(total)
print(label)

label2 = f"Order #{order_no} - total {total}"
print(label == label2)

Output

Order #5002 - total 349.5
True

How it works: str() turns any value into text so it can be joined with +. The f-string does the conversion automatically and is shorter, which is why it is preferred.

Reading the result: Both approaches give the identical sentence, and the comparison printed True. Use str() when you need text on its own, and f-strings when you are building a message.

Example 3: int() truncates, round() rounds

Question: What is the difference between int(7.9) and round(7.9)?

print(int(7.9), int(-7.9), int(7.0))
print(round(7.9), round(-7.9))
print(float(3), float("1e3"))

Output

7 -7 7
8 -8
3.0 1000.0

How it works: int() simply discards the decimal part, moving toward zero, so 7.9 becomes 7 and -7.9 becomes -7. round() goes to the nearest whole number. float(3) gives 3.0, and float("1e3") understands scientific notation.

Reading the result: Truncation can quietly bias results: int(7.9) is 7, not 8. When you mean "nearest", always use round().

Example 4: Conversion errors

Question: What happens when the text is not a clean number?

int("12.5")

Output

Traceback (most recent call last):
  File "example.py", line 1, in <module>
    int("12.5")
    ~~~^^^^^^^^
ValueError: invalid literal for int() with base 10: '12.5'
float("₹1,299.00")

Output

Traceback (most recent call last):
  File "example.py", line 1, in <module>
    float("₹1,299.00")
    ~~~~~^^^^^^^^^^^^^
ValueError: could not convert string to float: '₹1,299.00'

How it works: int() does not accept a decimal point in text, and float() does not accept currency symbols or thousand separators. Python refuses rather than guess, raising a ValueError whose message quotes the exact text it could not read.

Reading the result: The two messages say invalid literal for int() and could not convert string to float. Real datasets are full of values like this, so cleaning before converting is routine, as the next two examples show.

Example 5: Cleaning a price string, then converting

Question: Convert "₹1,299.50" and "Rs. 850" into numbers.

def to_number(text):
    cleaned = text.replace("₹", "").replace("Rs.", "").replace(",", "").strip()
    return float(cleaned)

print(to_number("₹1,299.50"))
print(to_number("Rs. 850"))
print(to_number("  74 "))

Output

1299.5
850.0
74.0

How it works: We wrote a small function (the functions lesson explains the syntax in full) that removes the rupee marks and commas, trims spaces, and converts. Writing the cleaning logic once and reusing it keeps your code tidy.

Reading the result: All three formats became clean numbers: 1299.5, 850.0 and 74.0. In pandas you will do the same to a whole column with .str.replace() and .astype(float).

Example 6: Safe conversion with try and except

Question: Convert a list of mixed values, but do not crash on bad ones.

raw_values = ["34", "27.5", "NA", "", "41"]
clean = []

for item in raw_values:
    try:
        clean.append(float(item))
    except ValueError:
        clean.append(None)

print(clean)

Output

[34.0, 27.5, None, None, 41.0]

How it works: The try block attempts the conversion. If Python raises a ValueError, execution jumps to the except block instead of stopping the program, and we record None for that item. The loop then moves on to the next value. (A full lesson on exceptions comes later.)

Reading the result: Three values converted and two ("NA" and the empty string) became None. Marking bad values and carrying on is how real data pipelines survive imperfect input.

Example 7: Truthy and falsy

Question: Which values does Python treat as true or false?

tests = [0, 1, -3, 0.0, "", "0", " ", None, [], [0], {}]

for value in tests:
    print(f"{value!r:>6} -> {bool(value)}")

Output

     0 -> False
     1 -> True
    -3 -> True
   0.0 -> False
    '' -> False
   '0' -> True
   ' ' -> True
  None -> False
    [] -> False
   [0] -> True
    {} -> False

How it works: bool(value) applies the truthiness rules. The !r inside the f-string asks for the repr() form so that empty text and lists are visible. Notice that the string "0" and a string with one space are true, because they are not empty.

Reading the result: Only 0, 0.0, "", None, [] and {} are false in this list. A very common bug is expecting "0" or "False" to be false; they are non-empty strings, so they are true.

Example 8: Reading input

Question: How do I ask the user for a value, and why can't I add 1 to it directly?

name = input("Enter customer name: ")
age = input("Enter age: ")
print(name, age + 1)

When this program runs, a person types answers at the keyboard. To show you exactly what happens, we replay a session where the user types Aarav and then 29:

name = input("Enter customer name: ")
age = input("Enter age: ")
print(name, age + 1)

Output

Enter customer name: Aarav
Enter age: 29
Traceback (most recent call last):
  File "example.py", line 3, in <module>
    print(name, age + 1)
                ~~~~^~~
TypeError: can only concatenate str (not "int") to str

How it works: input() pauses the program, shows the prompt, and returns whatever the user typed as a string, even if they typed digits. The text after each colon above is what the user typed. Adding 1 to the string "29" therefore fails with a TypeError.

Reading the result: The fix is to convert immediately:

name = input("Enter customer name: ")
age = int(input("Enter age: "))
print(f"{name} will be {age + 1} next year")

Output

Enter customer name: Aarav
Enter age: 29
Aarav will be 30 next year

Wrapping input() in int() converts the answer as soon as it arrives. Notebook and script users see the same behaviour; websites and apps collect input differently, but the same text-to-number conversion is always needed.

Example 9: Controlling print

Question: How do I print several values on one line, or change the separator and line ending?

print("Bengaluru", "Mumbai", "Delhi")
print("Bengaluru", "Mumbai", "Delhi", sep=" | ")
print("Loading", end="...")
print("done")
print("Total:", 1250, sep="")
print(f"{'City':<12}{'Orders':>8}")
print(f"{'Bengaluru':<12}{1301:>8,}")

Output

Bengaluru Mumbai Delhi
Bengaluru | Mumbai | Delhi
Loading...done
Total:1250
City          Orders
Bengaluru      1,301

How it works: print accepts several values and puts a space between them by default. The sep argument changes that separator, and end changes what is printed at the end (normally a new line). Combining print with f-string alignment lets you draw simple tables in the console.

Reading the result: The second line shows the pipe-separated cities, the Loading...done pair ended up on one line because we replaced the line break with dots, and the last two lines form a small aligned table.

Example 10: str() versus repr()

Question: Why does a value look different when I print it or just display it?

text = "Delhi\tNCR"
print(text)
print(repr(text))
print(str(3.0), repr(3.0))
print(len(text))

Output

Delhi	NCR
'Delhi\tNCR'
3.0 3.0
9

How it works: str() (used by print) gives a friendly view, and repr() gives an unambiguous view that shows quotes and escape characters. The tab inside the text is a single character, which is why len is 9.

Reading the result: repr reveals hidden characters such as \t, which makes it a debugging tool whenever text looks right on screen but does not match as expected.

Common mistakes

1. Forgetting that input() returns a string. Convert with int() or float() before arithmetic.

2. Using int() on decimal text. Use int(float("12.5")), or float() if you want to keep the decimals.

3. Expecting bool("False") to be False. Any non-empty string is true.

print(bool("False"), bool(""))

Output

True False

4. Converting without cleaning. Strip spaces and remove symbols first.

5. Using + to join text and numbers. Use f-strings: f"Total: {total}".

Practice questions

Practice 1 (Easy): Add two text numbers

The values "250" and "175" came from a file. Print their sum as a number.

Show solution
a = "250"
b = "175"
print(int(a) + int(b))

Output

425

Without conversion, a + b would give "250175", a joined string. Converting each value with int() first gives the arithmetic sum.

Practice 2 (Medium): Percentage text to number

Convert the text "18.5%" into the float 0.185.

Show solution
text = "18.5%"
value = float(text.replace("%", "")) / 100
print(value)

Output

0.185

Remove the percent sign, convert the remainder to a float, and divide by 100 to express it as a fraction.

Practice 3 (Hard): Robust average

From ["24", "31", "n/a", "27", "", "19"], compute the average of the values that can be converted, and report how many were skipped.

Show solution
values = ["24", "31", "n/a", "27", "", "19"]
numbers, skipped = [], 0

for v in values:
    try:
        numbers.append(float(v))
    except ValueError:
        skipped += 1

average = sum(numbers) / len(numbers)
print(round(average, 2), skipped)

Output

25.25 2

Valid items go into numbers and invalid ones increase the skipped counter. The average of 4 valid values is 25.25, with 2 skipped.

Key takeaways

  • int(), float(), str() and bool() return new values of the requested type; they never change the original.
  • int() truncates toward zero, round() goes to the nearest whole number, and text must be a clean number before conversion.
  • Falsy values are False, None, zeros and empty containers; everything else, including "0" and "False", is truthy.
  • input() always returns a string, so convert it straight away.
  • Wrap risky conversions in try/except ValueError so one bad value does not stop a whole run.
  • print(sep=..., end=...) and f-string alignment control layout; repr() shows hidden characters when you debug.

Frequently asked questions

What is the difference between implicit and explicit conversion?

Implicit conversion happens automatically, such as 3 + 1.5 giving a float. Explicit conversion is when you call int(), float() or str() yourself. Python never silently converts between text and numbers, which protects you from hidden mistakes.

Why does int("3.0") fail but int(float("3.0")) work?

int() on text only accepts digits with an optional sign. Converting to a float first understands the decimal point, and then int() truncates the float to a whole number.

How do I convert to a date?

Dates have their own lesson: use datetime.strptime for single values, and pd.to_datetime for whole columns in pandas.

Is input() used in data analytics work?

Rarely in analysis notebooks, because data comes from files and databases. It is useful for small command-line tools. The conversion skills, however, are used constantly.

How can I check if a string is numeric before converting?

"42".isdigit() works for plain non-negative integers, but it fails for decimals and negatives. The try/except pattern shown above is the most reliable approach.

What does bool([0]) return?

True, because the list is not empty, even though its only element is zero. Truthiness tests whether a container is empty, not what is inside it.

Newsletter

Keep learning Python

One email a week with Python and analytics guides, new practice questions and cohort dates. No spam, unsubscribe anytime.

Ready to practise? Try the Python interview questions