[Tutor] Beginner's question: Looping through variable & list simultaneously

Mark Lawrence breamoreboy at yahoo.co.uk
Tue Dec 3 15:41:37 CET 2013


On 03/12/2013 14:11, Rafael Knuth wrote:
> Hej there,
>
>> Loop around your list using the enumerate builtin function and an
>> appropriate value for start, see
>> http://docs.python.org/3/library/functions.html#enumerate
>
> thanks! That hint was very helpful, and I rewrote the program as
> follows (I learned how to enumerate just yesterday and I figured out
> you can do the same with a range(len(list)) ... so here's how I solved
> my issue:

That's very poor coding, if you're given a function that does exactly 
what you want, why rewrite it and worse still, get it wrong?

>
> PopularCountries = ["Brazil", "China", "France", "India", "Vietnam"]
> Year = 2009
> Backpackers = 1000000
> for Country in range(len(PopularCountries)):
>      Year += 1
>      Backpackers = Backpackers*1.15
>      print("In %d there were %d backpackers worldwide and their most
> popular country was %s." % (Year, Backpackers,
> PopularCountries[Country]))
>
>>>>
> In 2010 there were 1150000 backpackers worldwide and their most
> popular country was Brazil.

Whoops, what happened to 2009?

> In 2011 there were 1322500 backpackers worldwide and their most
> popular country was China.
> In 2012 there were 1520874 backpackers worldwide and their most
> popular country was France.
> In 2013 there were 1749006 backpackers worldwide and their most
> popular country was India.
> In 2014 there were 2011357 backpackers worldwide and their most
> popular country was Vietnam.
>
> I will now try to further enhance my program by adding a second list
> to the loop.

What do you mean by "enhance", get the output correct or make it even 
worse? :)

> Again, thank you all!
>
> Raf

So here's the code with enumerate.

PopularCountries = ["Brazil", "China", "France", "India", "Vietnam"]
Backpackers = 1000000
for x, PopularCountry in enumerate(PopularCountries, start=2009):
     Backpackers = Backpackers*1.15
     print("In %d there were %d backpackers worldwide and their most 
popular country was %s." % (x, Backpackers, PopularCountry))

In 2009 there were 1150000 backpackers worldwide and their most popular 
country was Brazil.
In 2010 there were 1322500 backpackers worldwide and their most popular 
country was China.
In 2011 there were 1520874 backpackers worldwide and their most popular 
country was France.
In 2012 there were 1749006 backpackers worldwide and their most popular 
country was India.
In 2013 there were 2011357 backpackers worldwide and their most popular 
country was Vietnam.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list