Getting Input In Python

 


In Python, you can get input from the user using the built-in function input(). This function reads a line of text entered by the user and returns it as a string.

Basic Input Usage:

  • Getting Input from the User:

    user_input = input("Enter something: ")

  • print("You entered:", user_input)

  1.  Here, the input() function displays the prompt message (in this case, "Enter something:"), waits for the user to type something, and then captures the input as a string.

  2. Converting the Input to Other Data Types: Since the input is always returned as a string, if you need the input to be of a different type (such as an integer or float), you can convert it using functions like int() or float().

  • Integer Input:

    age = int(input("Enter your age: "))

  • print("Your age is:", age)


  • Float Input:

    height = float(input("Enter your height: "))

  • print("Your height is:", height)


Example: Getting Multiple Inputs:

You can get multiple inputs at once and process them:

  • name, age = input("Enter your name and age: ").split(", ")

  • print("Name:", name)

  • print("Age:", age)


In this example, the split(", ") method splits the input string at the comma and space to separate the name and age.

Error Handling:

If the user enters a value that cannot be converted to the required type, you'll get an error. To handle this gracefully, you can use a try/except block.

  • try:

  •     age = int(input("Enter your age: "))

  •     print("Your age is:", age)

  • except ValueError:

  •     print("Please enter a valid number.")


Example of Getting Input for a Simple Program:

Here's a simple program where you ask the user for their name and age, then calculate the year they were born:

  • name = input("Enter your name: ")

  • age = int(input("Enter your age: "))

  • birth_year = 2025 - age

  • print(f"Hello {name}, you were born in {birth_year}.")


Key Points:

  • The input() function always returns a string.

  • You can convert the string to other types like int(), float(), etc., as needed.

  • You can use .split() to split a single input into multiple values.

  • You can handle invalid input with try/except.

Let me know if you'd like any further explanation on how to get input in Python! 😊


Post a Comment

0 Comments