Jump to content


Photo

Why Doens't This(Code) Work?


  • Please log in to reply
2 replies to this topic

#1 DragonDon

DragonDon

    New Member

  • Members
  • Pip
  • 4 posts

Posted 04 April 2013 - 08:21 PM

I just did the if/else exercise and got it wrong, but was curious why this is wrong?

for each_item in movies:
if isinstance(each_item,list):
print(each_item)
else:
print(each_item)

Why does there need to be a 'target' for the 'isinstance' finding of a nested list?

#2 Jon_Bryce

Jon_Bryce

    New Member

  • Members
  • Pip
  • 5 posts

Posted 25 September 2013 - 09:03 PM

I just did the if/else exercise and got it wrong, but was curious why this is wrong?

for each_item in movies:
if isinstance(each_item,list):
print(each_item)
else:
print(each_item)

Why does there need to be a 'target' for the 'isinstance' finding of a nested list?


Hi - I know this one... a rare thing.

Why is this wrong? - I'm guessing it's either the data you're feeding it, or the indentation. I entered this into IDLE...
<snip>
movies = ["Holy Grail", 1975,["Palin","Chapman"]]

for each_item in movies:
if isinstance(each_item, list):
print ("It's a list")
print(each_item)
else:
print ("Not a list")
print(each_item)
<snip>
and it worked. I added the 'prints' so I can see what branch is being taken. What's the error you're getting?

#2 - why does 'isinstance' need the target? "Cause it's a separate python construct. What you're asking is 'Is <this> a list'. You have to say what <this> is. You could use this outside the 'for' loop - for example, 'is <movies> a list' by saying ..
if isinstance(movies,list):
print "Hey, movies is a list"
else:
print "not a list"

I'm resisting the compulsion to mention spam, as I'm not a good python programmer. Damn, I just mentioned it...

#3 paulbarry

paulbarry

    Advanced Member

  • O'Reilly Author
  • PipPipPipPipPipPipPipPip
  • 307 posts

Posted 27 September 2013 - 11:01 AM

The code in the "if" part of your code and the code in the "else" part are the same: print(each_item). If you look at the code in the book from page 22 onwards, I don't ever do this.

--Paul.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users