Python Forum

Full Version: Converting String to Integer Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
NOTE: I am executing the Python langauge in Atom, a Text Editor for Coding.

I have a Homework assignment in which I'm supposed to get the following code to print out the expected output; 3.
a = "1"
b = 2
print(a + b)
I presume you have to convert the string; a, or "1" to a integer. Yet, when I change the above code to:
a = "1"
b = 2
int("1")
print(a + b)
(Which I assume is the correct way to do things?)

I get the following error:
Output:
Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str
Any help would be greatly appreciated!

Thanks,
Johnny

@Yoriz
@ichabod801

Thanks! I will endeavor to not make this mistake again, Sorry!
int('1') does not change the value a is assigned to. It creates a new value and converts that. You need to reassign the new value to a. And you should convert a, not a new value, to make sure it works if the value of a is changed.
using int is correct but you need to store the result from int to a variable.
you can use int on the variable a and store the result on a if you want to permanently change it.
(Aug-02-2019, 07:31 PM)ichabod801 Wrote: [ -> ]int('1') does not change the value a is assigned to. It creates a new value and converts that. You need to reassign the new value to a. And you should convert a, not a new value, to make sure it works if the value of a is changed.

Thanks! This helped.

To solve the problem, I simply did as ichabod801 instructed. I changed the code
a = "1"
b = 2
int("1") 
print(a + b)
to this code:

a = "1"
b = 2
a = int("1") 
print(a + b)
Thanks Again!
I would suggest using a = int(a) instead. That way it will still work if a is not '1'.
(Aug-02-2019, 08:04 PM)ichabod801 Wrote: [ -> ]I would suggest using a = int(a) instead. That way it will still work if a is not '1'.

Seems reasonable. I have added that to my code.

Thanks.