Salvatore Lopiparo

Software Engineer

Super Simple Python – Input

One of the ways to make your program more interesting is to have some kind of input from the user. There are many ways to have input, including a GUI (or Graphical User Interface), and reading from a file (which we covered in a previous SSP). Another way is to get input directly from the user on the command line using the input() function.

Luckily, input() is one of the easiest ways to get information from the user. We simply assign the function call to a variable, type our message when the prompt comes up, and Python takes care of the rest.

>>> user_input = input()
>? Hello world!
>>> print(user_input)
Hello world!

input() returns whatever the user types into the console as a string. It also takes an optional argument for a text prompt, which lets us tell the user what they should type.

 >>> full_name = input("What is your first and last name?")
What is your first and last name?
>? Frank Sinatra
>>> first_name, last_name = full_name.split()
>>> print("Hello {0}!".format(first_name))
Hello Frank!

This works as long as the user gives valid information. If they also give their middle name, we’re in trouble!

>>> full_name = input("What is your first and last name?")
What is your first and last name?
>? Frank Albert Sinatra
>>> first_name, last_name = full_name.split()
ValueError: too many values to unpack (expected 2)

A common way to account for this is to continue to ask the user for input until they give something that is valid. We can accomplish this by using a while loop.

first_name = ""
last_name = ""
while not (first_name and last_name):
    full_name = input("What is your first and last name?")
    split_name = full_name.split()
    if len(split_name) == 2:
        first_name, last_name = split_name
    else:
        print("Invalid input. Please give your first and last names only!")
print("Hello {0}!".format(first_name))

This will give us some interaction like the following:

What is your first and last name?
>? Frank Albert Sinatra
Invalid input. Please give your first and last names only!
What is your first and last name?
>? Torel Twiddler
Hello Torel!

DROP A COMMENT

Your email address will not be published. Required fields are marked *