[Tutor] input problem

Alan Gauld alan.gauld at btinternet.com
Wed Sep 15 01:57:35 CEST 2010

"ANKUR AGGARWAL" <coolankur2006 at gmail.com> wrote

> Suppose i am taking input or various variables like
> a=raw_input("...............") //hello
> b=raw_input("................")//hi
> but i want to run a common function when input is hello
> so instead of
> if a=="hello":
> fun()
> then again for b and then again for c then d and so on i have to 
> apply the
> code for the specific variable ,
> i want to run the function whenever in the code input is "hello"
> i am wondering is there is any way like
> if input=="hello":
> fun()

I don;t see how that changes from the previous example except
you changed a to input?

However I think you are asking about processing a collection
of data values (which happen to have been produced by raw_input()
but could equally have been read from a file).

The pattern for that case is the for loop:

for data in data_collection:
     if data == "hello":

Or if you want to collect the results:

results = [fun() for data in data_collection if data == "hello"]

How you get the data into data_collecton I leave as an excercise! :-)

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list