Introduction to Python User Input

User input is any data that you get from the user of your program, such as their name, age, preferences, etc. User input can make your program more interactive and dynamic, as well as more personalized and user-friendly.

In this blog post, I will show you how to use the input() function in Python to get user input.

Table of Contents

The input() Function Syntax

The input() function is a built-in function that allows you to prompt the user for a value and store it in a variable. The syntax of the input() function is:

variable = input(prompt)

Where:

  • variable is the name of the variable that will hold the user input, and
  • prompt is the message that you want to display to the user.

For example, if you want to ask the user for their name, you can write:

name = input("What is your name? ")

The input() function will display the prompt “What is your name? ” on the screen and wait for the user to type something and press enter. Whatever the user types will be assigned to the variable name.

Working With User Input

You can then use the variable name in your program, such as printing it or concatenating it with other strings. For example:

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

This will output something like:

What is your name? > Alice
Hello, Alice!

Data Type Conversion

You can also use the input() function to get other types of data from the user, such as numbers, booleans, or lists.

However, you need to be careful about the data type of the user input, because the input() function always returns a string.

This means that if you want to use the user input as a number, you need to convert it to a numeric data type using functions like int(), or float().

Example: Asking the user for their age

For example, if you want to ask the user for their age and calculate how old they will be in 10 years, you can write:

age = input("How old are you? ")
age = int(age) # convert the string to an integer
future_age = age + 10
print("In 10 years, you will be " + str(future_age) + " years old.")

This will output something like:

How old are you? > 25
In 10 years, you will be 35 years old.

Example: Expecting a boolean value from user

Similarly, if you want to use the user input as a boolean value, you need to convert it to a bool data type using functions like bool(). For example, if you want to ask the user if they like Python and print a different message depending on their answer, you can write:

like_python = input("Do you like Python? (yes/no) ")
like_python = bool(like_python.lower() == "yes") # convert the string to a boolean

if like_python:
    print("That's great! Python is awesome!")
else:
    print("That's too bad. Python is fun and easy to learn.")

This will output something like:

Do you like Python? (yes/no) > yes
That's great! Python is awesome!

Example: Expecting a list from user

Finally, if you want to use the user input as a list, you need to convert it to a list data type using functions like list(), split(), or eval().

For example, if you want to ask the user for their favorite colors and print them in reverse order, you can write:

colors = input("What are your favorite colors? (separate them by commas) ")
colors = list(colors.split(",")) # convert the string to a list
colors.reverse()
print("Your favorite colors in reverse order are: " + ", ".join(colors))

This will output something like:

What are your favorite colors? (separate them by commas) > red, green, blue
Your favorite colors in reverse order are: blue, green, red

Examples and Projects

To demonstrate the concepts we learned, let’s look at some examples and projects that use user input in Python.

Mad Libs Game

A Mad Libs game is a word game where the user fills in the blanks of a story with their own words. For example:

One day, I went to the [place] with my [adjective] friend. We saw a [noun] that was [verb]ing. It was so [adjective]!

To implement this game, we can use the input() function to ask the user for different types of words and store them in variables. Then, we can use string formatting to insert them into the story template. For example:

place = input("Enter a place: ")
adj1 = input("Enter an adjective: ")
noun = input("Enter a noun: ")
verb = input("Enter a verb ending in -ing: ")
adj2 = input("Enter another adjective: ")

story = f"One day, I went to the {place} with my {adj1} friend. We saw a {noun} that was {verb}ing. It was so {adj2}!"

print(story)

The output of this game will look something like this:

Enter a place: park
Enter an adjective: funny
Enter a noun: dog
Enter a verb ending in -ing: running
Enter another adjective: cute
One day, I went to the park with my funny friend. We saw a dog that was running. It was so cute!

Number Guessing Game

A number-guessing game is a game where the computer randomly chooses a number and the user tries to guess it. The computer gives feedback on whether the guess is too high, too low, or correct. For example:

I'm thinking of a number between 1 and 100.
Guess the number: 50
Too low.
Guess the number: 75
Too high.
Guess the number: 63
You got it!

To implement this game, we can use the random module to generate a random number and store it in a variable. Then, we can use a loop to get user input and compare it to the random number. We can also keep track of the number of guesses and limit them to a certain amount. For example:

import random

number = random.randint(1, 100)
guesses = 0
limit = 10

print("I'm thinking of a number between 1 and 100.")

while guesses < limit:
    guess = int(input("Guess the number: "))
    guesses += 1
    if guess == number:
        print("You got it!")
        break
    elif guess < number:
        print("Too low.")
    else:
        print("Too high.")

if guesses == limit:
    print(f"Sorry, you ran out of guesses. The number was {number}.")

I hope this blog post was helpful and informative for you. If you have any questions or comments, please feel free to leave them below. Happy coding!

Stephen Mclin
Stephen Mclin

Hey, I'm Steve; I write about Python and Django as if I'm teaching myself. CodingGear is sort of like my learning notes, but for all of us. Hope you'll love the content!

Articles: 125

Leave a Reply

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