Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Top Posters

Who's Online (0)

Powered by Vanilla. Made with Bootstrap.
Python Variable in Output Question
  • Xin
    Posts: 3,251
    Im trying to output a line of text for example

    print 'you have' + number + 'berries'

    How do i make this work as its just erroring atm. The number is an int i believe will this make a difference?
    Xin

  • print(\"You have %d berries\" % number)
  • Xin
    Posts: 3,251
    Cheers bro :), still learning python you see
    Xin
  • said:


    Cheers bro :), still learning python you see



    Welcome. Yea just remember format strings can be a big help.
  • sangf
    Posts: 203
    also note if you have more than 1 format parameter you need to use a tuple for the values:
    print(\"You have %d berries, %s\" % (number, 'derp'))

    the original code didn't work because you're using the + operator on different types of data. when used with int, it's mathematic, and with string it just concatenates. both is bad, you could however cast the int to a string:
    print 'you have ' + str(number) + ' berries'

    string formatting is the way to go though.