-1

Can someone tell me what's wrong with this bit of code and what to change?

number = 1
text = "hello"

while number <= 10:
    print("%d, %s" % number, text)
    number = number + 1

Error:

Traceback (most recent call last): File "program.py", line 5, in print("%d, %s" % number + text) TypeError: not enough arguments for format string

It works when I do it this way:

number = 1
text = "hello"

while number <= 10:
    print("%d" % number)
    number = number + 1

I think i read somewhere that using the "%" sign to merge strings is the old way to do it, I'd like the code to still use it if it's possible.

4 Answers4

2

Doing it this way requires parentheses around number, text, as it requires a tuple. So just replace the line print("%d, %s" % number, text) with print("%d, %s" % (number, text)) and you should be good.

Nobozarb
  • 334
  • 1
  • 12
1

use this code

number = 1
text = "hello"

while number <= 10:
    print("%d, %s" % (number, text))
    number = number + 1
ali sarkhosh
  • 143
  • 1
  • 10
1

In print("%d, %s" % number, text) statement, you need to provide a tuple of parameters to the string formatting (in your case "%d, %s"). So, the correct way to do this is -

print("%d, %s" % (number, text))

or

print number, text  # applicable for python 2.7
# print (number, text) # Python 3. Python 2.7 prints a tuple

The second one is applicable as you are not printing anything other that the variables. For the first one you need a tuple for where you are providing more than one arguments during string formatting. So, if want to print say only number, you can do just print ("%d" %number) or print "%d" %number. The tuple in this case is not mandatory, but you can always do print ("%d" %(number,)) if you really want to type some more characters.

But the first one is old way of doing things. For newer and more cooler version, use format() like below -

print("{}, {} blah blah blah".format(number, text))

or,

print "{}, {} blah blah blah".format(number, text)

For more info, check out - https://docs.python.org/2/library/string.html#format-string-syntax

Also follow the answer given by @lenik for other problems in your code.

kuro
  • 2,585
  • 1
  • 12
  • 23
0

Your code is absolutely against all the rules of the python code. Should have been written like this:

text = 'hello'
for number in range(10) :
    print( number, text )
  1. No unneeded initializations for number
  2. No while loop, which often leads to errors
  3. No formatting where not necessary
lenik
  • 21,662
  • 4
  • 29
  • 38