User Input

User Input

In Python, you can get user input using the input() function. The input() function waits for the user to type something and press enter. Whatever the user types is returned as a string. For example:

pythonCopy codename = input("What is your name? ")
print(f"Hello, {name}!")

In this example, the input() function prompts the user to enter their name, and the user’s input is stored in the name variable. The print() function then outputs a greeting message to the console.

Note that the input() function always returns a string, even if the user enters a number or some other type of input. If you need to convert the user’s input to a different data type, you can use functions like int(), float(), or bool() to convert the input to the desired type. For example:

pythonCopy codeage = int(input("What is your age? "))
if age >= 18:
    print("You are an adult.")
else:
    print("You are not yet an adult.")

In this example, the input() function prompts the user to enter their age, and the int() function is used to convert the user’s input to an integer. The program then checks if the user is an adult based on their age and outputs an appropriate message to the console.

It’s important to note that the input() function can be dangerous if you don’t validate or sanitize the user’s input, as it can be used to execute malicious code or crash your program. Always make sure to validate and sanitize user input before using it in your program.

Apply for Python Certification!

https://www.vskills.in/certification/certified-python-developer

Back to Tutorials

Forms
User Input Validation

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?