+ 2

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?

3rd Mar 2018, 5:38 PM
arbaaz
5 Answers
+ 6
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? ;)
3rd Mar 2018, 5:46 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 3
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.
3rd Mar 2018, 6:01 PM
abhijeet
abhijeet - avatar
+ 3
Thank you all for your answers.
4th Mar 2018, 1:06 PM
arbaaz
+ 2
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!
3rd Mar 2018, 5:48 PM
Faisal
Faisal - avatar
+ 1
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...
4th Mar 2018, 4:36 PM
Amaras A
Amaras A - avatar