What is Console in Python?

The console (also called Shell) is essentially a command line interpreter that takes input from the user, executing one command at a time. If the command is error-free, it runs and provides the required output; otherwise, it displays an error message. A Python console typically looks like this:

>> 

You can write your next command in the shell only when these prompts appear after executing the first command. The Python Console accepts commands that you write after the prompt.

Accepting Input from Console

To accept input from the user, we utilize the built-in function input(). The user enters values in the console, which can then be used in the program as needed.

input_value = input()
print(input_value)
        

1. Typecasting the Input to Integer

In scenarios where you require integer input, you can typecast the input using int(). The following code takes two inputs from the console, typecasts them to integers, and then prints their sum:

num1 = int(input())
num2 = int(input())
print(num1 + num2)
        

2. Typecasting the Input to Float

To convert input to a float, you can use the float() function. Here’s how it works:

num1 = float(input())
num2 = float(input())
print(num1 + num2)
        

3. Typecasting the Input to String

All types of input can be converted to a string using str(). You can take input as a string by simply using the input() function, which defaults to string type:

string_value = str(input())
print(string_value)

# Or by default
string_default = input()
print(string_default)
        

Conclusion

Understanding how to take input from the console in Python is essential for developing interactive applications. The input() function allows you to gather user input efficiently, and typecasting enables you to handle various data types as per your program's requirements. With the provided examples, you can easily implement user input handling in your Python projects.