0

I have written a code using while loop. However I have written the code successfully but it is not efficient. Please see the while loop: -

struct_type = { 1:'slab', 2:'beam', 3:'column', 4:'footing' }
z = int(input("Enter the structure type as 1-slab,2-beam,3-column,4-footing"))
while (z != 1 and z != 2 and z != 3 and z != 4):
    print("Invalid Structure type")
    z = int(input("Enter only: 1-slab,2-beam,3-column,4-footing"))
print(z)

How to write this while loop more efficiently? For example

while (z != [1, 2, 3, 4]):

or

while (z != range(1:5)):

But both these give errors. please help in writing this while loop more efficiently.

1
  • Did you mean: while z not in [1,2,3,4]:? Commented Nov 10, 2020 at 15:05

3 Answers 3

1

Just compare to limits:

while z < 1 or z > 4:
Sign up to request clarification or add additional context in comments.

Comments

1

You can use while z not in range(1, 5) which is pretty efficient (in checks in range objects is O(1)).

You can also do while z not in struct_type since 1..4 are keys of struct_type. This is also O(1).

Comments

0

I think you are looking for in clause.

while z not in [1,2,3,4]:

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.