Learning objectives:

In the first module, you will learn the basic concepts of programming. We will start with basic operations in Julia, followed by the different types of variables in programming. This module also covers the different data structures in Julia, such as tuples, dictionaries and arrays, and also some useful built-in functions.

Basics

Below is an example of basic operations in Julia, such as addition, multiplication, division, etc.

1+1
2-3
20*5
100/10
10^2
101%2

If you would like to suppress the output, you can use the semicolon at the end of the command:

2+2;

If you don’t know what a particular function does and you would like to check its documentation, you can use the question mark as below:

?println

In Julia, you can also use Unix Shell commands by using the ; in front of the command:

;pwd

or

;ls

To print the output of a command, we will use the println method and not the print one because the println(“…”) method prints the string “…” and moves the cursor to a new line (adds a new line at the end of the output). The print(“…”) method instead prints just the string “…”, but does not move the cursor to a new line.

println("I am excited to learn Julia!")

Variables

There are several types of variables in programming, with the main types being:

To assign a new variable, you have to use the equal sign after the name of the variable. In the example below, we assign the number 42 to a new variable called my_answer. This new variable is an integer.

my_answer = 42

If you would like to check the type of the variable you just defined, you can use the typeof command:

typeof(my_answer)
Int64

Please note that you can add comments in Julia by using the # symbol in the beginning of the line or by using #= text =# for multiple line comments.

Exercise

A) Assign the number 365 to a variable called days. What is the type of this variable?

B) Convert days to a floating point number

Strings

As we mentioned before, you need to use quotes “string” or triple quotes “”“string””” to define a string. The difference between the single vs triple quotes is that, in the latter, you can use quotation marks within your string.

Be careful! You cannot use single quotation marks (‘) to define strings in Julia!

Below is an example of a string:

"This is my first string."
"This is my first string."

Another example using the triple quotes:

"""This is a string with "special" characters, such as !-@"""
"This is a string with "special" characters, such as !-@"

The following example will give you an error as it uses a wrong syntax to define a string in Julia:

'This is a wrong string'
syntax: Invalid character literal

In this section, you will learn more about printing strings including the values of variables. In the following example, we create two variables called name and age, which are a string and an integer, respectively. If you would like to print a string including the values of these two variables, you need to use the $ symbol in the variable name. For example, if you add $name within the string, you will print the value of the name variable. In this example, we print two strings with the values of the two variables indluded in the outputs:

name = "John"
age = 25

println("Hello $name")
println("You are $age years old")

which gives the following output:

Hello John
You are 25 years old

Here is another example showing how to print the values of both variables in a single command:

println("Hello $name. You are $age years old")
Hello John. You are 25 years old

You can also do calculations within the println command. Note that the calculation should be within parenthesis after the $ symbol:

println("You are $(2*age+10) years old")
You are 60 years old

You can also concatenate strings:

s1 = "String 1";
s2 = "String 2";

string(s1," ",s2, " Another string")
"String 1 String 2 Another string"

Another way to concatenate two strings is by using the * symbol:

s1*s2
"String 1String 2"

Exercise

Define two variables, a=3 and b=4, and use them to create two strings

A) “3 + 4”

B) “7”

Data Structures

Once we start working with many pieces of data at once, it will be convenient for us to store data in structures like arrays or dictionaries rather than just relying on variables.

The types of data structures covered in this section are:

Tuples

You can create a tuple by enclosing an ordered collection of elements in ( ). In this example, we create a tuple called animals including three elements, namely “dogs”, “cats” and “penguins”.

animals = ("dogs", "cats", "penguins")
("dogs", "cats", "penguins")

You can index into the tuple using the square brackets [ ]:

animals[1]
"dogs"

But tuples are immutable, which means that you can’t update its elements:

animals[1] = "lions"
MethodError: no method matching setindex!(::Tuple{String,String,String}, ::String, ::Int64)

Dictionaries

If you have sets of data related to one another, you may choose to store that data in a dictionary. You can create a dictionary using the Dict() function, which you can initialise as an empty dictionary or storing key and value pairs.

The syntax to create a dictionary is: Dict(key1 => value1, key2 => value2, …).

Here is an example of a dictionary. We create a dictionary called phonebook, with the keys being the names, and the values being the phone numbers.

phonebook = Dict("Jenny" => "823-231", "John" => "842-475")
Dict{String,String} with 2 entries:
  "Jenny" => "823-231"
  "John"  => "842-475"

In this example, each name and number is a “key” and “value” pair. You can get Jenny’s number (the value) using the associated key:

phonebook["Jenny"]
"823-231"

You can add another entry to this dictionary using the following syntax:

phonebook["Isabel"] = "736-283";
phonebook
Dict{String,String} with 3 entries:
  "Jenny"  => "823-231"
  "John"   => "842-475"
  "Isabel" => "736-283"

You can also delete entries from the dictionary using pop!

pop!(phonebook, "John");
phonebook
Dict{String,String} with 2 entries:
  "Jenny"  => "823-231"
  "Isabel" => "736-283"

Unlike tuples and arrays, dictionaries are not ordered. So, you can’t index into them using numbers (except if the keys are these numbers). If you try to access phonebook[1], you will get an error saying that key 1 has not found.

phonebook[1]
KeyError: key 1 not found

Exercise

Try to add “Emergency” as key to the phonebook dictionary with the value 911 using the following syntax:

phonebook[“Emergency”]=911

Why doesn’t this work?

Arrays

Unlike tuples, arrays are mutable, and unlike dictionaries, arrays contain ordered collections. You can create an array by enclosing this collection in [ ].

The syntax to create an array is: [item1, item2, …].

For example, let’s create an array called fibonachi with the first few fibonacci numbers (https://en.wikipedia.org/wiki/Fibonacci_number).

fibonacci = [1,1,2,3,5,8,13]
7-element Array{Int64,1}:
  1
  1
  2
  3
  5
  8
 13

The elements in an array can be a mix of variable types. In the example below, we create an array that includes integers and strings:

mix = [1, 2, 3, "Jenny", "John"]
5-element Array{Any,1}:
 1       
 2       
 3       
  "Jenny"
  "John"

To select an element of an array, you need to use the index inside square brackets:

mix[3]
3

You are also able to update the value of an element:

mix[3] = "Jack"
mix
5-element Array{Any,1}:
 1       
 2       
  "Jack" 
  "Jenny"
  "John" 

You can also add more elements in the array using push!

push!(fibonacci, 21)
fibonacci
8-element Array{Int64,1}:
  1
  1
  2
  3
  5
  8
 13
 21

and you can remove an element from an array using pop! (similar to dictionaries):

pop!(fibonacci)
fibonacci
6-element Array{Int64,1}:
 1
 1
 2
 3
 5
 8

Exercise

Create an array called a_array with the following code:

a_array = [1,2,3]

Add the number 4 to the end of this array and then remove it

Useful functions in Julia

There are several built-in functions in Julia that are very useful and practical for our coding. Here is a list of some useful built-in function in Julia for basic operations.

Function     Description
round(x, N)     round x to the nearest integer using N decimal points
floor(x, N)     round x to the nearest lower integer using N decimal points
ceil(x, N)     round x to the nearest upper integer using N decimal points
abs(x)     the absolute value of x
sign(x)     indicates the sign of x
sqrt(x)     square root of x
exp(x)     natural exponential function at x
log(x)     natural logarithm of x
log(b, x)     base b logarithm of x
log10(x)     base 10 logarithm of x
A’     transpose of matrix/array A

Trigonometric and hyperbolic functions

These functions are all single-argument, except for atan2, which gives the angle in radians between the x-axis and the point specified by its arguments, interpreted as x and y coordinates. Additionally, sinpi(x) and cospi(x) are provided for more accurate computations of sin(pix) and cos(pix), respectively.

           
sin cos tan cot sec csc
sinh cosh tanh coth sech csch
asin acos atan acot asec acsc
asinh acosh atanh acoth asech acsch
sinc cosc atan2      

To compute trigonometric functions with degrees instead of radians, suffix the function with d, as shown below. For example, sind(x) computes the sin of x with x specified in degrees. The complete list of trigonometric functions with degree variants is:

           
sind cosd tand cotd secd cscd
asind acosd atand acotd asecd acscd

Go to Module 2 (Slicing)