木兰编程语言入门教程之一——浅介

本教程不求全面,各个方面点到即止。各位可多尝试,欢迎反馈~

一 浅介

所有示例在运行 ulang.0.2.2.exe 打开的交互环境下测试通过(Win7 64位)。


木兰编程语言入门教程之一——浅介

示例中,开头带>提示的为代码行,不带的为输出。

所有//后的内容为注释,并不执行。/*和*/中间的内容也是。只支持单行注释。

比如:

<code>> // 首行注释
> n = 1 /* 第二行注释!*/
> /* 第三行!*/
> text = "// 这不是注释"
> text
// 这不是注释
/<code>


1.1 计算

四则运算的运算符与括号与数学类似,*为乘,/为除。

如果都为整数,那么结果也会取整(整除):

<code>> (1+3)*2/3
2
/<code>

如果带有小数,结果也是小数:

<code>> (1.0+3)*2/3
2.6666666666666665
/<code>

%为取余数:

<code>> 11%3
2
/<code>

^为求幂:

<code>> 5^2
25
/<code>

=为一个变量赋值,不返回内容:

<code>> width = 2
> height = 3
> width * height
6
/<code>

如果某个变量没见过,则报错:

<code>> hehe
NameError: name 'hehe' is not defined
/<code>


1.2 字符串

用单、双引号括起来,反斜杠为转义符:

<code>> 'doesn\\'t'
doesn't
> '"你好"'
"你好"
> "\"吃了么?\""
"吃了么?"
> "“吃过了!”"
“吃过了!”
/<code>

\\n为换行:

<code>> s='第一行\\n第二行'
> s
第一行
第二行
/<code>

如需表示\\n原始字符串,比如c:\\name,可以这样:

<code>> 'c\\\\\\'+'name'
c\\name
/<code>

通过乘法重复多次:

<code>> 3 * '长长' + '消'
长长长长长长消
/<code>

可以通过位置截取字符串:

<code>> a = '木兰编程语言'
> a[1]

> a[5]

> a[0:2]
木兰
> a[4:]
语言
/<code>

取长度:

<code>> saying = '迅雷不及掩耳之势'
> len(saying)
8
/<code>


1.3 列表

比如平方数数列:

<code>> squares = [1, 4, 9, 17]
> squares
[1, 4, 9, 17]
/<code>

截取其中内容、拼接、求长度都与字符串操作类似。

与字符串不同,列表内容可以修改:

<code>> squares[3] = 16
> squares
[1, 4, 9, 16]
/<code>

也可添加内容:

<code>> squares.append(25)
> squares
[1, 4, 9, 16, 25]
/<code>

也可以修改其中一段:

<code>> squares[1:3] = [40, 90]
> squares
[1, 40, 90, 16, 25]
> squares[2:4] = []
> squares
[1, 40, 25]
/<code>

可清除所有内容:

<code>> squares[:] = []
> squares
[]
/<code>

列表可以包含多个列表,类似多维数组:

<code>> x = [['a', 'b', 'c'], [1, 2, 3]]
> x[0][1]
b
> x[1][2]
3
/<code>


1.4 等差数列

<code>> a = 1
> while a < 10 {
>> println(a)
>> a += 2
>> }
1
3
5
7
9
/<code>

当a小于10,每次循环将a增加2。println在输出内容后换行。print不换行。


分享到:


相關文章: