2

I'm having a problem with the int() function. I tried to use it in a simple program, but remains not working. This is my short program. I use int() to turn the a variable from a str into a int. And use it to compeare with 2. But it returns an error, because it's still seen a as a str. What's happening??

a = '4'
int (a)
if a > 2:
    print( "It's working" )

3 Answers3

3

int(a) doesn't mutate a, it creates a new object and returns it. Try this:

a = '4'
i = int(a)
if i > 2:
    print("It's working")

Notice that the new variable I created on line 2 has a different name from the one I created on line 1. It doesn't have to. In fact, sometimes it can be more readable to re-use the name:

a = '4'     # Now `a` is a `str`
a = int(a)  # Now `a` is an `int`
if a > 2:
    print("It's working")
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
0
# or mutate the a by redefining a:
a = '4'
a = int(a)
if a > 2:
    print("It's working")
Gwang-Jin Kim
  • 9,303
  • 17
  • 30
0

Instead of type casting it before the for loop, you can keep "a" as a str and just type cast it to int in the for loop. This will preserve your str dataype while you will get your desired output.

a = '4'

if int(a) > 2:
    print( "It's working" )

In your program. you are converting str to int only for that instance. You're not storing it anywhere. So your variable a points to the str which is stored before type casting it.

Yash Ghorpade
  • 607
  • 1
  • 7
  • 16