DEV Community

Discussion on: Solving the Problem Sets of CS50's Introduction to Programming with Python — One at a Time: Problem Set 3

 
rivea0 profile image
Eda • Edited

int(a) converts the input to a number ... but how about b?

This piece of code (a, b = [int(a) for a in input("Fraction: ").split('/')]) is actually a list comprehension — one of my favorites of Python. It is just a more elegant, and "pythonic" way to write for loops. Here, it asks for an input, and splits it with /, then it puts the values (converted to integers) inside a list. Then it unpacks the list with assigning the two values into variables a and b. Literally the same as this:

values = []
for a in input('Fraction: ').split('/'):
    values.append(int(a))
a = values[0]
b = values[1]
Enter fullscreen mode Exit fullscreen mode

So, the a inside the list is different from a the variable that the first value is assigned to. Giving them the same name is not a good practice in my opinion. You can change that name and it does not matter, for example, a, b = [int(x) for x in input("Fraction: ").split('/')] gives the same output.

W3Schools has a basic explanation on how list comprehensions work. You can also read about them from the official docs.

Glad you passed the tests. The whole aim of the infinite loop is just to keep getting input, but using that list comprehension example inside an infinite loop would continue asking for an input forever and keep adding the results into a list, so it wouldn't work. I think it's better to convert the values after you got the input, but it really depends on how you would like to implement it.

Thread Thread
 
heyandre profile image
Andre Castro

Thanks a lot for the clear explanation...