Python User Input

Dec 18, 2020

User Input from the Keyboard

Python has a very handy function for obtaining user keyboard input from the CLI called input(). When called, this function allows the user to type input into your program using their keyboard.

Step 1 : Declare the following variable:

message = input()

The program execution will halt until you input a value and hit the Enter key

Step 2 : The message variable was assigned to the value that we passed. Let's print it out:


Passing in a Prompt to the input Function

You can pass a prompt to the input function to do this. The prompt is written to standard output without a trailing newline and serves as a cue for the user to pass in their input. Let's view this in action.

Step 3 : Declare the following variable, passing in the prompt Enter a tongue twister: to the input function. This will be displayed to the user:

name = input("please enter your name: ")

Using Different Input Data Types in your Program

Step 4 : To retrieve integer values from user input, all your program needs to do is cast the string that is returned as a value by the input function. Let's take a look at an example of this:

age = int(input("Please enter your age: "))