Learn How to Capture Text from Users and Make Your Programs Interactive

This tutorial will guide you through the process of collecting text input from users in your Python programs. We’ll explore the input() function, how it works with strings, and provide practical exa …

Updated August 26, 2023



This tutorial will guide you through the process of collecting text input from users in your Python programs. We’ll explore the input() function, how it works with strings, and provide practical examples to get you started.

Welcome to the exciting world of interactive Python programming!

So far, we’ve been working with pre-defined data. But what if we want our programs to be more dynamic and respond to user actions? That’s where user input comes in. Python allows us to capture text entered by the user through the keyboard using a special function called input().

Understanding Strings:

Before we dive into input(), let’s quickly recap what strings are in Python:

  • Strings: Think of them as sequences of characters enclosed in single (’) or double (") quotes. Examples: “Hello, world!”, ‘Python is fun!’.

The Power of input():

The input() function pauses the execution of your program and waits for the user to type something into the console (the window where you run Python code) and press Enter. Whatever the user types is captured as a string.

Here’s a simple example:

name = input("What's your name? ")
print("Hello,", name + "!") 

Let’s break down what happens:

  1. name = input("What's your name? "): This line does two things:

    • It displays the message “What’s your name?” on the screen, prompting the user for input.
    • The text entered by the user is stored in a variable named name.
  2. print("Hello,", name + "!"): This line greets the user by combining the string “Hello,” with the value stored in the name variable and adding an exclamation mark.

Typical Mistakes:

  • Forgetting Quotes: If you don’t enclose strings within quotes, Python will throw an error.
  • Assuming Input is a Number: input() always returns a string. If you need to perform calculations, you’ll have to convert the input string to a numerical type (like an integer or float) using functions like int() or float().

Example: Converting Input to a Number

age_str = input("How old are you? ")
age = int(age_str)  # Convert the string to an integer
print("You will be", age + 1, "next year!")

Key Points:

  • User input is captured as a string, even if the user enters numbers.
  • You can use variables to store and reuse user input.
  • Use functions like int() or float() to convert strings to numerical types when necessary.

Now you’re equipped with the knowledge to make your Python programs interactive! Experiment with different prompts and see what creative ways you can incorporate user input into your code.


Stay up to date on the latest in Computer Vision and AI

Intuit Mailchimp