5: Ranges and for-loops 范围和遍历
There’s yet another data type to introduce now, and that’s Range. A Range is, as the name suggests, a range of numbers with a start and an end. If you want to make a range with the number 1, 2, 3 and 4, you have two options:
有一种数据类型叫做范围,我们来看下面的这个例子:
You first type a number, 1 in this case (can also be negative). If you then write down two dots, you’re including the number written down after the dots. If you write down three dots, you’re excluding the number written down after the dots. So 1..4 starts at 1 and includes up to 4. 1...5 starts at 1 and goes up to 5, but doesn’t include it.
You can also have negative ranges.
-7..-3 (-7, -6, -5, -4, and -3)
-2..2 (-2, -1, 0, 1, and 2)
You can’t have ranges go from big to small, though. You can’t use Floats either.
2..-2 is empty. Just like an empty array, [], this is empty. Nothing.
1.1..1.3 is also empty. It won’t work when you try to do anything with it (regardless of using parentheses)
同样的,也支持负数的范围,比如说-2..2,就是指从-2到2,并且包括2。
Naturally, ranges also work with variables.
我们来看下面这个使用变量来作为范围的两个端点的例子:
The parentheses don’t make a difference, as long as they’re valid.
There’s yet another data type to introduce now, and that’s Range. A Range is, as the name suggests, a range of numbers with a start and an end. If you want to make a range with the number 1, 2, 3 and 4, you have two options:
有一种数据类型叫做范围,我们来看下面的这个例子:
You first type a number, 1 in this case (can also be negative). If you then write down two dots, you’re including the number written down after the dots. If you write down three dots, you’re excluding the number written down after the dots. So 1..4 starts at 1 and includes up to 4. 1...5 starts at 1 and goes up to 5, but doesn’t include it.
You can also have negative ranges.
-7..-3 (-7, -6, -5, -4, and -3)
-2..2 (-2, -1, 0, 1, and 2)
You can’t have ranges go from big to small, though. You can’t use Floats either.
2..-2 is empty. Just like an empty array, [], this is empty. Nothing.
1.1..1.3 is also empty. It won’t work when you try to do anything with it (regardless of using parentheses)
同样的,也支持负数的范围,比如说-2..2,就是指从-2到2,并且包括2。
Naturally, ranges also work with variables.
我们来看下面这个使用变量来作为范围的两个端点的例子:
The parentheses don’t make a difference, as long as they’re valid.