Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

Python int() and str()


ghost's Avatar
0 0

Hey, out of the tutorials I have been reading I have not yet come across anything too in depth about using the statements int() and str(). I am wondering when or why exactly I would have to declare objects stating these tags.


ghost's Avatar
0 0

You need the different data types for different reasons.

for example: Find the sum of the numbers in this string, '1234567890'.

>>> a = '123456789'
>>> b = 0
>>> for n in a:
...     [tab]b += int(n)
... 
>>> b
45
>>> 

Understand?


ynori7's Avatar
Future Emperor of Earth
0 0

Basically, you'd use the int() method if you have some datatype (such as a string) that you need to perform integer operation on and you use the str() method if you have some datatype (such as an integer) that you want to perform string operations (such as concatenating) on.


ghost's Avatar
0 0

Im not understanding the: for n in a:

I don't understand what n is representing. So I am kinda stuck on the whole thing still. I only am grasping that I would use the statements to differ strings and and integers within the same section of code.


ghost's Avatar
0 0

Yeah I understand what ynori7 is saying. However the Python guru up top got me lost in transaction. K, well I'm out for the night, maybe I will get more into discussing python tomorrow, well, later. Later.


ghost's Avatar
0 0

chronicburst wrote: Im not understanding the: for n in a:

I don't understand what n is representing. So I am kinda stuck on the whole thing still.

The for loop is iterating through the characters, which are stored in the variable a. With each iteration, the succeeding character is stored in variable n.

i.e. first loop: n = a[0] which is equal to '1' second loop: n = a[1] == '2' third loop: n = a[2] == '3' etc.


ghost's Avatar
0 0

Okay, so the loop is being classified as n. I have to admit I am finding Python much, much easier to catch onto that C++, which I gave up on.


ynori7's Avatar
Future Emperor of Earth
0 0

chronicburst wrote: Okay, so the loop is being classified as n.

I dont know what you mean by classified, but n is the iterator. Python uses lists with its for loops. You'll probably see loops that look like this:

sum+=n```
The range function creates a list comprised of the numbers (in this case) from 0 up to (but not including) 10.
As you go through the loop, the variable n points to the current spot in the list so that you can perform operations with that element.

ghost's Avatar
0 0

Ok, understood. By classified, I just meant variable.