1. python
  2. /basics
  3. /user-input

The Basics of User Input in Python

Getting Started

User input is a basic yet neat component in Python. Whether you're building a simple calculator or something slightly more complex, you'll need to be able to take input from a user and make decisions based on it.

Naturally, that's where the input() function comes in. As a built-in feature, it lets us take input from a user, and when it's called, the program stops and waits for the user to type something into the console. Whatever the user types is then converted and stored in a variable for later use.

name = input("What's your name? ")
print("Nice to meet you, " + name + "!")

Converting the Value of User Input

Bear in mind that input() always returns the input as a string, even if our user enters a number. So, to use the input as a number, we'll have to convert it to an integer or float. Let's illustrate:

age = int(input("How old are you? "))
print("Wow, you're already " + str(age) + " years old!")

As we can see, we use the int() function to convert the user's input from a string to an integer. Then, we leverage the str() function to convert the age variable back into a string so that we can concatenate it with our greeting.

Let's also convert the user input to a float:

height = float(input("Please enter your height in meters: "))
print("Your height is " + str(height) + " meters.")

Printing in Python

You'll notice the print() function a lot, as we'll use it to show the output of each example, and check the data type, as well as other use cases.

python_creator = "Guido van Rossum"

print(python_creator) # Output: Guido van Rossum

print(type(python_creator)) # Output: <class 'str'>

There are plenty of ways to customize the output and make it look just the way we want. For instance, if you want to print multiple lines of text using the print function, you can use the end parameter to specify the end character. By default, end='\n' is used to print each statement on a new line. To print multiple statements on the same line, we use end=' '.

print("Hello world, ", end=' ')
print("Python is awesome!")

# Output: Hello world,  Python is awesome!

Guess the Number Game

Now, let's combine all of this with other essential Python concepts to create a simple game. The objective of the game is to guess a randomly generated number between 1 and 100.

import random

print("Welcome to the Guess the Number game!")
print("I'm thinking of a number between 1 and 100. Can you guess what it is?")

number = random.randint(1, 100)
guess = 0
tries = 0

while guess != number:
    tries += 1
    guess = int(input("Enter your guess: "))
    if guess < number:
        print("Too low. Try again!")
    elif guess > number:
        print("Too high. Try again!")

print(f"Congratulations! You guessed the number in {tries} tries.")

In our game, we first import the random module to generate a random number between 1 and 100. We then prompt the user to guess the number and initialize some variables to keep track of the number of tries and the user's guess.

Note that we have to utilize the while loop to repeatedly ask the user for their guess and check if it matches the randomly generated number. If the guess is too low or too high, we give the user a hint and ask them to try again. Once the user correctly guesses the number, we print a congratulatory message and display the number of tries it took to guess the number.

Also, this game can be easily customized by changing the range of the randomly generated number, adding more hints or difficulty levels, or even incorporating graphics or sound effects to make it more engaging.

Final Thoughts

Lastly, we encourage you to play around with the examples and test them out in your preferred environment. Remember, in this article, we primarily focused on the basics of user input in Python. The topic of input and output in Python is much more extensive, including more advanced concepts like file I/O, exceptions, and formatting. If you're eager to learn more, check out the official Python documentation, as well as some other useful resources to deepen your Python knowledge.

Additional Resources

Strings in Python

The Basics of Variables in Python

Control Flow Basics in Python - A Guide to Loops

The Basics of Conditional Statements in Python