[Tutor] Taking user input from keyboard inside list comprehension

Alan Gauld alan.gauld at yahoo.co.uk
Sun Sep 6 04:13:15 EDT 2020


On 06/09/2020 07:30, Manprit Singh wrote:

> If i write a single line code like this in python shell :
>>>> ",".join([i for i in input("Enter the string").split(",") if int(i,
> base=2) % 5 ==0])

This is way too complicated for a single line of code.
It will be very difficult to maintain, almost impossible to debug.
This would be much clearer expanded into several lines.

fields = input("Enter the string").split(",")
validFields = [n for n in fields if int(n,2)%5 == 0]
result = "".join(validFields)

Also you should probably incorporate a try/except to catch bad
formatting in the input string.

However, to your actual question:

> it will first prompt you to input the binary string through keyboard and
> then it will immediately display the result, as given above
> My question is, as you can see in the example I have taken input from
> keyboard inside the list comprehension, is it valid to do so in python ?

input() is a function like any other so yes you can do it although it's
fairly uncommon. The simplest way to answer such questions is just to
try them at the >>> prompt - that's what it's there for!

>>> [n for n in input('Nums> ').split()]
Nums> 1 2 5 7 34
['1', '2', '5', '7', '34']
>>>


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list