What is wrong with my Python...

Started by
2 comments, last by Calcious 8 years ago

magicians = ["Alice", "David", "Carolina"]

for magicians in magicians:
		print(magicians)
		
for magicians in magicians:
		print(magicians.title() + ", that was a great trick!")

I do this ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

I get this as my output...

Alice

David
Carolina
C, that was a great trick!
A, that was a great trick!
R, that was a great trick!
O, that was a great trick!
L, that was a great trick!
I, that was a great trick!
N, that was a great trick!
A, that was a great trick!
Advertisement

Here's a different version of the program that does the same thing, plus comments:


magicians = ["Alice", "David", "Carolina"]

for person in magicians:
    print(person)
#person is now magicians[3], aka "Carolina"

magicians = person #magicians is now "Carolina".  Whoops!

for letter in magicians:
    print(letter.title() + ", that was a great trick!")

Basically, you're overwriting "magicians" by using the same variable as your loop iterator.

I don't really know Python, but I would guess that it's a variable scope issue.

My guess as to how you can fix it -- rename the variable names in the for loops.

Even if that isn't the issue, I would personally refrain from having identical names for the variable describing each separate magician and the collection of magicians.

E.g. try

for magician1 in magicians

print(magician1)

for magician2 in magicians

print (magician2.title() + ", that was a great trick!")

---

EDIT: Seraph ninja.

Hello to all my stalkers.

Thank you guys

This topic is closed to new replies.

Advertisement