I've wrote a little Python script that prompts the user to enter plot coordinates to then make a graph with it. Here's the part I have some trouble with:
x = []
while True:
try:
x.append(float(input()))
except ValueError:
break
y = [float(input()) for _ in range(len(x))]
Here's a little description of what happens: the user enters whatever numerical values he wants provided they are in float
or int
format, then enters a forbidden character, like a letter, to go on to the next step and enter another set of values, but this time the same quantity as the first set.
Now this code works perfectly fine, but notice how the y
list is elegantly filled in a single line of code by a list comprehension, thanks to the fact that the iterator's length is already known due to the presence of the x
list. But my problem is that I can't figure out how to beautifully fill x
, not only to make my code shorter and probably more optimized, but also not to have to define the list beforehand at the beginning of my script.
I have tried ways to go around ths problem, but they did not seem to work, so I'm gonna show that to you with the hopes that you can help my poor soul.
x = [float(tempvalue) for _ in iter((lambda tempvalue=input(): tempvalue),"end")]
x = [float(tempvalue) for _ in iter(int,1) if (tempvalue := input()) != "end"]
In these attempts, I tried to exit the loop with the specific keyword 'end' instead of any random character that is not a number, but it doesn't really matter since it doesn't work.