0

newbie for python here.

i'm trying to validate if user input is empty for a nested list to store (x y coordinate). If user did not input anything, codes should be displaying a message e.g. "No input" and will loop back prompting the user to input.

Had been searching everywhere on validate empty nested list, or validate empty input but i just can't put the knowledge together. An example of the code is display below:

add = "y"
xy = []

#-------------------------------------
def count_list(l):
    count = 0
    for e in l:
        if isinstance(e, list):
            count = count + 1 + count_list(e)
    return count
#--------------------------------------

while (add == "y"):

    xy.append([(input("Input x value: ")), (input("Input y value: "))])

    add = input("Additional (x, y)? [y/n] ")

qty = (count_list(xy))

print ("(x, y) coordinate(s) inserted:- " + str(xy))

print ("No. of coordinate(s) inserted:- " + str(qty))

Output

enter image description here


Had been cracking my brain for this. Notice 2nd nested list is empty. Am trying to find out how stop the code to proceed but instead prompting the user with a msg "no input". The position of the empty nested list should not be added into the list.

Also have no idea why my count_list function also include counting in an empty nested list. T_T

1 Answer 1

1

What you can do to avoid counting an empty input is continue when you see that the input is empty.

while (add == "y"):
    x_val = input("Input x value: ")
    y_val = input("Input y value: ")
    # not x_val checks if the string is an empty string
    if not x_val or not y_val:
        print("Error: No input. Try again.")
        continue

    xy.append([(x_val), (y_val)])

    add = input("Additional (x, y)? [y/n] ")

Output:

Input x value: 1
Input y value: 2
Additional (x, y)? [y/n] y
Input x value:
Input y value:
Error: No input. Try again.
Input x value: 5
Input y value: 6
Additional (x, y)? [y/n] n
(x, y) coordinate(s) inserted:- [['1', '2'], ['5', '6']]
No. of coordinate(s) inserted:- 2
Sign up to request clarification or add additional context in comments.

1 Comment

What the... was spending half a day on this and you nailed it ! Thanks a lot.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.