Explain User Input & Type Casting in Python | Command Line Input | Python Tutorial for Beginners

Explain User Input & Type Casting in Python | Command Line Input | Python Tutorial for Beginners



In Python, you can get input from the user using the input() function. This function reads a line of text from the standard input (usually the keyboard) and returns it as a string. You can use the input() function to ask the user for a piece of information and store it in a variable. For example:


Copy code

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

print("Hello, " + name + "!")

This code will ask the user for their name and store it in the name variable. Then, it will print a greeting using the user's name.


If you want to get a number from the user, you can use the input() function to read a string and then use type casting to convert it to a number. Type casting is the process of converting a value from one data type to another.


For example, to read an integer from the user, you can use the int() function to convert the input string to an integer.


Copy code

age = int(input("What is your age? "))

print("You are " + str(age) + " years old.")

To read a float from the user, you can use the float() function to convert the input string to a float.


Copy code

pi = float(input("What is the value of pi? "))

print("The value of pi is approximately " + str(pi) + ".")

You can also use type casting to convert a number to a string. For example:


Copy code

x = 10

y = 3.14


a = str(x)   # Convert integer to string ('10')

b = str(y)   # Convert float to string ('3.14')

Keep in mind that type casting can fail if the input value is not compatible with the target data type. For example, if you try to convert a string that contains letters to an integer using the int() function, it will raise a ValueError exception.


Copy code

x = int(input("Enter an integer: "))   # ValueError if the input is not an integer

You can use the try and except statements to handle these errors and provide a graceful way to handle them.


Copy code

try:

    x = int(input("Enter an integer: "))

except ValueError:

    print("Invalid input. Please enter an integer.")

I hope this helps! Let me know if you have any questions.

Comments