-2

What does %d do in this line of my code?

puppy+="and Puppy %d (User %d) "%((j+1),(i+1))

Here's my code.

u=int(input("Number of users:"))
puppy=""

for i in range (0,u):
  upos=input("Position of User "+str(i+1)+":")
  upos_list=upos.split()
  upos_x=int(upos_list[0])
  upos_y=int(upos_list[1])
  p=input("Number of puppies for User "+str(i+1)+":")

  for j in range (0,int(p)):
    ppos=input("Position of Puppy "+str(j+1)+":")
    ppos_list=ppos.split()
    ppos_x=int(ppos_list[0])
    ppos_y=int(ppos_list[1])     

    d=abs((ppos_x)-(upos_x))+abs((ppos_y)-(upos_y))
    if d>10:
      puppy+="and Puppy %d (User %d) "%((j+1),(i+1))

if puppy=="":
  print("No puppies too far away")
else:
  print(puppy[4:]+"too far away")

Here's the input and output for your reference.

Here's the input and output for reference

Yolanda Hui
  • 97
  • 1
  • 1
  • 8

1 Answers1

2

It takes the value that is after your string and places it into the string at the %d. The first %d gets the first value, and the second gets the second and so on...

So it prints like this. "and Puppy (whatever j+1 is) (User (whatever I +1 is) ) "

chillinOutMaxin
  • 182
  • 1
  • 13
  • Do you know how "and Puppy 2 (User 1) and Puppy 1 (User 2) and Puppy 2 (User 2)" becomes "Puppy 2 (User 1) and Puppy 1 (User 2) and Puppy 2 (User 2) too far away" after the code print(puppy[4:]+"too far away")? What does [4:] do and why the "and" before Puppy 2 disappear? – Yolanda Hui Oct 16 '18 at 18:17
  • I would need more information to fully answer your question but the [4:] refers to an index. That would return all objects in the array from the 4th index to the end of the array. Keep in mind that index 0 is the first item and 1 second and so on. – chillinOutMaxin Oct 16 '18 at 18:24
  • If your getting an error, please post it – chillinOutMaxin Oct 16 '18 at 18:27
  • index 0 is the first item which is "and Puppy 2 (User 1)"? – Yolanda Hui Oct 16 '18 at 18:27
  • You are looping through 2 arrays. If you want to see what is at each index in your array try printing your array. – chillinOutMaxin Oct 16 '18 at 18:39