简体   繁体   中英

How do I separate a normal “print” from a “for print”?

Just going to get straight to the point, but when I write a normal "print" after writing a "for print" I only get the letter of the last word. Here is what I wrote

print("Animal list:")
animallist = ["cows", "sheep", "pigs", "horses", "chickens", "goats", "ducks"]
for animallist in animallist:
  print (animallist)

and when I write this

print("Animal list:")
animallist = ["cows", "sheep", "pigs", "horses", "chickens", "goats", "ducks"]
for animallist in animallist:
  print (animallist)
print(animallist[4])

It just goes and shows the list and the last letter of the last word.

So what im trying to make is a normal list with "chicken" at the bottom aswell. Im not good with this so Im kinda clueless, would love some help, what im looking for is something that looks like

Animal list:
cows
sheep
pigs
horses
chickens
goats
ducks

chickens

Understand the list and the item in the list:

print("Animal list:")
animallist = ["cows", "sheep", "pigs", "horses", "chickens", "goats", "ducks"]
for animal in animallist:
  print (animal)
print(animallist[4])

When python run the for loop, it re-assigns the variable animallist to each item of the animallist (class 'list') ("cows", "sheep", "pigs", etc. which are class 'str' ), so the variable animallist has become class 'str' . When the for loop iterates to the last item of the list, which is "ducks" , it assigns animallist to the value "ducks" , so when it runs the print(animallist[4]) , it will print the 4th index of the string "ducks" , which is s .

You can see the type of your animallist variable has changed here:

animallist = ["cows", "sheep", "pigs", "horses", "chickens", "goats", "ducks"]
print(type(animallist))

for animallist in animallist:
    pass

print(type(animallist))

Output:

<class 'list'>
<class 'str'>

So you shouldn't use the same name for the variable in the loop functions and the iterable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM