Skip to main content
  • Python is available now. All other compilers are coming soon.

    Python
  • Popular Tutorials

    • Getting Started With Python
    • Python if Statement
    • while Loop in Python
    • Python Lists
    • Dictionaries in Python
    All Python Tutorials

    Reference Materials

    Built-in FunctionsList MethodsDictionary MethodsString Methods
    View all

Online Compilers

  • Python Compiler
  • Python Playground
  • Python Projects
  • Exercises

Tutorials

  • Learn Python
  • Python for Beginners
  • Variables and Types
  • Python Strings
  • Python Lists
  • Python If Else
  • Python For Loops
  • Python Functions
  • Python Classes

Examples

  • Python Examples
  • Hello World
  • Add Two Numbers
  • Even or Odd
  • Factorial
  • Fibonacci
  • Prime Check
  • Palindrome Check

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Use
  • Disclaimer

© 2026 ILoveCompiler. All rights reserved.

  1. Home
  2. Python Tutorial
  3. Python Type Conversion and Input Values

Core Python · Tutorial 6

Python Type Conversion and Input Values

Convert between strings, integers, and floats safely, and understand which conversions can fail.

Open the compilerPractice exercises
beginner7 min readUpdated November 19, 20263 learning goals
On this page
  1. Numeric conversions
  2. Booleans from other values
  3. Safe conversion
  4. Converting collections
  5. Rounding versus formatting
  6. Practice

What you will learn

  • Convert values with int(), float(), str(), and bool()
  • Explain why input() returns a string
  • Handle conversion failures with try/except
Before this lesson: Python Variables and Data Types, Python Numbers and Arithmetic Operators

input() always returns a string. Even if the user types 42, the program receives the four characters "42". Convert the text before doing arithmetic.

Python
age_text = input("Your age: ")
age = int(age_text)
print(age + 1)

Numeric conversions#

Python
print(int("42"))       # 42
print(int(3.9))        # 3: truncates toward zero
print(float("2.5"))    # 2.5
print(float(7))        # 7.0
print(str(42))         # "42"
print(str(True))       # "True"

int("3.5") raises ValueError because the text is not a valid integer literal. Convert to float first if decimals are possible:

Python
value = int(float("3.5"))  # 3

Be aware that this silently truncates. Decide whether that is acceptable for the task.

Booleans from other values#

bool() converts values by truthiness:

Python
print(bool(0))        # False
print(bool(1))        # True
print(bool(""))       # False
print(bool("False"))  # True: non-empty string
print(bool([]))       # False
print(bool(None))     # False

The string "False" is non-empty, so it is truthy. To parse a yes/no answer, compare the text explicitly.

Safe conversion#

Invalid input should not crash the whole program. Use try and except:

Python
text = input("Enter a whole number: ")

try:
    number = int(text)
except ValueError:
    print("That was not a whole number.")
else:
    print(f"Double is {number * 2}")

The else block runs only when no exception occurred. Put as little code as possible inside try.

Do not use eval() for user input

eval() executes arbitrary Python expressions. For numbers, use int() or float(). For structured data, use json.loads() with validation.

Converting collections#

Python
letters = list("abc")           # ['a', 'b', 'c']
numbers = list(map(int, ["1", "2", "3"]))
text = " ".join(["Python", "rocks"])

map() applies a conversion to each item lazily. Wrapping it in list() materialises the results.

Rounding versus formatting#

round(value, 2) returns a float. An f-string with .2f produces display text:

Python
value = 3.14159
print(round(value, 2))    # 3.14
print(f"{value:.2f}")     # 3.14

Use formatting for output and keep full precision in calculations unless the problem requires rounding at each step.

Practice#

Ask for a price and a quantity. Convert the price to float and the quantity to int, then print the total with two decimal places. If either conversion fails, print a clear message instead of a traceback.

Previous tutorialPython Strings: Creation, Indexing, and SlicingNext tutorialReading User Input with Python input()

Related tutorials

beginner

Reading User Input with Python input()

Read text and numbers from standard input, understand prompts, and design programs that handle supplied input cleanly.

7 min read
beginner

Python Strings: Creation, Indexing, and Slicing

Create strings, access characters, take slices, use escapes, and explore common string operations.

9 min read

On this page

  1. Numeric conversions
  2. Booleans from other values
  3. Safe conversion
  4. Converting collections
  5. Rounding versus formatting
  6. Practice

Run the examples

Every Python block has a Run in compiler button that opens the code in a new tab.