Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to use input in Python

Introduction

Input is an essential part of programming. It allows users to interact with programs by providing data that the program can process. In Python, there are several ways to accept input from the user, and in this tutorial, we'll discuss some of the common methods for doing so.

We'll cover the following topics:

  1. The input() function
  2. Reading from files
  3. Command line arguments

As you follow along, remember that we're writing for someone who's learning programming, so we'll avoid using jargon and will explain any terms that might be new to you. We'll also give actual code examples, intuitions, and analogies to help you understand the concepts.

So let's get started!

The input() Function

The input() function is a built-in Python function that allows you to accept input from the user. It takes a single argument, which is the prompt that will be displayed to the user, and returns a string containing the user's input.

Here's a simple example:

name = input("Please enter your name: ")
print("Hello, " + name + "!")

In this code snippet, we first call the input() function with the prompt "Please enter your name: ". This will display the prompt to the user, and then wait for them to enter some text and press Enter. Once they do, the input they entered will be stored as a string in the name variable. We then use the print() function to display a greeting that includes the user's name.

Converting Input to Other Data Types

Since the input() function always returns a string, you'll often need to convert the input to the appropriate data type for your program. For example, if you're expecting the user to enter a number, you'll need to convert the string to a numerical data type like an integer or a float.

Here's an example of how to accept an integer as input:

age_string = input("Please enter your age: ")
age = int(age_string)
print("You are " + str(age) + " years old.")

In this example, we first call the input() function with the prompt "Please enter your age: ". The user's input is then stored as a string in the age_string variable. We then use the int() function to convert the string to an integer and store it in the age variable. Finally, we use the print() function to display the user's age, converting the integer back to a string using the str() function.

Similarly, if you need to accept a floating-point number as input, you can use the float() function to convert the string to a float:

weight_string = input("Please enter your weight in kilograms: ")
weight = float(weight_string)
print("You weigh " + str(weight) + " kilograms.")

Handling Errors in User Input

When accepting input from users, it's important to handle cases where they might enter incorrect or unexpected data. For example, if your program expects the user to enter a number, they might accidentally enter some text instead, which would cause an error when you try to convert the input to a numerical data type.

To handle these cases, you can use a try-except block to catch and handle any errors that occur during the conversion. Here's an example of how to handle errors when converting a user's input to an integer:

try:
    age_string = input("Please enter your age: ")
    age = int(age_string)
    print("You are " + str(age) + " years old.")
except ValueError:
    print("Invalid input. Please enter a number.")

In this example, we've wrapped the input() and int() function calls in a try block. If the user enters a valid number, the program will proceed as normal. However, if they enter something that can't be converted to an integer, a ValueError will be raised, and the code in the except block will be executed. This allows us to display an error message to the user and continue running the program.

Reading from Files

Another common way to accept input in Python is by reading data from a file. This can be useful when you need to process large amounts of data or when you want to store the input data in a more structured format.

To read data from a file, you'll first need to open the file using the open() function. This function takes two arguments: the name of the file you want to open, and the mode in which you want to open the file. The mode can be either 'r' for reading, 'w' for writing, or 'a' for appending. In this tutorial, we'll focus on reading files, so we'll use the 'r' mode.

Here's an example of how to read data from a file called input.txt:

file = open("input.txt", "r")
content = file.read()
file.close()

print("The content of the file is:")
print(content)

In this example, we first call the open() function with the name of the file we want to open ("input.txt") and the mode in which we want to open it ("r"). This returns a file object, which we store in the file variable. We then call the read() method on the file object to read the entire content of the file into a string, which we store in the content variable. After that, we call the close() method on the file object to close the file, and finally, we use the print() function to display the content of the file.

Reading Files Line by Line

In some cases, you might want to read the data from a file line by line, rather than reading the entire file at once. This can be useful when working with large files or when you want to process the data as you read it.

To read a file line by line, you can use a for loop to iterate over the file object. Each iteration of the loop will read one line from the file, which you can then process as needed.

Here's an example of how to read a file called input.txt line by line:

file = open("input.txt", "r")

print("The content of the file is:")
for line in file:
    print(line.strip())

file.close()

In this example, we first open the file as before, and then use a for loop to iterate over the file object. Each iteration of the loop reads one line from the file, which we store in the line variable. We then use the strip() method to remove any leading or trailing whitespace from the line, and the print() function to display the line. Finally, we close the file as before.

Command Line Arguments

The third method of accepting input in Python is by using command line arguments. These are values that the user can pass to your program when they run it from the command line. Command line arguments can be useful when you want to allow the user to customize the behavior of your program or when you want to run your program as part of a larger script or pipeline.

In Python, you can access command line arguments through the sys.argv list. This list contains the name of your program as its first element, followed by any command line arguments that the user provided. To use sys.argv, you'll first need to import the sys module.

Here's an example of how to use command line arguments to customize the behavior of a simple program:

import sys

if len(sys.argv) != 3:
    print("Usage: python example.py [input_file] [output_file]")
    sys.exit(1)

input_file = sys.argv[1]
output_file = sys.argv[2]

print("Reading from " + input_file + " and writing to " + output_file + ".")

In this example, we first import the sys module, which provides access to the sys.argv list. We then check if the length of sys.argv is equal to 3, which means that the user should have provided two command line arguments (in addition to the name of the program). If the number of arguments is incorrect, we display a usage message and exit the program with an error code of 1.

If the number of arguments is correct, we use indexing to access the two command line arguments and store them in the input_file and output_file variables. We then use the print() function to display a message indicating which files the program will read from and write to.

Conclusion

In this tutorial, we discussed three methods for accepting input in Python:

  1. The input() function, which allows you to accept input from the user interactively.
  2. Reading from files, which allows you to process large amounts of data or structured input.
  3. Command line arguments, which allow the user to customize the behavior of your program when running it from the command line.

We also provided code examples and explanations for each method, along with tips for handling errors and converting input to the appropriate data types.

Now that you're familiar with these methods, you should be able to create more interactive and flexible programs in Python. Good luck, and happy coding!