Python Logo

User Input


To take user input in Python, you can use the input() function. The input() function prompts the user for input and returns the user's input as a string.

Example:

 

Python

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

print(f"Hello, {name}!")
 

This code will prompt the user for their name and then print a greeting to them.

Getting numeric input

If you need to get numeric input from the user, you can use the int() or float() functions to convert the user's input to a number.

Example:

 

Python

age = int(input("How old are you? "))

if age >= 18:
    print("You are an adult.")
else:
    print("You are not an adult yet.")
 

This code will prompt the user for their age and then print a message to them based on their age.

Validating user input

It is important to validate user input before using it in your program. This is because the user may enter invalid input, such as an empty string or a non-numeric value.

Example:

 

Python

def get_user_input(prompt):
    while True:
        user_input = input(prompt)

        if user_input:
            return user_input
        else:
            print("Please enter a valid input.")

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

print(f"Hello, {name}!")
 

This code will prompt the user for their name and keep prompting them until they enter a valid input.

Conclusion

Python provides a number of ways to take user input. By understanding how to use user input, you can write more interactive and user-friendly programs.