Read input as an integer in Python

Python | read/take input as an integer (number): Here, we are going to learn how to read input as an integer in Python? By IncludeHelp Last updated : December 17, 2023

Input in Python

To take input in Python, we use input() function, it asks for an input from the user and returns a string value, no matter what value you have entered, all values will be considered as strings values.

Example

Consider the following example,

# python code to demonstrate example
# of input() function

val1 = input("Enter any value: ")
print("value of val1: ", val1)
print("type of val1: ", type(val1))

val2 = input("Enter another value: ")
print("value of val2: ", val2)
print("type of val2: ", type(val2))

val3 = input("Enter another value: ")
print("value of val3: ", val3)
print("type of val3: ", type(val3))

Output

Enter any value: 10
value of val1:  10
type of val1:  <class 'str'>
Enter another value: 10.23
value of val2:  10.23
type of val2:  <class 'str'>
Enter another value: Hello
value of val3:  Hello
type of val3:  <class 'str'>

See the program and output – Here, we provided three value "10" for val1 which is an integer value but considered as a string, "10.23" for val2 which is a float value but considered as a string, "Hello" for val3 which is a string value.

How to take input as integer?

There is no such method, that can be used to take input as an integer directly – but input string can be converted into an integer by using int() function which accepts a string and returns an integer value.

Thus, we use input() function to read input and convert it into an integer using int() function.

Example to read input as an integer in Python

# python code to take integer input

# reading a value, printing input and it's type
val1 = input("Enter any number: ")
print("value of val1: ", val1)
print("type of val1: ", type(val1))

# reading a value, converting to int
# printing value and it's type
val2 = int(input("Enter any number: "))
print("value of val2: ", val2)
print("type of val2: ", type(val2))

Output

Enter any number: 123
value of val1:  123
type of val1:  <class 'str'>
Enter any number: 456
value of val2:  456
type of val2:  <class 'int'>

Example to input two integer numbers and find their sum and average

# python code to read two integer numbers
# and find their addition, average

num1 = int(input("Enter first number : "))
num2 = int(input("Enter second number: "))

# addition
add = num1 + num2

# average
avg = float(num1 + num2)/2

print("addition: ", add)
print("average : ", avg)

Output

Enter first number : 3
Enter second number: 4
addition:  7
average :  3.5

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.