Reputation: 1
I am a beginner at python. I am trying to create a program and a part of it requires users to input coordinates then store them in a dictionary. I want it to stop asking for input once the user writes 'END'. However, when I run this particular piece of code, it doesn't close when you enter END.
dict_coord = {} #empty dictionary for coordinates users input
coord_no = 0
coord_no += 1
coord = input('Enter coordinate {}: '.format(coord_no)).split(',')
dict_coord[coord_no] = coord
while coord != 'END':
coord_no += 1
coord = input('Enter coordinate {}: '.format(coord_no)).split(',')
dict_coord[coord_no] = coord
Upvotes: 0
Views: 94
Reputation: 11
you check for coord!=['end']. the part you forgot was that you have to check for parsed strings when using parsed strings for arguments. the fixed code is
dict_coord = {} #empty dictionary for coordinates users input
coord_no = 0
coord_no += 1
coord = input('Enter coordinate {}: '.format(coord_no)).split(',')
dict_coord[coord_no] = coord
while coord != ['end']:
coord_no += 1
coord = input('Enter coordinate {}: '.format(coord_no)).split(',')
dict_coord[coord_no] = coord
print(coord)
print(coord!=['end'])
Upvotes: -1
Reputation: 17
You need to using break
Like this;
dict_coord = {} #empty dictionary for coordinates users input
coord_no = 0
coord_no += 1
coord = input('Enter coordinate {}: '.format(coord_no)).split(',')
dict_coord[coord_no] = coord
while True:
coord_no += 1
coord = input('Enter coordinate {}: '.format(coord_no)).split(',')
print(coord)
dict_coord[coord_no] = coord
if "END" in coord or "end" in coord: #END and end is different for python '==' and 'in' syntax.
break #if end in coord, break.
Upvotes: 0
Reputation: 333
.split()
returns an array, so you need to refer to the first element in array in your condition as shown here:
dict_coord = {} #empty dictionary for coordinates users input
coord_no = 0
coord_no += 1
coord = input('Enter coordinate {}: '.format(coord_no)).split(',')
dict_coord[coord_no] = coord
while coord[0] != 'END':
coord_no += 1
coord = input('Enter coordinate {}: '.format(coord_no)).split(',')
dict_coord[coord_no] = coord
Upvotes: 3
Reputation: 304
You can just say break when the user enters end. So it could look something like this:
while True:
coord_no += 1
coord = input('Enter coordinate {}: '.format(coord_no)).split(',')
dict_coord[coord_no] = coord
if coord == "END":
break
Upvotes: 0
Reputation: 8277
What about:
dict_coord = {} #empty dictionary for coordinates users input
coord_no = 0
while True:
coord_no += 1
userInput = input('Enter coordinate {}: '.format(coord_no))
if userInput == "END":
break
dict_coord[coord_no] = userInput.split(',')
Upvotes: 4
Reputation: 8086
Split returns a list, so it will never be equal to 'END'
(a string).
print("END".split(",") == "END") # False
print("END".split(",") == ["END"]) # True
Upvotes: 0