int function | Sololearn: Learn to code for FREE!


int function

Why is it necessary to use the "int" function (in Python), when you can still display numbers and use them without using the "int" function?

3/3/2018 5:38:46 PM


5 Answers

New Answer


int(x) converts the argument into an integer, specifically. You can have strings: "337" and "56" and you can surely display them no problem. But if you want to do calculations, so treat those as numbers, you have to convert to int. Otherwise they will be treated as strings and you might not get what you want :) Let's see two examples: a = "23" b = "45" c = 23 d = 45 print(a + b) # ==> 2345 print(c + d) # ==> 68 See the difference? ;)


Bcoz later on "you"(programmer) won't be the one entering the values, but rather the user. User input (example, his age) will be input as a string. It will the job of the programmer to convert it to integer as above for further processing.


Thank you all for your answers.


Well, when using the input function, the value that the user enters will always be returned as a string. To counteract this, you can use the int() function surrounding the input() function to make sure that whatever the user enters will be returned as an int. This is usually used if you want a number to be entered, allowing you to do calculations and comparisons that you wouldn't be able to do with a string. For example: x = int(input()) y = int(input()) print(str(x + y)) #Adds the values of x and y Hope this helped!


I'm sorry to correct all of you, but int(x) calls int.__init__ with the argument x. This means that int is a class and not a function. I'm sorry if you are more confused than before you asked, but I see everywhere that the *int* class is a function...