Python input() Function with Examples


How to Use the input() Function in Python

In this tutorial, you'll learn how to use the input() function in Python. This tutorial also gives you sample programs to illustrates examples of using the input() function with the IF and WHILE loop statements.

Python input() Function Syntax

input(string)

Argument

  • string: The input string representing a message before you input

Examples

Example 1: input() and print()

The following example illustrates a sample program that takes the user input and then prints to console:

#input() and print()
your_name = input ("Please enter you name:")
print("Your name is ", your_name)

Here, the program waits for the user input, and the user enters his or her name, and then the program prints to console.

Example 2: input() with IF Statement

The following sample program asks a user to input his or her password and informs the user if the password is correct or not:

#using input() function with IF ELSE loop statement
#inform a user if she or he enters the correct password
password = "12345"
input_password = input("Please enter your password:")
if password == input_password:
    #The password is correct.
    print("Your password is correct.")
else:
    #The password is not correct.
    print("Your password is not correct.")

Here, the password is 12345. The program gets the user input, and if the user enters the correct password, the program informs the user that his or her password is correct.

Example 3: input() with WHILE Loop Statement

The following program illustrates how to use the input() function with the WHILE loop statement:

#using input() function with WHILE loop statement
#wait unit a user enter the correct password.
password = "12345"
while True:
    input_password = input("Please enter your password:")
    #if a user enter the correct password, break the loop
    if password == input_password:
        break

The program waits and asks a user to input the correct password. When the user enters the correct password, the program breaks the WHILE loop and exits.

In this tutorial, you've learned how to use the input() function in Python. This tutorial also provided you examples to illustrate how to use the input function with the print() function, IF statement, and WHILE statement.

Leave a Reply

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