string. Please note that the type() function in Python returns the data type of a variable.
So, how should we get an integer or float or other data type as input? We can use explicit typecasting for that purpose.
number = input("Number: ")
print("You entered: " + number)
print(type(number))
number = int(number)
print(type(number))
The program will print the following output:
Number: 57 You entered: 57 <class 'str'> <class 'int'>
Here, we are giving 57 as input. The input() function returns the string โ57โ. So, the initial data type of the variable โnumberโ is a string. Then, we are using explicit typecasting (What are implicit and explicit typecasting in Python?) to convert the string value into an integer. So, finally, the data type of the variable โnumberโ becomes an integer. Now, we can perform integer operations on the variable number.
Similarly, if we want to accept a float as input, we can do the following:
number = input("Number: ")
number = float(number)
print("You entered: %.2f" % number)
print(type(number))
Here, the input() function initially returns a string. We are doing explicit typecasting to convert the string into float. And, then we are printing the float value. Please note that we are using โ%.2fโ to print the float value after rounding off up to 2 decimal places. So, the above program will print the following output with the mentioned input:
Number: 34.56788 You entered: 34.57 <class 'float'>








































0 Comments