0% found this document useful (0 votes)
38 views

Chapter 3

The document provides an introduction to conditional expressions and functions in Julia. It explains that conditional expressions allow code to make decisions based on whether a condition is met or not. It demonstrates if/else conditional expressions and comparisons. It also introduces functions, explaining that functions allow code to be reused and details ignored. It shows how to write custom functions to perform conversions like Fahrenheit to Celsius and use functions repeatedly.

Uploaded by

lucy heartfilia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Chapter 3

The document provides an introduction to conditional expressions and functions in Julia. It explains that conditional expressions allow code to make decisions based on whether a condition is met or not. It demonstrates if/else conditional expressions and comparisons. It also introduces functions, explaining that functions allow code to be reused and details ignored. It shows how to write custom functions to perform conversions like Fahrenheit to Celsius and use functions repeatedly.

Uploaded by

lucy heartfilia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Conditionals

INTRODUCTION TO JULIA

James Fulton
Climate informatics researcher
What are conditional expressions?
Tell our computer to do some action if a condition is met

Allow us to write code which makes its own decisions

is_raining = true

# Conditional expression
if is_raining
println("Better get your coat")
end

Better get your coat

INTRODUCTION TO JULIA
What are conditional expressions?
Tell our computer to do some action if a condition is met

Allow us to write code which makes its own decisions

is_raining = true

# Conditional expression
if is_raining
println("Better get your coat")
end

Better get your coat

INTRODUCTION TO JULIA
What are conditional expressions?
is_raining = false

# Conditional expression
if is_raining
println("Better get your coat")
end

INTRODUCTION TO JULIA
Multiple lines of code under the if statement
is_raining = true is_raining = false

if is_raining if is_raining
# This can be many lines of code # This can be many lines of code
println("The weather is awful") println("The weather is awful")
println("Better get your coat") println("Better get your coat")
end end

# Code below end is always run # Code below end is always run
println("Ready to go") println("Ready to go")

The weather is awful Ready to go


Better get your coat
Ready to go

INTRODUCTION TO JULIA
Comparisons
When raining: When dry:

amount_of_rain = 1. amount_of_rain = 0.

# Use comparison # Use comparison


is_raining = amount_of_rain > 0 is_raining = amount_of_rain > 0

print(is_raining) print(is_raining)

true false

INTRODUCTION TO JULIA
Comparisons
When raining: When dry:

amount_of_rain = 1. amount_of_rain = 0.

# Use comparison # Use comparison


is_raining = amount_of_rain > 0 is_raining = amount_of_rain > 0

# Conditional expression # Conditional expression


if is_raining if is_raining
println("Better get your coat") println("Better get your coat")
end end

Better get your coat

INTRODUCTION TO JULIA
Comparisons
When raining: When dry:

amount_of_rain = 1. amount_of_rain = 0.

# Conditional expression # Conditional expression


if amount_of_rain>0 if amount_of_rain>0
println("Better get your coat") println("Better get your coat")
end end

Better get your coat

INTRODUCTION TO JULIA
Other comparisons
a == b check if two values are equal
a = 1.

# Value of a is 1?
println(a==1)

true

# Data type of a is Float64?


println(typeof(a)==Float64)

true

INTRODUCTION TO JULIA
Other comparisons
a == b check if two values are equal
a = 1.
a != b check if two values are not equal
# Value of a is not 1?
println(a!=1)

false

# Data type of a is not Float64?


println(typeof(a)!=Float64)

false

INTRODUCTION TO JULIA
Other comparisons
a == b check if two values are equal
a = 1.
a != b check if two values are not equal
# a is greater than 1?
a > b check if a greater than b
println(a>1)
a >= b check if greater than or equal to

false

# a is greater than or equal to 1?


println(a>=1)

true

INTRODUCTION TO JULIA
Other comparisons
a == b check if two values are equal
a = 1.
a != b check if two values are not equal
# a is less than 1?
a > b check if a greater than b
println(a<1)
a >= b check if greater than or equal to

a < b check if a less than b false


a <= b check if less than or equal to
# a is less than or equal to 1?
println(a<=1)

true

INTRODUCTION TO JULIA
When the condition is not met
amount_of_rain = 0. amount_of_rain = 5.

if amount_of_rain == 0 if amount_of_rain == 0
# Do this if conditon is met # Do this if conditon is met
println("The sky looks clear") println("The sky looks clear")
else else
# Do this if not met # Do this if not met
println("Better get your coat") println("Better get your coat")
end end

The sky looks clear Better get your coat

INTRODUCTION TO JULIA
Additional conditions
amount_of_rain = 0.

if amount_of_rain == 0
println("There is zero rain")
elseif amount_of_rain < 1
# Add a second condition
println("Better get your coat")
else
println("That's a lot of rain, stay home")
end

There is zero rain

INTRODUCTION TO JULIA
Additional conditions
amount_of_rain = 0.5

if amount_of_rain == 0
println("There is zero rain")
elseif amount_of_rain < 1
# Add a second condition
println("Better get your coat")
else
println("That's a lot of rain, stay home")
end

Better get your coat

INTRODUCTION TO JULIA
Additional conditions
amount_of_rain = 2

if amount_of_rain == 0
println("There is zero rain")
elseif amount_of_rain < 1
# Add a second condition
println("Better get your coat")
else
println("That's a lot of rain, stay home")
end

That's a lot of rain, stay home

INTRODUCTION TO JULIA
Multiple elseif's
amount_of_rain = 2

if amount_of_rain == 0
println("There is zero rain")
elseif amount_of_rain < 1 # <--- many elseif conditions
println("Better get your coat")
elseif amount_of_rain < 5 # <--- many elseif conditions
println("You're going to need a bigger coat")
else
println("That's a lot of rain, stay home")
end

You're going to need a bigger coat

INTRODUCTION TO JULIA
Let's practice!
INTRODUCTION TO JULIA
Basic Functions
INTRODUCTION TO JULIA

James Fulton
Climate informatics researcher
What are functions?
Functions you have used:
x = [2,1,3]

println()
# Takes an array, returns integer
typeof()
l = length(x)
string()
# Takes an array, returns sorted array
push!()
x_sorted = sort(x)
pop!()

append!() # Takes a value, prints it to console


println(l)
length()

sort()

INTRODUCTION TO JULIA
Why use functions?
Allows us to focus on program structure

Can ignore irrelevant details of how a function works

INTRODUCTION TO JULIA
Writing custom functions
# Declare function to convert temperatures
function fahrenheit2celsius(temp)
# Function body
return (temp - 32) * 5/9
end

# Use function
println(fahrenheit2celsius(212))

100.0

INTRODUCTION TO JULIA
Writing custom functions
# Declare function to convert temperatures
function fahrenheit2celsius(temp)
# Function body
return (temp - 32) * 5/9
end

# Use function many times


println(fahrenheit2celsius(212))
println(fahrenheit2celsius(100))

100.0
37.77

INTRODUCTION TO JULIA
Longer functions
# Declare function to convert temperatures
function fahrenheit2celsius(temp)
# Function body
temp_sub = temp - 32
temp_c = temp_sub * 5/9
return temp_c
end

t = fahrenheit2celsius(212)
println(t)

100.0

INTRODUCTION TO JULIA
Longer functions
# Declare function to convert temperatures
function fahrenheit2celsius(temp)
# Function body
temp_sub = temp - 32 # variable inside function not available outside
temp_c = temp_sub * 5/9
return temp_c
end

t = fahrenheit2celsius(212)
println(temp_sub)

ERROR: UndefVarError: temp_sub not defined

INTRODUCTION TO JULIA
Return keyword
function x_or_zero(x)
if x>0
return x
else
return 0
end
end

println(x_or_zero(-3))
println(x_or_zero(3))

0
3

INTRODUCTION TO JULIA
Return keyword
# Function with longer body
function check_if_raining(rain_amount)
is_raining = rain_amount > 0
if is_raining
println("Better get your coat")
else
println("The sky looks clear")
end
end

check_if_raining(0.2) # Function returns nothing - only prints

Better get your coat

INTRODUCTION TO JULIA
Multiple arguments
function power(x, y)
return x^y
end

# Use function to calculate 5*5


println(power(5, 2))

25

# Use function to calculate 2*2*2*2*2


println(power(2, 5))

32

INTRODUCTION TO JULIA
Broadcasting functions
function fahrenheit2celsius(temp)
return (temp - 32) * 5/9
end

temps_f = [212, 32, 100]

# Function not written to work with arrays


temps_c = fahrenheit2celsius(temps_f)

ERROR: MethodError: ...

INTRODUCTION TO JULIA
Broadcasting functions
function fahrenheit2celsius(temp)
return (temp - 32) * 5/9
end

temps_f = [212, 32, 100]

# Broadcast function with dot syntax


temps_c = fahrenheit2celsius.(temps_f)
println(temps_c)

[100.0, 0.0, 37.77]

INTRODUCTION TO JULIA
Broadcasting functions
x = ["one", 2, 3.0]

# Broadcast using typeof function


println(typeof.(x))

[String, Int64, Float64]

INTRODUCTION TO JULIA
Broadcasting multiple arguments
function power(x, y)
return x^y
end

x_arr = [1,2,3,4,5]

# Square each element of the array


println(power.(x_arr, 2))

[1, 4, 9, 16, 25]

INTRODUCTION TO JULIA
Broadcasting multiple arguments
function power(x, y)
return x^y
end

x_arr = [1,2,3,4,5]
y_arr = [1,2,3,4,5]

# Use function on x_arr and y_arr


println(power.(x_arr, y_arr))

[1, 4, 27, 256, 3125]

INTRODUCTION TO JULIA
Let's practice!
INTRODUCTION TO JULIA
Mutating functions
and multiple
dispatch
INTRODUCTION TO JULIA

James Fulton
Climate informatics researcher
Mutating functions
Some functions modify inputs push!(x, 4)
println(x)
Starting with the array:

[1, 2, 3, 4]
x = [1,2,3]

append!(x, [4,5,6]) pop!(x)


println(x) println(x)

[1, 2, 3, 4, 5, 6] [1, 2]

INTRODUCTION TO JULIA
Non-mutating functions
Starting with the array: l = length(x)
println(x)
x = [3,1,2]

[3, 1, 2]

x_sorted = sort(x) x_type = typeof(x)


println(x) println(x)

[3, 1, 2] [3, 1, 2]

INTRODUCTION TO JULIA
Mutating and non-mutating functions
Mutating functions change their inputs Non-mutating functions do not change their
inputs
pop!()
sort()
push!()
println()
append!()
typeof()
...
string()

length()

...

INTRODUCTION TO JULIA
Writing a mutating function
function modify_array!(x) function modify_array!(x)
x[1] = 0 x = [0,2,3,4,5]
end end

# Try to mutate y # Try to mutate y


y = [1,2,3,4,5] y = [1,2,3,4,5]
modify_array!(y) modify_array!(y)

# y has changed # y has changed


print(y) print(y)

[0, 2, 3, 4, 5] [1, 2, 3, 4, 5]

INTRODUCTION TO JULIA
Writing a mutating function
function modify_array!(x) function modify_array!(x)
x[1] = 0 x = [0,2,3,4,5]
end end

# Try to mutate y # Try to mutate y


y = [1,2,3,4,5] y = [1,2,3,4,5]
modify_array!(y) modify_array!(y)

print(x) print(x)

ERROR: UndefVarError: x not defined ERROR: UndefVarError: x not defined

INTRODUCTION TO JULIA
Writing a mutating function
function setarray2zero!(x)
x .= 0
end

y = [1,2,3,4,5]
setarray2zero!(y)

print(y)

[0, 0, 0, 0, 0]

INTRODUCTION TO JULIA
Writing a mutating function
function modify_array!(x)
x .= x .- 1
end

y = [1,2,3,4,5]

modify_array!(y)

print(y)

[0, 1, 2, 3, 4]

INTRODUCTION TO JULIA
Multiple dispatch
function double(x) println(double(2)) # Works on integers
return x*2
end 4

println(double(10.0)) # Works on floats

20.0

println(double("yo")) # Not on strings

ERROR: MethodError: ...

INTRODUCTION TO JULIA
Multiple dispatch
function double(x) println(double(2)) # Works on integers
return x*2
end 4

function double(x::String)
println(double(10.0)) # Works on floats
return x*x
end
20.0

println(double("yo")) # Works on strings

yoyo

INTRODUCTION TO JULIA
Multiple dispatch
function double(x) println(double(2)) # Works on integers
return x*2
end 4

function double(x::String)
println(double(10.0)) # Works on floats
return x*x
end
20.0

function double(x::Bool)
return x println(double("yo")) # Works on strings

end
yoyo

INTRODUCTION TO JULIA
Multiple dispatch
println(double(2)) # Not on integers

ERROR: MethodError: ...

function double(x::String)
println(double(10.0)) # Not on floats
return x*x
end
ERROR: MethodError: ...

function double(x::Bool)
return x println(double("yo")) # Works on strings

end
yoyo

INTRODUCTION TO JULIA
Multiple dispatch
function double(x)
return x*2
end

INTRODUCTION TO JULIA
Let's practice!
INTRODUCTION TO JULIA
Using packages
INTRODUCTION TO JULIA

James Fulton
Climate informatics researcher
Packages
A collection of Julia les from which you can import

Popular packages include


Statistics.jl - calculating descriptive statistics

DataFrames.jl - storing and manipulating tabular data

CSV.jl - loading and saving CSV data

Plots.jl - creating visualizations

Thousands more packages exist

Some lists of packages found here:


h ps://julialang.org/packages

INTRODUCTION TO JULIA
Installing packages
import MyPackage

| Package MyPackage not found, but a package named MyPackage is available from a registry.
| Install package?
| (@v1.7) pkg> add MyPackage
|_ (y/n) [y]:

INTRODUCTION TO JULIA
Importing packages
import Statistics using Statistics

m = Statistics.mean([1,2,3]) m = Statistics.mean([1,2,3])
println(m) println(m)

2.0 2.0

m = mean([1,2,3]) m = mean([1,2,3])
println(m) println(m)

ERROR: UndefVarError: mean not defined 2.0

INTRODUCTION TO JULIA
Importing packages
import Statistics as sts using Statistics

m = sts.mean([1,2,3]) m = Statistics.mean([1,2,3])
println(m) println(m)

2.0 2.0

m = mean([1,2,3])
println(m)

2.0

INTRODUCTION TO JULIA
The Statistics package
mean() - Calculate mean of array

median() - Calculate median value of array

std() - Calculate standard deviation of array values

var() - Calculate variance of array values

mean_x = Statistics.mean(x_arr)

median_x = Statistics.median(x_arr)

std_x = Statistics.std(x_arr)

var_x = Statistics.var(x_arr)

INTRODUCTION TO JULIA
Let's practice!
INTRODUCTION TO JULIA

You might also like