1. if else语句
基本语法
//单条件判断 if condition { //do something } //多条件判断 if condition { } else if condition { //do something } else { //do something }
if 单条件先跟个语句然后再做条件判断
if statement;condition{ //do something } //单条件,不带语句的基本判断 package main import( "fmt" ) func main(){ nu := 1 if nu %2 == 0 { fmt.Println("the number is even") } else{ fmt.Println("the number is odd") } } //单条件,带语句的判断 package main import( "fmt" ) func main(){ if nu := 21; nu % 2 == 0 { //带了一个赋值语句然后再做的判断 fmt.Println("The number is even") } else{ fmt.Println("The number is odd ") } }
注:不太建义这样做因为逻辑看着就复杂了,但是可以减少代码量
if 多条件先跟个语句然后再做条件判断
//多条件,不带语句的判断 package main import( "fmt" ) func main(){ num := 34 if num <= 50{ fmt.Println("Number is less then 50") } else if num >= 51 && num <= 100{ fmt.Println("The number is between 51 and1 100") } else{ fmt.Println("The number is greater than 100") } } //多条件,带语句的判断 package main import( "fmt" ) func main(){ //num := 34 if num := 78;num <= 50{ fmt.Println("Number is less then 50") } else if num >= 51 && num <= 100{ fmt.Println("The number is between 51 and1 100") } else{ fmt.Println("The number is greater than 100") } }
有疑问加站长微信联系(非本文作者)