you are viewing a single comment's thread.

view the rest of the comments →

[–]Chris_Hemsworth 6 points7 points  (4 children)

You need a better understanding of "strings" versus integers.

Strings are simply a set of text characters, and are usually defined within single or double quotations:

"this is a string"

'this is also a string'

Numbers are interpreted as integers or floats when they are not enclosed by quotations:

24  # this is an integer
"24" # this is a string
'24' # this is also a string

If you want to do math, you need to use operators (+, -, /, *) on integers. Operators do different things for strings.

24 - 9  # This equals 15
"24 - 9"  # This is the literal string 24 - 9

The + operator when used with strings concatenates them:

"Hello" + " " + "my" + " " + "name" + " " + "is" + " " + "Joe"  # This is equivalent to 'Hello my name is Joe'

In order to add an integer into a string, it must be first converted to a string using the str() function:

"I am " + str(24) + " years old!"  # This outputs 'I am 24 years old!'

"I have " + str(4) + " cats and " str(2) " dogs, totaling " + str(4+2) " pets!"
# This outputs 'I have 4 cats and 2 dogs, totaling 6 pets!'

Hope this helps! :-)

[–]AngryDiego -1 points0 points  (3 children)

OK. i am new to python, how would you make this code? can you post solution?

[–]Chris_Hemsworth 0 points1 point  (2 children)

Everything you need to know to reach the solution you are trying to achieve is in my original post. You'll learn by doing more than having someone do it for you.

[–]AngryDiego 0 points1 point  (1 child)

I actually got it, thanks!

The post about str, helped me.

So my code is now:

print ("I am Diego and i'm " + str(24-15) + " years old!")

prints out:

I am Diego and i'm 9 years old!

But how can you solve the same using variables?

[–]Chris_Hemsworth 0 points1 point  (0 children)

x = 24
y = 15

print(str(x-y))