Method of Accepting User Input and eval Function

Most real programs need to react to information supplied by the person running them. Python makes this easy with the built-in input() function, which pauses the program and waits for the user to type something.

The input() Function

The input() function displays an optional prompt and always returns whatever the user types as a string.

name = input("Enter your name: ")
print("Hello,", name)

Converting Input to Other Data Types

Since input() always returns a string, you need to convert it explicitly if you want to work with numbers.

age = int(input("Enter your age: "))
height = float(input("Enter your height in meters: "))
print(age + 1)

The eval() Function

The eval() function goes a step further than simple conversion. It takes a string and evaluates it as if it were a Python expression, which is useful when a user might enter a calculation rather than a single value.

expression = input("Enter an expression: ")
result = eval(expression)
print("Result:", result)
Use eval() carefully. Because it executes whatever string it is given as real Python code, it should never be used on input from an untrusted source in production systems.

Coming Up

Now that you can gather input while a program runs, the next topic covers how to work with data stored outside your program, using Python's file input and output functions.

Validating Input Until It Is Correct

Calling int() on text like "twenty" raises a ValueError and stops the program. A small loop with try and except keeps asking until the user enters something usable:

def ask_int(prompt, low=None, high=None):
    while True:
        raw = input(prompt).strip()
        try:
            value = int(raw)
        except ValueError:
            print("Please type a whole number, for example 25.")
            continue
        if (low is not None and value < low) or (high is not None and value > high):
            print(f"Enter a number between {low} and {high}.")
            continue
        return value

age = ask_int("Enter your age: ", 0, 120)
print("Next year you will be", age + 1)

Calling .strip() removes accidental spaces, and the range check rejects values that are numbers but make no sense, such as an age of 500.

Reading Several Values on One Line

In data work you often want a few numbers at once. Split the string and convert each part:

line = input("Enter marks separated by spaces: ")   # e.g. 78 85 92
marks = [float(x) for x in line.split()]
print("Average:", sum(marks) / len(marks))

# Two values unpacked directly
rows, cols = map(int, input("Rows and columns: ").split())

split() without arguments splits on any whitespace, so extra spaces between numbers do not cause problems. If the user might separate values with commas, use split(",") instead.

Safer Alternatives to eval()

The warning above is serious: eval() runs any Python expression, including ones that read files, call system functions or change data. If a script can ever receive text from someone else, such as a web form, an uploaded file or a shared notebook, treat eval() on that text as a security hole. Restricting its globals does not make it safe either, because there are well-known ways around those restrictions.

Pick a tool that does only what you need:

NeedSafer choice
Number from textint(), float(), decimal.Decimal()
A list, dict, tuple or number typed as Python syntaxast.literal_eval()
Data from files or APIsjson.loads()
Simple arithmetic from usersA small parser or a dedicated math-expression library
import ast

text = input("Enter a list of numbers, e.g. [1, 2, 3]: ")
try:
    data = ast.literal_eval(text)       # accepts only literals
    if not isinstance(data, list):
        raise ValueError("Expected a list")
    print("Total:", sum(data))
except (ValueError, SyntaxError) as err:
    print("Invalid input:", err)

ast.literal_eval() accepts strings, numbers, tuples, lists, dicts, sets, booleans and None. Anything else, such as a function call, is rejected with an error instead of being run.

Inside a data science workflow, user input usually arrives through other channels: command-line arguments read with argparse, widgets in a notebook, or a configuration file. The same rule applies to all of them. Convert values to the exact type you expect, check that they fall within a sensible range, and reject anything else with a clear message. Treating every external value as untrusted text until it passes these checks keeps both your results and your machine safe.

Input Pitfalls in Everyday Scripts

  • Adding strings by mistake. input("a") + input("b") with 5 and 3 gives "53", not 8.
  • Using int() for decimals. int("4.5") fails; use float() first.
  • No empty-input handling. Pressing Enter returns an empty string; decide on a default or ask again.
  • Blocking notebooks and pipelines. input() waits forever in scheduled jobs; read parameters from arguments or config files there.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course