READ INPUT AS INTEGER IN PYTHON

INTRODUCTION:

To get an input as an integer one uses the input() in python. to promote the user and then converts the input to an integer using the int() function.

Process:

This process involves several steps to ensure the input is correctly received and converted. We can directly give the values in a program or we can also get the input from the user. When we get the user input, the program prompts the user to enter some value. The input() is used for this purpose. When the user types their responds and press enter the input() captures this input as a string. Then the program needs to covert this into an integer.

So the user could use the int(). Sometimes the input given by the user may not be valid in that case the user can use a try-catch  block. This structure allows the program to attempt the conversion and catch the value error exceptions that occur, providing an opportunity to respond with the error message and prompt the user again.

For better understanding let us try to understand a simple addition program without using the int() function.

num1 = input("enter the first number:")
num2 = input("enter the second number:")
result = num1 + num2
print("the result is:",result)
output:

enter the first number: 10
enter the second number: 20
the result is: 1020

Here in this program, the input from the user input is considered to be a string ,so the result is given as a string. In the next program we will use the int()  function so that the result will be given in the form of integer.

A = int(input("enter the number:"))
B = int(input("enter the number:"))
C = A+B
print("the result is:" , C)
output:

enter the number: 10

enter the number: 20

the result is: 30

Leave a Comment

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

Scroll to Top