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.

Ready to Master Data Science?

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

Explore Course