What They Never Told You About Programming - Part 4

Graham has written a "dump" function to sell all the shares of his tech stocks in case of bad news in the market. However, he hasn't tested his code, and he's made an important mistake:

1
2
3
    tech_stocks=["AAPL","IBM","GOOG","ORCL","HPQ"]      
    for stock in 1,2,3,4,5:     
        sell_shares(tech_stocks[stock])     

Why will this code fail?

There is a problem but it's not listed in the other choices The brackets are incorrectly nested There is a syntax error in the for loop The index is out of range of the list

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

3 solutions

Eddie The Head
Apr 11, 2014

List index starts from 0 and for 5 elements it must go from 0 to 4 but in this case the value 5 has been used an hence the code will result in an index error .....

Ya! it's true Eddie Guerrero!

Mayank Holmes - 7 years, 1 month ago
Amit Patel
Apr 16, 2014

index for a list start from 0, so for 5 element index will be 0 - 4 , but the loop value is from 1 - 5 is used , hence code will result an error index out of range ...

true

Angga Pranata - 7 years, 1 month ago
Dhruv Patel
Apr 13, 2014

This is an index Issue as it starts with 0 and should end with 4. Its a syntax mistake and the code will not run. !

Not all programming languages are zero-indexed. Are we assuming a particular programming language here?

Pu li - 7 years, 1 month ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...