[Tutor] run with default value if input not given
Steven D'Aprano
steve at pearwood.info
Mon Oct 29 08:37:52 CET 2012
On Mon, Oct 29, 2012 at 11:28:05AM +0500, Saad Javed wrote:
> I've come up with this:
>
> try:
> sys.argv[1]
> x = sys.argv[1]
> main(x)
> except IndexError:
> main(x)
>
> It works but seems hackish.
There's no need to look up sys.argv[1] twice, nor any need to write
main(x) in both blocks. You can do each once only:
try:
# Always use the minimum code needed inside a try block.
x = sys.argv[1]
except IndexError:
x = "some default value"
main(x)
Here's yet another way:
args = sys.argv + ["some default value"]
main(args[1])
--
Steven
More information about the Tutor
mailing list