user3769115
user3769115

Reputation: 1

Python 3: How do I change user input into integers inside of a loop?

I want my program to ask the user to input a 3D point, and it is supposed to keep prompting the user until the user inputs the point (0,0,0). The problem I am having with this loop is being caused by the statement "point = [int(y) for y in input().split()]". Whenever the loop reaches this statement, it quits. I have tried placing this statement in different places, but it does the same thing no matter where I put it. If I take the statement out, the loop works. I need to change the coordinates inputted by the user to integers, so I cannot leave the statement out. Is there something else I can do to change the coordinates to integers that won't affect the loop?

point = ""
pointList = [[]] #pointList will be a list that contains lists

while True:        
    if point == "0,0,0":
        break
    else:
        point = input("Enter a point in 3D space:")
        point = [int(y) for y in input().split()]            
        pointList.append(point)
print(pointList)

Upvotes: 0

Views: 181

Answers (2)

pepr
pepr

Reputation: 20792

I suggest to make it more robust with respect to the user input. While regular expressions should not be overused, I believe it is a good fit for this situation -- you can define the regular expression for all possible allowed separators, and then you can use the split method of the regular expression. It is also more usual to represent the point as a tuple. The loop can directly contain the condition. Also, the condition can be a bit different than giving it a point with zeros. (Not shown in the example.) Try the following code:

#!python3
import re

# The separator.
rexsep = re.compile(r'\s*,?\s*') # can be extended if needed

points = []     # the list of points

point = None    # init
while point != (0, 0, 0):
    s = input('Enter a point in 3D space: ')
    try:
        # The regular expression is used for splitting thus allowing
        # more complex separators like spaces, commas, commas and spaces,
        # whatever - you never know your user ;)
        x, y, z, *rest = [int(e) for e in rexsep.split(s)]
        point = (x, y, z)
        points.append(point)
    except:
        print('Some error.')

print(points)

Upvotes: 1

whereswalden
whereswalden

Reputation: 4959

From the docs:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

In short, it splits on whitespace, which doesn't include commas. What you're looking for is str.split(',').

Upvotes: 1

Related Questions