简体   繁体   中英

Need clarification on optional parameters

range(start, stop[, step])

what does these square brackets and comma means exactly? I know that step is optional parameter, but the concept is still not clear to me It would be great if you can provide some good examples so that next time these brackets in python doc doen't horrify me

Thanks!

The square brackets are an old syntax-documentation shorthand for "part in brackets can be omitted." So by putting both the second , and step in brackets, it's saying you can keep both or omit both, but keeping the , and omitting step (or vice versa) is a syntax error.

Another syntax-documentation shorthand you sometimes see is <parameter> , which means to put the parameter's value (or a variable or expression; whatever works) where the text is. The <> are not kept. These brackets are used to disambiguate parameters from keywords and function names.

And another shorthand is ... , which means "the part before this can be repeated as needed."

Putting it all together, you could document the max function as:

max(<value> [, <value> ...])

which means the literal function name max followed by a literal ( then a value; then optionally a , and another value, repeated as needed, and ending with a literal ) .

It's easier to read than BNF-type syntaxes, though less precise, and it works even if you only have a plain text format and thus can't set keywords and literals in a different typeface.

It means that even if you don't specify the step argument, a default value will be used. In this case the default value is 1 . The square brackets are just a python convention to indicate optional arguments.

You can override the default value by explicitly specifying the step.

>>> range(0, 10, 2)
[0, 2, 4, 6, 8]

It means you can call the range function with/without step argument.

>>> range(1, 5, 1) # with `step` argument
[1, 2, 3, 4]
>>> range(1, 5)    # without `step` argument
[1, 2, 3, 4]

So, above two example both works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM