006_go语言中的if else条件语句

代码演示

package main

import "fmt"

func main() {
	if 7%2 == 0 {
		fmt.Println("7 is even")
	} else {
		fmt.Println("7 is odd")
	}
	if 8%4 == 0 {
		fmt.Println("8 is divisible by 4")
	}
	if num := 9; num < 0 {
		fmt.Println(num, "is negative")
	} else if num < 10 {
		fmt.Println(num, "has 1 digit")
	} else {
		fmt.Println(num, "has multiple digits")
	}
}

代码运行结果

7 is odd
8 is divisible by 4
9 has 1 digit

代码解读:

  • if声明语句可以单独使用,不用带上else
  • 变量声明可以放在条件前面,声明的变量能够在if else的任何分支使用
  • 条件语句不用括号,但是执行语句需要大括号
posted @ 2018-03-28 19:05  Joestar  阅读(134)  评论(0编辑  收藏  举报