Python’s input() Function

Learn Python @ Freshers.in

Python’s input() function is a built-in method that allows user input from the keyboard. It’s a powerful tool for creating interactive programs and gathering data dynamically. In this comprehensive guide, we’ll explore the functionalities of input() with detailed examples to help you understand its usage thoroughly.

Basic Usage:

# Example 1: Getting user input and displaying it
name = input("Enter your name: ")
print("Hello,", name)

Output:

Enter your name: John
Hello, John

In this example, input() prompts the user to enter their name, and the entered value is stored in the variable name.

Converting Input to Desired Data Type:

# Example 2: Converting input to an integer
age = int(input("Enter your age: "))
print("You are", age, "years old.")

Output:

Enter your age: 25
You are 25 years old.

input() returns a string, so if you need to work with numerical values, you can convert the input using functions like int() or float().

Using input() in Loops:

# Example 3: Using input() in a loop
numbers = []
for _ in range(3):
    num = int(input("Enter a number: "))
    numbers.append(num)
print("Numbers entered:", numbers)

Output:

Enter a number: 5
Enter a number: 10
Enter a number: 15
Numbers entered: [5, 10, 15]

input() can be used within loops to repeatedly prompt the user for input, allowing the collection of multiple values.

Error Handling:

# Example 4: Handling invalid input
while True:
    try:
        num = int(input("Enter a number: "))
        break
    except ValueError:
        print("Invalid input. Please enter a valid number.")
print("You entered:", num)

Output:

Enter a number: abc
Invalid input. Please enter a valid number.
Enter a number: 42
You entered: 42

Using a try-except block, you can handle potential errors when the user enters invalid input.

Enhancing User Experience:

# Example 5: Providing a default value with input()
response = input("Would you like to proceed? (yes/no): ").lower()
if response == 'yes':
    print("Great! Let's continue.")
elif response == 'no':
    print("Okay, maybe next time.")
else:
    print("Invalid response. Please enter 'yes' or 'no'.")

Output:

Would you like to proceed? (yes/no): maybe
Invalid response. Please enter 'yes' or 'no'.

By providing a default value or instruction within the prompt, you can guide users and improve the interaction flow.

Author: user