Question on variables


#1

The interpreter interprets a text when a variable equals to a string and after the string is printed out. May i know why is it that when a variable equals to a number, say now = 3, when now is printed, 3 appears. But when a variable equals to a word, say now = candy, there is an error when i submit the code.

Other than the question above, i have another burning question on my mind. Given that when now=3 and 3 appears when now is printed, why is there a need for str() function to change, say str(3) to get "3" when it already can appear in the interpreter even without being stringed?


#2

seems your question is more about data type then variables, the data types covered so far:

3 # integer
5.4 # float
"hello world" # string
True # boolean

this are the data types covered so far, in this case:

now = candy

now and candy are both variables, given you haven't defined candy yet, you will get an error

3 is integer, "3" is a string. You can represent integers as string


#3

Given that integers can be represented as strings, why is there a need for the function str() to be applied to integers?


#4

well, if you want to concat string and integer you will need it:

print "the value of pi is: " + str(3.14)

without str(), you will get an error.

always representing integers as strings sucks for math:

print "2" + "2"  # 22
print 2 + 2 # 4

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.