Reputation: 1
I am currently learning python and i want to show what position the new added object is in, but for some reason the string formatting isn't working and it just outputs 0 when i write print.
Can someone help?
listgen = []
while True:
print("Enter any names u want")
print("hit enter if u wanna leave")
print("if u want to see the list type print")
inp0 = input("> ")
number = 0
if inp0 == "":
break
elif inp0.lower() == "print":
for name in listgen:
print(name + " is in spot number %s" % number)
else:
listgen.append(inp0)
number = number + 1
Upvotes: 0
Views: 44
Reputation: 42227
Removing the "irrelevant" bits,
while True:
number = 0
number = number + 1
You're re-setting number
to 0 every time you loop around, so it's only 1
between the else
and the end of the loop, then it's back to 0, and therefore will always be printed as 0.
Furthermore it's a constant for all item, so even if you fix this reinitialisation issue (initialise to 0 outside the loop) that's not going to be very informative as basically all it tells you is the number of names in your listgen
, e.g. if you input 3 names it's going to print "a is in spot number 2", "b is in spot number 2", "c is in spot number 2" which is unlikely to be what you want. Depending on your specific needs there are two ways to fix this:
Upvotes: 3
Reputation: 13
If you want to know what position has the new append, it should be the last one, so, get your list size with len(listgen)
.
If you have problem with string formatting and got >python3.6 version, try the new f-strings f-string python docs
>>> name = "Fred"
>>> f"He said his name is {name}."
"He said his name is Fred."
Upvotes: 0