把循環(huán)寫完了枪蘑。感覺和Python的差別不是很大损谦。只是在GO中單獨(dú)有switch, select岳颇。循環(huán)語句和python一毛一樣照捡。中斷關(guān)鍵字,break.continue 也是一樣的用法
package main
import ("fmt")
func main() {
//運(yùn)算符 第一類 加減乘除,取余數(shù)等
a, b := 5, 10
var c int
c = a + b
c = a - b
d := 6
d *= a //與Python類似话侧。 d= d*a
fmt.Println(c, d)
// 運(yùn)算符 第二類:關(guān)系運(yùn)算符 ==, !=, >,<,>=,<=栗精,返回的是bool類型的false,true
i :=4
// 條件:if else
if i%2 ==0 {
fmt.Println("this is even")
} else {
fmt.Println("this is odd")
}
//條件:if...else if...
j := 9
if j %2 ==0 {
fmt.Println("j能被2整除")
} else if j%3 ==0 {
fmt.Println("j能被3整除")
} else if j%4 ==0 {
fmt.Println("j能被4整除")
}
//條件:switch
//條件語句:switch,case,按照順序向下進(jìn)行匹配悲立,匹配成功后break鹿寨,不會(huì)再進(jìn)行匹配。
//switch默認(rèn)情況下case 最后自帶break語句薪夕,匹配成功后不會(huì)執(zhí)行其他case脚草,如果我們需要執(zhí)行后面的case,可以使用fallthrough原献。
//fallthrough:強(qiáng)制執(zhí)行后面的case語句
//switch var1 {
// case val1: 執(zhí)行的命令
// ...
// case val2:
// ...
// default:
// ...
//}
//switch x.(type){
// case type:
// statement(s);
// case type:
// statement(s);
// default: // 可選
// statement(s);
//}
//條件寫在外面馏慨,switch當(dāng)作if else
score :=90
switch {
case score >90:fmt.Printf("優(yōu)秀\n")
fallthrough
case score<=90 || score >80:fmt.Printf("加油吧\n")
default:fmt.Printf("你還有啥吧\n")
}
//條件寫在switch中
switch scores :=91;{
case scores >90:fmt.Printf("優(yōu)秀\n")
fallthrough
case scores<=90 || scores >80:fmt.Printf("加油吧\n")
default:fmt.Printf("你還有啥吧\n")
}
grade := "B"
marks := 90
switch marks {
case 90:
grade = "A"
case 80:
grade = "B"
case 70, 60, 50:
grade = "C"
}
switch{
case grade =="A": fmt.Printf("優(yōu)秀A")
case grade =="B": fmt.Printf("良好B")
case grade =="C": fmt.Printf("加油吧您內(nèi)C")
}
fmt.Printf("你的等級是 %s\n", grade )
//條件:select:
//select {
// case communication clause :
// statement(s);
// case communication clause :
// statement(s);
// default : // 可選
// statement(s);
//}
//循環(huán):for
//for init; condition; post { } //for
//for condition { } //while
//for {}
//init: 一般為賦值表達(dá)式,給控制變量賦初值姑隅;
//condition: 關(guān)系表達(dá)式或邏輯表達(dá)式写隶,循環(huán)控制條件;
//post: 一般為賦值表達(dá)式粤策,給控制變量增量或減量樟澜。
m :=10
for i:=0;i<m;i+=1 {
fmt.Println(i)
}
p :=0
for p <10 {
fmt.Println(p)
p+=1
}
//循環(huán)語句的控制關(guān)鍵字:
//break語句:
//用于循環(huán)語句中跳出循環(huán),并開始執(zhí)行循環(huán)之后的語句叮盘。
//break 在 switch(開關(guān)語句)中在執(zhí)行一條 case 后跳出語句的作用秩贰。
//在多重循環(huán)中,可以用標(biāo)號 label 標(biāo)出想 break 的循環(huán)柔吼。
//continue語句:跳過當(dāng)前循環(huán)的剩余語句毒费,然后繼續(xù)進(jìn)行下一輪循環(huán)。
//goto:無條件轉(zhuǎn)移到過程中指定行愈魏,與條件語句配合觅玻,實(shí)現(xiàn)條件轉(zhuǎn)移、構(gòu)成循環(huán)培漏、跳出循環(huán)體等(不建議用溪厘,造成混亂)
}
執(zhí)行結(jié)果
GOROOT=C:\Program Files\JetBrains\GoLand 2020.1.3\go1.15.6\go #gosetup
-5 30
this is even
j能被3整除
加油吧
優(yōu)秀
加油吧
優(yōu)秀A你的等級是 A
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
Process finished with exit code 0