Python Forum
Converting String to Integer Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting String to Integer Python
#1
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!
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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.
Reply
#4
(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!
Reply
#5
I would suggest using a = int(a) instead. That way it will still work if a is not '1'.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#6
(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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Using an integer to manipulate a string/text variable rexyboy2121 1 1,703 Apr-22-2020, 01:37 AM
Last Post: michael1789
  Trouble converting a string into an int DreDigital 2 1,614 Jan-29-2020, 09:41 PM
Last Post: DreDigital
  Determine if string is integer jrodencal 12 4,045 Oct-15-2019, 01:39 PM
Last Post: jefsummers
  Converting pseudocode to Python qwertyK 3 23,560 Oct-24-2017, 01:41 PM
Last Post: qwertyK

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020