1

How can i set default values on the w, d & h?

w, d, h = input("Specify width, depth & height: ").split()
print (w)
print (d)
print (h)
0

2 Answers 2

1

Explicit is better than implicit:

values = input("Specify width, depth & height: ").split()

w = values[0] if len(values) > 0 else DEFAULT_W
d = values[1] if len(values) > 1 else DEFAULT_D
h = values[2] if len(values) > 2 else DEFAULT_H

But a more extravagant way could be:

values = iter(input("Specify width, depth & height: ").split())

w = next(values, DEFAULT_W)
d = next(values, DEFAULT_D)
h = next(values, DEFAULT_H)
Sign up to request clarification or add additional context in comments.

Comments

0
w, d, h = input("Specify width, depth & height: ").split() or (10, 11, 12)
print (w)
print (d)
print (h)

This sets the values to a default if the user entered nothing, since an empty string will be split to an empty list, which will be evaluated to False.

5 Comments

Simple and sweet. +1
But will fail if the user enters one or two. But I guess it might be the OP's intention. It's not very clear from the question.
Also, using or (...) with a tuple of default values would be more logical, to avoid an unnecessary split of your default values. (and empty list after split would also evaluate to False
Yes, it is worth noting that it will also fail if the user enters something nonsensical, like letters. Validation is a whole different task
@YevhenKuzmovych +1 You're right, that's better! Didn't think about an empty list also evaluating to false.

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.