0

so I just started Python today. Tried a basic program, but I'm getting an error "can't convert int object to str implicity"

userName = input('Please enter your name: ' )
age = input('Please enter your age: ')

factor = 2
finalAge = age + factor  **ERRORS OUT ON THIS LINE**
multAge = age * factor
divAge = age / factor


print('In', factor, 'years you will be', finalAge, 'years old', userName )
print('Your age multiplied by', factor, 'is', multAge )
print('Your age divided by', factor, 'is', divAge )

When I do enter int(age)+factor, instead of age, it works perfectly. But the author says that python auto detects the variable type when you key it in. So in this case when I enter age=20, then age should become integer automatically correct?

Looking forward to any help!!

  • 1
    The tutorial you are using is for Python 2.x, but you are using Python 3.x. There are several important differences between the two, and you should use a version of Python that matches the tutorial. That said, relying on `input()` to convert values for you is a bad idea, even in a Py2.x tutorial... – kindall Dec 11 '15 at 21:50

3 Answers3

1

From the doc

The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

As you can see, the input() function in python 3+ returns a string by converting whatever input you are given, much like raw_input() in python 2.x.

So, age is clearly a string.

You can't add a string with an integer, hence the error.

can't convert int object to str implicity

int(age) converts age to an integer, so it works in your case.

What you can do:

Use:

age = int(input('Please enter your age: '))

To cast your input to an integer explicitly.

Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
0

Your problem is that input returns a string (since in general, input from the command line is text). You can cast this to an int to remove the error, as you have done.

Python only automatically detects the type of your variables in your program if they don't already have a type - it does not automatically convert typed variables to different types.

Leon
  • 68
  • 5
0

Python does not know what operation you're trying to make, provided the '+' operator can be used both to concatenate strings and adding numbers.

So, it can't know if you're trying to do

finalAge = int(age) + factor   #finalAge is an integer

or

finalAge = age + str(factor)   #finalAge is a string

You need to explicitly convert your variables so it won't be ambiguous.

In your case, int(age) returns an integer, which is the proper way to get what you want.

Cyriaque C
  • 36
  • 4