Home > Software engineering >  while loop not closing
while loop not closing

Time:04-01

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

CodePudding user response:

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(',')

CodePudding user response:

.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

CodePudding user response:

Split returns a list, so it will never be equal to 'END' (a string).

print("END".split(",") == "END") # False
print("END".split(",") == ["END"]) # True

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

fixed code is

dict_coord = {} #empty dictionary for coordinates users input
coord_no = 0
coord_no  = 1
coord = input('enter coordinate ' str(coord_no) ':')
dict_coord[coord_no] = coord

while coord != 'end':
    coord_no  = 1
    coord = input('enter coordinate ' str(coord_no) ':')
    dict_coord[coord_no] = coord
    print(coord)
  • Related