Taking Input From Console in Python

A console is a command-line interpreter that takes input from the user (one command at a time) and interprets the input provided. If the input is error-free, the console executed the command and gives the desired output. In case of an error, it shows an error message. Below is a sample of a console.

To execute the command, we press the enter key, and the command gets interpreted. Understanding the basics of the console is necessary to do coding in Python.

The primary prompt of the Python console is the three successive greater than symbols (>>>). Python Console will only accept commands after the prompt.

Accepting Input from Console:

The users enter the value in the console, and it is used in the program as per requirement.

Built in function input() is used to take input from users.

# input

input1 = input()

# output

print(input1)

Typecasting the input to integer, float or string is possible by specifying the input() function inside the type.

  1. Typecasting input to integer: There might be a requirement of integer input from user/console. The code to take two input(integer/float) from the console and typecast them to integer and then print the sum is given below.

# input

num1 = int(input())

num2 = int(input())

# printing the sum in integer

print(num1 + num2)

  1. Typecasting input to float: The following code is used to convert the input to float.

# input

num1 = float(input())

num2 = float(input())

# printing the sum in float

print(num1 + num2)

  1. Typecasting input to string: All kinds of input can be converted to a string. The keyword str is used for typecasting.

# input

string = str(input())

# output

print(string)

Leave a Reply

Your email address will not be published. Required fields are marked *