add: questions and exercises for the if statement

This commit is contained in:
Inanc Gumus
2018-10-20 19:03:06 +03:00
parent 9652451f5c
commit 63243dbe77
25 changed files with 1155 additions and 15 deletions

View File

@ -0,0 +1,33 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
// ---------------------------------------------------------
// EXERCISE
// Let's start simple. Print the expected outputs,
// depending on the age variable.
//
// EXPECTED OUTPUT
// If age is greater than 60, print:
// Getting older
// If age is greater than 30, print:
// Getting wiser
// If age is greater than 20, print:
// Adulthood
// If age is greater than 10, print:
// Young blood
// Otherwise, print:
// Booting up
// ---------------------------------------------------------
func main() {
// Change this accordingly to produce the expected outputs
// age := 10
// Type your if statement here.
}

View File

@ -0,0 +1,26 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import "fmt"
func main() {
age := 10
if age > 60 {
fmt.Println("Getting older")
} else if age > 30 {
fmt.Println("Getting wiser")
} else if age > 20 {
fmt.Println("Adulthood")
} else if age > 10 {
fmt.Println("Young blood")
} else {
fmt.Println("Booting up")
}
}

View File

@ -0,0 +1,49 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import "fmt"
// ---------------------------------------------------------
// EXERCISE
// Can you simplify the if statement inside the code below?
//
// When:
// isSphere == true and
// radius is equal or greater than 200
//
// It will print "It's a big sphere."
//
// Otherwise, it will print "I don't know."
//
// EXPECTED OUTPUT
// It's a big sphere.
// ---------------------------------------------------------
func main() {
// DO NOT TOUCH THIS
isSphere, radius := true, 100
var big bool
if radius >= 50 {
if radius >= 100 {
if radius >= 200 {
big = true
}
}
}
if big != true {
fmt.Println("I don't know.")
} else if !(isSphere == false) {
fmt.Println("It's a big sphere.")
} else {
fmt.Println("I don't know.")
}
}

View File

@ -7,5 +7,14 @@
package main
import "fmt"
func main() {
isSphere, radius := true, 200
if isSphere && radius >= 200 {
fmt.Println("It's a big sphere.")
} else {
fmt.Println("I don't know.")
}
}

View File

@ -0,0 +1,28 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
// ---------------------------------------------------------
// EXERCISE
// 1. Get arguments from command-line.
// 2. Print the expected outputs below depending on the number
// of arguments.
//
// EXPECTED OUTPUT
// go run main.go
// Give me args
// go run main.go hello
// There is one: "hello"
// go run main.go hi there
// There are two: "hi there"
// go run main.go i wanna be a gopher
// There are 5 arguments
// ---------------------------------------------------------
func main() {
}

View File

@ -0,0 +1,33 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"os"
)
func main() {
var (
args = os.Args
l = len(args) - 1
)
if l == 0 {
fmt.Println("Give me args")
} else if l == 1 {
fmt.Printf("There is one: %q\n", args[1])
} else if l == 2 {
fmt.Printf(
`There are two: "%s %s"`+"\n",
args[1], args[2],
)
} else {
fmt.Printf("There are %d arguments\n", l)
}
}

View File

@ -0,0 +1,33 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
// ---------------------------------------------------------
// EXERCISE
// 1. Get a number from the command-line.
// 2. Find whether the number is odd, even and divisible by 8.
//
// RESTRICTION
// Handle the error. If the number is not a valid number,
// or it's not provided, let the user know.
//
// EXPECTED OUTPUT
// go run main.go 16
// 16 is an even number and it's divisible by 8
// go run main.go 4
// 4 is an even number
// go run main.go 3
// 3 is an odd number
// go run main.go
// Pick a number
// go run main.go ABC
// "ABC" is not a number
// ---------------------------------------------------------
func main() {
}

View File

@ -0,0 +1,35 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("Pick a number")
return
}
n, err := strconv.Atoi(os.Args[1])
if err != nil {
fmt.Printf("%q is not a number\n", os.Args[1])
return
}
if n%8 == 0 {
fmt.Printf("%d is an even number and it's divisible by 8\n", n)
} else if n%2 == 0 {
fmt.Printf("%d is an even number\n", n)
} else {
fmt.Printf("%d is an odd number\n", n)
}
}

View File

@ -0,0 +1,49 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
// ---------------------------------------------------------
// STORY
// Your boss wants you to create a program that will check
// whether a person can watch a particular movie or not.
//
// Imagine that another program provides the age to your
// program. Depending on what you return, the other program
// will issue the tickets to the person automatically.
//
// EXERCISE
// 1. Get the age from the command-line.
//
// 2. Return one of the following messages if the age is:
// -> Above 17 : "R-Rated"
// -> Between 13 and 17: "PG-13"
// -> Below 13 : "PG-Rated"
//
// RESTRICTIONS:
// 1. If age data is wrong or absent let the user know.
// 2. Do not accept negative age.
//
// BONUS:
// 1. BONUS: Use if statements only twice throughout your program.
// 2. BONUS: Use an if statement only once.
//
// EXPECTED OUTPUT
// go run main.go 18
// R-Rated
// go run main.go 17
// PG-13
// go run main.go 12
// PG-Rated
// go run main.go
// Requires age
// go run main.go -5
// Wrong age: "-5"
// ---------------------------------------------------------
func main() {
}

View File

@ -0,0 +1,34 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("Requires age")
return
}
age, err := strconv.Atoi(os.Args[1])
if err != nil || age < 0 {
fmt.Printf(`Wrong age: %q`+"\n", os.Args[1])
return
} else if age > 17 {
fmt.Println("R-Rated")
} else if age >= 13 && age <= 17 {
fmt.Println("PG-13")
} else if age < 13 {
fmt.Println("PG-Rated")
}
}

View File

@ -0,0 +1,34 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"os"
"strconv"
)
// 🛑 DON'T DO THIS:
// It's hard to read.
// It's just an exercise.
func main() {
if len(os.Args) != 2 {
fmt.Println("Requires age")
return
} else if age, err := strconv.Atoi(os.Args[1]); err != nil || age < 0 {
fmt.Printf(`Wrong age: %q`+"\n", os.Args[1])
return
} else if age > 17 {
fmt.Println("R-Rated")
} else if age >= 13 && age <= 17 {
fmt.Println("PG-13")
} else if age < 13 {
fmt.Println("PG-Rated")
}
}

View File

@ -0,0 +1,43 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
// ---------------------------------------------------------
// EXERCISE
// Detect whether a letter is vowel or consonant.
//
// NOTE
// y or w is called a semi-vowel.
// Check out: https://en.oxforddictionaries.com/explore/is-the-letter-y-a-vowel-or-a-consonant/
//
// HINT
// + You can find the length of an argument using the len function.
//
// + len(os.Args[1]) will give you the length of the 1st argument.
//
// BONUS
// Use strings.IndexAny function to detect the vowels.
// Search on Google for: golang pkg strings IndexAny
//
// EXPECTED OUTPUT
// go run main.go
// Give me a letter
// go run main.go hey
// Give me a letter
// go run main.go a
// "a" is a vowel.
// go run main.go y
// "y" is sometimes a vowel, sometimes not.
// go run main.go w
// "w" is sometimes a vowel, sometimes not.
// go run main.go x
// "x" is a consonant.
// ---------------------------------------------------------
func main() {
}

View File

@ -0,0 +1,34 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"os"
)
func main() {
args := os.Args
if len(args) != 2 || len(args[1]) != 1 {
fmt.Println("Give me a letter")
return
}
// I didn't use a short-if here because, it's already
// hard to read. Do not make it harder.
s := args[1]
if s == "a" || s == "e" || s == "i" || s == "o" || s == "u" {
fmt.Printf("%q is a vowel.\n", s)
} else if s == "w" || s == "y" {
fmt.Printf("%q is sometimes a vowel, sometimes not.\n", s)
} else {
fmt.Printf("%q is a consonant.\n", s)
}
}

View File

@ -0,0 +1,39 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"os"
"strings"
)
func main() {
args := os.Args
if len(args) != 2 || len(args[1]) != 1 {
fmt.Println("Give me a letter")
return
}
s := args[1]
if strings.IndexAny(s, "aeiou") != -1 {
fmt.Printf("%q is a vowel.\n", s)
} else if s == "w" || s == "y" {
fmt.Printf("%q is sometimes a vowel, sometimes not.\n", s)
} else {
fmt.Printf("%q is a consonant.\n", s)
}
// Notice that:
//
// I didn't use IndexAny for the else if above.
//
// It's because, calling a function is a costly operation.
// And, this way, the code is simpler.
}

View File

@ -0,0 +1,30 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
// ---------------------------------------------------------
// EXERCISE
// Find out whether a given year is a leap year or not.
//
// EXPECTED OUTPUT
// go run main.go
// Give me a year number
// go run main.go eighties
// "eighties" is not a valid year.
// go run main.go 2018
// 2018 is not a leap year.
// go run main.go 2019
// 2019 is not a leap year.
// go run main.go 2020
// 2020 is a leap year.
// go run main.go 2024
// 2024 is a leap year.
// ---------------------------------------------------------
func main() {
}

View File

@ -0,0 +1,46 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("Give me a year number")
return
}
year, err := strconv.Atoi(os.Args[1])
if err != nil {
fmt.Printf("%q is not a valid year.\n", os.Args[1])
return
}
// Notice that:
// I've intentionally created this solution as verbose
// as I can.
//
// See the next exercise.
var leap bool
if year%400 == 0 {
leap = true
} else if year%4 == 0 {
leap = true
}
if leap {
fmt.Printf("%d is a leap year.\n", year)
} else {
fmt.Printf("%d is not a leap year.\n", year)
}
}

View File

@ -9,13 +9,11 @@ package main
// ---------------------------------------------------------
// EXERCISE
// ?
//
// NOTE
// ?
// 1. Look at the solution of "the previous exercise".
// 2. And simplify the code (especially the if statements!).
//
// EXPECTED OUTPUT
// ?
// It's the same as the previous exercise.
// ---------------------------------------------------------
func main() {

View File

@ -0,0 +1,36 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("Give me a year number")
return
}
year, err := strconv.Atoi(os.Args[1])
if err != nil {
fmt.Printf("%q is not a valid year.\n", os.Args[1])
return
}
if year%4 == 0 && (year%100 != 0 || year%400 == 0) {
fmt.Printf("%d is a leap year.\n", year)
} else {
fmt.Printf("%d is not a leap year.\n", year)
}
}
// Review the original source code here:
// https://github.com/golang/go/blob/ad644d2e86bab85787879d41c2d2aebbd7c57db8/src/time/time.go#L1289

View File

@ -0,0 +1,78 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
// ---------------------------------------------------------
// EXERCISE
// Print the number of days in a given month.
//
// RESTRICTIONS
// 1. On a leap year, february should print 29. Otherwise, 28.
//
// Set your computer clock to 2020 to see whether it works.
//
// 2. It should work case-insensitive. See below.
//
// Search on Google: golang pkg strings ToLower
//
// 3. Get the current year using the time.Now()
//
// Search on Google: golang pkg time now year
//
//
// EXPECTED OUTPUT
//
// -----------------------------------------
// Your solution should not accept invalid months
// -----------------------------------------
// go run main.go
// Give me a month name
// go run main.go sheep
// "sheep" is not a month.
//
// go run main.go january
// "january" has 31 days.
//
// -----------------------------------------
// Your solution should handle the leap years
// -----------------------------------------
// go run main.go february
// "february" has 28 days.
//
// go run main.go march
// "march" has 31 days.
// go run main.go april
// "april" has 30 days.
// go run main.go may
// "may" has 31 days.
// go run main.go june
// "june" has 30 days.
// go run main.go july
// "july" has 31 days.
// go run main.go august
// "august" has 31 days.
// go run main.go september
// "september" has 30 days.
// go run main.go october
// "october" has 31 days.
// go run main.go november
// "november" has 30 days.
// go run main.go december
// "december" has 31 days.
//
// -----------------------------------------
// Your solution should be case insensitive
// -----------------------------------------
// go run main.go DECEMBER
// "DECEMBER" has 31 days.
// go run main.go dEcEmBeR
// "dEcEmBeR" has 31 days.
// ---------------------------------------------------------
func main() {
}

View File

@ -0,0 +1,58 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"os"
"strings"
"time"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("Give me a month name")
return
}
// get the current year and find out whether it's a leap year
year := time.Now().Year()
leap := year%4 == 0 && (year%100 != 0 || year%400 == 0)
// setting it to 28, saves me typing it below again
days := 28
month := os.Args[1]
// case insensitive
if m := strings.ToLower(month); m == "april" ||
m == "june" ||
m == "september" ||
m == "november" {
days = 30
} else if m == "january" ||
m == "march" ||
m == "may" ||
m == "july" ||
m == "august" ||
m == "october" ||
m == "december" {
days = 31
} else if m == "february" {
// try a "logical and operator" above.
// like: `else if m == "february" && leap`
if leap {
days = 29
}
} else {
fmt.Printf("%q is not a month.\n", month)
return
}
fmt.Printf("%q has %d days.\n", month, days)
}

View File

@ -92,8 +92,8 @@ fmt.Println(2.9 <= 2.9)
## What does this code print?
```go
fmt.Println(1 >= true)
fmt.Println(0 <= false)
fmt.Println(false >= true)
fmt.Println(true <= false)
```
1. true true

View File

@ -25,6 +25,15 @@
> **3:** That's right. All the logical operators expect a bool value (or a bool expression that yields a bool value).
## Which expression below equals to the sentence below?
"age is equal or above 15 and hair color is yellow"
1. `age > 15 || hairColor == "yellow"`
2. `age < 15 || hairColor != "yellow"`
3. `age >= 15 && hairColor == "yellow"` *CORRECT*
4. `age > 15 && hairColor == "yellow"`
## What does this program print?
```go
package main
@ -120,10 +129,10 @@ func duper() bool {
}
```
1. "super duper super duper"
2. "duper super"
3. "duper super duper super"
4. "super duper"
1. "super duper super duper "
2. "duper super " *CORRECT*
3. "duper super super duper "
4. "super duper "
> **1, 3:** Remember: Logical operators short-circuit.

View File

@ -1,11 +1,202 @@
## What does control flow mean?
## What does "control flow" mean?
1. Changing the top-to-bottom execution of a program
2. Changing the left-to-right execution of a program
3. Controlling which statements are executed *CORRECT*
3. Deciding which statements are executed *CORRECT*
> **1:** You can't change that.
> **1, 2:** You can't change that.
>
> **3:** That's right. Control flow allows us to decide which parts of a program is to be run depending on condition values such as true or false.
## How can you simplify the condition expression of this if statement?
```go
if (mood == "perfect") {
// this code is not important
}
```
1. `if {mood == perfect}`
2. `if [mood == perfect]`
3. `if mood = perfect`
4. `if mood == perfect` *CORRECT*
> **1, 2:** That's a syntax error. Try again.
>
> **3:** `=` is the assignment operator. It cannot be used as a condition.
>
> **4:** That's right. In Go, you don't need to use the parentheses.
## The following code doesn't work. How you can fix it?
```go
package main
import "fmt"
func main() {
// this program prints "cool"
// when the mood is "happy"
mood := "happy"
if "happy" {
fmt.Println("cool")
}
}
```
1. Just wrap the "happy" inside parentheses.
2. You need to compare mood with "happy". Like this: `if mood == "happy" { ... }` *CORRECT*
3. Just directly use `mood` instead of `happy`. Like this: `if mood { ... }`
4. This should work! This is a tricky question.
> **1:** That won't change anything. Go adds the parentheses automatically behind the scenes for every if statement.
>
> **2:** Yep. In Go, condition expressions always yield a bool value. Using a comparison operator will yield a bool value. So, it will work.
>
> **2:** You can't change that.
> **4:** No, it's not :)
## How can you simplify the following code? You only need to change the condition expression, but how?
```go
package main
import "fmt"
func main() {
happy := true
if happy == true {
fmt.Println("cool!")
}
}
```
1. `happy != false`
2. `!happy == false`
3. `happy` *CORRECT*
4. `!happy == true`
> **1, 2:** Right! But you can do it better.
>
> **3:** Perfect! You don't need to compare the value to `true`. `happy` is already true, so it'll print "cool!".
>
> **4:** That won't print anything. `happy` will be true.
## How can you simplify the following code? You only need to change the condition expression, but how?
```go
package main
import "fmt"
func main() {
happy := false
if happy == !true {
fmt.Println("why not?")
}
}
```
1. Easy! Like this: `happy != true`
2. `!happy` *CORRECT*
3. `happy == false`
4. `!happy == false`
> **1, 3:** Right! But you can do it better.
>
> **2:** Perfect! You don't need to compare the value to `false` or to `!true` (which is false). `!happy` already returns true, because it's false at the beginning.
>
> **4:** That won't print anything. `happy` will be true.
## Is this code going to work? Why?
```go
package main
import "fmt"
func main() {
happy := false
if happy {
fmt.Println("cool!")
} else if !happy {
fmt.Println("why not?")
} else {
fmt.Println("why not?")
} else {
fmt.Println("why not?")
}
}
```
1. Remove one of the else branches. *CORRECT*
2. Move the else if as the last branch.
3. It repeats "why not?" several times.
4. Remove the `else if` branch.
> **1:** Right. There can be only one else branch.
>
> **2:** If there's an else branch, you can't move else if branch as the last branch.
>
> **3, 4:** So? :) That's not the cause of the problem.
>
## What's the problem with the following code?
```go
package main
import "fmt"
func main() {
happy := true
energic := happy
if happy {
fmt.Println("cool!")
} else if !happy {
fmt.Println("why not?")
} else if energic {
fmt.Println("working out?")
}
}
```
1. It declares the energic variable unnecessarily.
2. You can't use more than one else if branch.
3. It will never run the last else if branch. *CORRECT*
4. There's no else branch.
> **2:** Well, actually you can.
>
> **3:** Right. `happy` can only be either true or false. That means, it will always execute the first two branches, but it will never execute the else if branch.
>
> **4:** It doesn't have to be. Else branch is optional.
## How can you simplify the following code?
```go
package main
import "fmt"
func main() {
happy := false
if happy {
fmt.Println("cool!")
} else if happy != true {
fmt.Println("why not?")
} else {
fmt.Println("why not?")
}
}
```
1. Change `else if`'s condition to: `!happy`.
2. Move the else branch before else if.
3. Remove the else branch.
4. Remove the else if branch. *CORRECT*
> **1, 3:** Close! But, you can do it even better.
>
> **2:** You can't: `else` branch should be the last branch.
>
> **4:** Cool. That's not necessary because `else` branch already handless "unhappy" situation. It's simpler because it doesn't have a condition.

View File

@ -0,0 +1,144 @@
## What's a nil value?
1. The dark matter that rules the universe.
2. It's a zero value for pointers or pointer-based types. It means the value is uninitialized. *CORRECT*
3. It's equal to empty string: `"" == nil` is true.
## What's an error value?
1. It stores the error details *CORRECT*
2. A global variable which stores the error status.
3. A global constant which stores the error status.
> **2, 3:** There aren't any global variables in Go. There are only package level variables. And, since the error value is just a value, so it can be stored in any variable.
>
## Why error handling is needed?
1. I don't know.
2. To control the execution flow.
3. To make a program malware safe.
4. Because, things can go wrong. *CORRECT*
> **1:** Then, please rewatch the lecture! :)
>
> **2:** Actually yes, but that's not the main reason.
>
> **3:** Come on!
## How Go handles error handling?
1. Using a throw/catch block
2. Using a simple if statement with nil comparison *CORRECT*
3. Using a mechanism called tagging
> **1:** There isn't a throw/catch block in Go; unlike Java, C#, and so on... Go is explicit.
## When you should handle the errors?
1. After the main func ends.
2. Before calling a function.
3. Immediately, after calling a function which returns an error value. *CORRECT*
## For which one of the following functions that you might want to handle the errors?
```go
func Read() error
func Write() error
func String() string
func Reset()
```
1. Read and Write *CORRECT*
2. String and Reset
3. Read, Write and Reset
4. For neither of them
5. For all of them
> **1:** They return error values. So, you might want to handle the errors after you call them.
>
> **2:** They don't return error values. So, you don't have to handle any errors.
>
> **3:** Partially true. Try again.
## Let's say a function returns a nil error value. So, what does that mean?
1. The function call is failed.
2. The function call is successful. *CORRECT*
3. The function call is in an indeterministic state. We can't know.
## Let's say a function returns a non-nil error value. So, what does that mean?
1. The function call is failed. *CORRECT*
2. The function call is successful.
3. The function call is in an indeterministic state. We can't know.
> **1:** Yep. Later on you'll learn that, this is not always true. Sometimes a function can return a non-nil error value, and the returned value may indicate something rather than an error. Search on Google: golang io EOF error if you're curious.
## Does the following program correctly handles the error?
**NOTE:** This is what the `ParseDuration` function looks like:
```go
func ParseDuration(s string) (Duration, error)
```
```go
package main
import (
"fmt"
"time"
)
func main() {
d, err := time.ParseDuration("1h10s")
if err != nil {
fmt.Println(d)
}
}
```
1. Yes. It prints the parsed duration if it's successful.
2. No. It doesn't check for the errors.
3. No. It prints the duration even when there's an error. *CORRECT*
> **1:** Yes, it handles the error; however it does so incorrectly. Something is missing here. Look closely.
>
> **2:** Actually, it does.
>
> **3:** That's right. It shouldn't use the returned value when there's an error.
## Does the following program correctly handles the error?
**NOTE:** This is what the `ParseDuration` function looks like:
```go
func ParseDuration(s string) (Duration, error)
```
```go
package main
import (
"fmt"
"time"
)
func main() {
d, err := time.ParseDuration("1h10s")
if err != nil {
fmt.Println("Parsing error:", err)
return
}
fmt.Println(d)
}
```
1. Yes. It prints the parsed duration if it's successful. *CORRECT*
2. No. It doesn't check for the errors.
3. No. It prints the duration even when there's an error.
> **1:** That's right. When there's an error, it prints a message and it quits from the program.
>
> **2:** Actually, it does.
>
> **3:** No, it does not. It only prints it when there isn't an error.

View File

@ -0,0 +1,71 @@
## How to fix this program?
```go
package main
import (
"fmt"
"time"
)
func main() {
if err != nil; d, err := time.ParseDuration("1h10s") {
fmt.Println(d)
}
}
```
1. Swap the simple statement with the `err != nil` check. *CORRECT*
2. Remove the error handling.
3. Remove the semicolon.
4. Change the short declaration to an assignment.
> **1:** Yes. In a short if statement, the simple statement (the short declaration there) should be the first part of it. Then, after the semicolon separator, there should be a condition expression.
>
> **2:** You don't want that. That's not the issue here.
## What does this program print?
```go
package main
import "fmt"
func main() {
done := false
if done := true; done {
fmt.Println(done)
}
fmt.Println(done)
}
```
1. true and true
2. false and false
3. true and false *CORRECT*
4. false and true
> **3:** Yes. It shadows the main()'s done variable, and inside the if statement, it prints "true". Then, after the if statement ends, it prints the main()'s done variable which is "false".
## How can you fix this code?
```go
package main
import "fmt"
func main() {
done := false
if done := true; done {
fmt.Println(done)
}
fmt.Println(done)
}
```
1. Remove the first declaration (main()'s done)
2. Remove the declaration in the short-if (if's done)
3. Change the done declaration of the main() to an assignment
4. Change the done declaration of the short-if to an assignment. And, after the if statement, assign false back to the done variable. *CORRECT*
> **1:** That will break the program. The last line tries to print it.
>
> **2:** The program wants to use it to print true.
>
> **3:** There will be "undefined variable" error.
> **4:** Yes, that will solve the shadowing issue. Short-if will reuse the same done variable of the main(). And, after the short-if, done will be false because of the assignment, and it will print false.