Add some more about ranges
This commit is contained in:
parent
4b6b8f6069
commit
6b75246207
|
@ -133,7 +133,33 @@ So, when using inheritance, be sure to inherit using refs, unless you know what
|
||||||
|
|
||||||
### Ranges
|
### Ranges
|
||||||
|
|
||||||
The syntax for ranges is different. a[x:y] becomes a[x..<y]
|
In Python, simple integer for loops use the `range` generator function. For the 1- and 2- argument forms of this function, nim's [`..` iterator](https://nim-lang.org/docs/system.html#...i%2CT%2CT) works almost the same way:
|
||||||
|
|
||||||
|
``` Nim
|
||||||
|
for i in ..10:
|
||||||
|
echo i # Prints 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
|
||||||
|
|
||||||
|
for i in 5..10:
|
||||||
|
echo i # Prints 5, 6, 7, 8, 9, 10
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that the `..` operator includes the end of the range, whereas Python's `range(a, b)` does not include `b`. If you prefer this behavior, use the [`..<` iterator](https://nim-lang.org/docs/system.html#..%3C.i%2CT%2CT) instead:
|
||||||
|
|
||||||
|
``` Nim
|
||||||
|
for i in ..<10:
|
||||||
|
echo i # Prints 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
|
||||||
|
```
|
||||||
|
|
||||||
|
Python's `range()` also has an optional third parameter, which is the value to increment by each step, which can be positive or negative. If you need this behavior, use the [`countup`](https://nim-lang.org/docs/system.html#countup.i%2CT%2CT%2CPositive) or [`countdown`](https://nim-lang.org/docs/system.html#countdown.i%2CT%2CT%2CPositive) iterators:
|
||||||
|
|
||||||
|
``` Nim
|
||||||
|
for i in countup(1, 10, 2):
|
||||||
|
echo i # Prints 1, 3, 5, 7, 9
|
||||||
|
```
|
||||||
|
|
||||||
|
### Python slices
|
||||||
|
|
||||||
|
The syntax for slice ranges is different. a[x:y] becomes a[x..<y].
|
||||||
Also, a[x..y] is inclusive.
|
Also, a[x..y] is inclusive.
|
||||||
``` Nim
|
``` Nim
|
||||||
let a = @[1,2,3,4]
|
let a = @[1,2,3,4]
|
||||||
|
@ -143,6 +169,7 @@ a[0..<2] # returns @[1, 2]
|
||||||
a[0..3] # returns @[1, 2, 3, 4]
|
a[0..3] # returns @[1, 2, 3, 4]
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
### Python strings
|
### Python strings
|
||||||
|
|
||||||
Use double quotes: "foo" or """foo""", not 'foo'
|
Use double quotes: "foo" or """foo""", not 'foo'
|
||||||
|
|
Loading…
Reference in New Issue