0

Never mind the placeholder variable names; how do I assign to D, E, and F in the way that I'm trying to do here?

print("Input 3 search coordinates")
D, E, F, = 0, 0, 0
    for axes in [[D, "Y"], [E, "X"], [F, "Z"]]:
        while True:
            try: 
                axes[0] = int(input("{}-Axis: ".format(axes[1])))
                break
            except:
                print("No, a natural number!")
        print(axes)
print(str(D) + str(E) + str(F))

This little bit of print debugging at the end outputs "000," rather than the inputs, like "444." What do I need in order to assign the inputs to the variables in the list being looped through (while also not repeating myself)?

4
  • Don't use dynamic variables, just use a container like a list or a dict Commented Sep 5, 2019 at 23:01
  • 1
    The list element does not remember that its initial value came from the variable D; assigning a new value to the list element leaves D undisturbed. Commented Sep 5, 2019 at 23:05
  • @JohnGordon As a question of academic interest, what is the compiler doing with the first and second D? (Is there a way to turn a Python into the assembly of the C from the compilation, or would that be wildly unreadable?) Commented Sep 5, 2019 at 23:13
  • The way this code is organized, I don't think you can retrieve the input values, because you didn't assign a name to the outer list. The only name you have access to is axes, which will contain only the last sub-list when the for loop is finished. Commented Sep 5, 2019 at 23:14

2 Answers 2

1
def get_input(axis):
    while True:
        user_input = input(f"{axis}-Axis: ")
        try:
            axis_int = int(user_input)
        except ValueError:
            continue
        else:
            break
    return axis_int

print("Input 3 search coordinates")
x, y, z = [get_input(axis) for axis in "XYZ"]
Sign up to request clarification or add additional context in comments.

Comments

1

Use a dictionary instead:

  • Replace the list with a dict, then call the key to update the value
  • Dictionaries are a better data type for situations where named variables (e.g. x, y, z) are being updated.
coor_dict = {'x': 0, 'y': 0, 'z': 0}

for k in coor_dict.keys():
    while True:
        try:
            coor_dict[k] = int(input(f'{k}-Axis: '))
            break
        except ValueError:
            print('No, a natural number!')

print(coor_dict)

Output of execution:

x-Axis:  4
y-Axis:  5
z-Axis:  6
{'x': 4, 'y': 5, 'z': 6}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.