Introduction and Overview
Contents
Introduction and Overview¶
Meta Thoughts:¶
What are these pages and how do they work.¶
These pages are called Jupyter notebooks. They allow one to run snippets of code in a web environment without any setup, downloads, or configuration. This dramatically reduces the learning curve for getting up and running on the first day. Just click the button up at the button at the top and click the “Binder” link. It will open up an environment where you can run the code in these snippets as well as make edits and run your own code. More on this will be explained as we go along.
What we are and are not going to do in these tutorials:¶
We will
learn how to think about problems like a programmer
learn how to learn like a programmer
learn to write programs
learn about the fundamentals of writing “good” code, good programming habits, and the principles of software-engineering.
learn how to do basic troubleshooting / debugging
learn how to make our lives scientists easier by using code.
Do Math
Process Data
We won’t
talk about how computers work unless absolutely necessary
“master” the skill of programming
Computational thinking:¶
You may or may not know it, but you have been taught some concepts about how to think like a programmer all your life. The first step to writing code is to understand what is is you are going to do, that is what are you going to “compute.” Like science and engineering problems, first the ideas must be understood, then described in equations. Only then can the “answers” be acquired.
Using computational thinking one has the tools required to synthesize problems and arrive at their solutions.
Decomposition¶
breaking down a complex problem or system into smaller, more manageable parts
“Don’t solve the whole problem at once.”
Pattern recognition¶
looking for similarities among and within problems
“Have I done something similar before?”
“Don’t reinvent the wheel”
Abstraction¶
focusing on the important information only, ignoring irrelevant detail
“Synthesize the real world concept into the necessary information for solving the problem”
“Model the real system, concept, etc. with data and procedures”
Algorithms¶
developing a step-by-step solution to the problem, or the rules to follow to solve the problem
examples in day to day life
Cooking Recipes
Directions from your house to the grocery store
Sorting Papers in alphabetical order
Performing mathematical operations using PEMDAS.
Algorithms are the steps to the solution of a problem. In programming we write code to “implement” these algorithms, so they can be “executed” on a computer to get a solution.
Programming Languages¶
“A programming language is any set of rules that converts [text], to various kinds of machine code output. Programming languages are one kind of computer language, and are used in computer programming to implement algorithms.”` 2
Syntax:¶
Just as a spoken language has syntax, so does a computer programming language. The rules are just as strict for communicating properly. I cannot stress this highly enough, a computer can only understand machine code (a topic for later.) But a short description for now is that a computer can, using a program called a compiler/interpreter (or other similar concepts), convert the text of a program written in a programming language into it to machine code, which are instructions that it can execute. If any of the code does not conform to the rules of the programming language that process will fail and you will not be able to run your code. At the end of the module there are examples of the programs that won’t work because of “syntax errors”.
Just remember: “The computer does not speak english!”””
Your First Program¶
There is a time honored tradition in the instruction of programming. The first program one is taught code is almost always the same. The program is called “Hello World.” We will continue this tradition.
The purpose of Hello World is to print the text hello world to the output. It seems trivial but one uses it all the time when setting up a new computer, or installing a programming language, it proves that the system is working.
(You can run this “Program” by clicking the start button in the top menu or hitting SHIFT+ENTER while you have the cell selected.)
println("Hello World!")
Hello World!
Let’s break down set of each characters on the screen:
println( )
This is the function we are calling, it prints a line of text to the output. The println is a function provided by the julia. A function in programming can be thought of in the same way as one thinks about a function in mathematics. It has parameters and “returns” an output. In mathematics it is always numbers in and numbers out. In programming we have more freedom to express other ideas through functions.
The println function takes one value, in this case some text.
"Hello World!"
This is a “string” of text. Using the
"
symbol defines the beginning and end of a string.
Another Example¶
What do you think it will print? Will it work?
print("My Favorite Number is: ")
print(7)
My Favorite Number is: 7
Run Code then click to expand Explanation
Notice we used a different function print() vs println(). The difference between the print function and the println function is that the println function starts a new line at the end of the output.
Copy and Paste the following into the box below and execute the code to see the difference
println("My Favorite Number is: ")
println(7)
# Remove this line and copy and paste here
Before we move any further…¶
As we move along in this tutorial I will be introducing some attributes and concepts that key to learning to be a programmer and being what some call a “software-craftsman” (yes there is a difference.) I will introduce them as early as they can be relevant, helpful, and instructive.
The first lesson (which actually is relevant outside of just programming): **Google your exact question and look at the top few results before you ask anyone for help. Especially when you are first starting out, you will likely find the answer. **
As you gain more experience you will get better at phrasing your questions. There are a lot of new terms to learn for programming. There is no need to learn it all at once, taking it one step at a time is a good thing.
Exercise 1¶
Google this exact phrase “How do I get the square root of a number in julia” and see if you can output the square root of 25 to the screen.
Comments¶
A comment in code is text that is not executed by the computer but serves as explanation of the code by the programmer. This is also useful for temporarily removing a line from execution while debugging code.
More on how and when to use comments can be found in Software Engineering Concepts
In Julia this is done by putting the # character before some text.
Examples:
# This is a comment
#=
This is a
multi line
comment
=#
println("hello world") #this is an end of line comment
hello world
Functions¶
“Functions are “self contained” modules of code that accomplish a specific task. Functions usually “take in” data, process it, and “return” a result. Once a function is written, it can be used over and over and over again. Functions can be “called” from the inside of other functions. Functions “Encapsulate” a task (they combine many instructions” which can be used by other modules.
The data they take in are called parameters, there can be none, one, or many. They perform some task(s) and they return the result to the other code that called the function. Functions can call other functions, just like in math.
\(f(x) = xsin(x) + xcos(x)\)
Let’s do an example. Lets put the code from our previous example into a function and call it.
function print_my_favorite_number(favorite_number)
print("My Favorite Number is: ")
print(favorite_number)
end
print_my_favorite_number(7)
My Favorite Number is: 7
Syntax Errors¶
A syntax error is where there is some code that is not “valid.” Julia tries to execute the code, but it cannot understand it, so it has to terminate the program. Here is an example: can you find the error?
Copy the following into the box below and run it:
println("hello world"
# Remove this line and copy and paste here
The main takeaway here is: Code has to be precise, it isn’t like a human language where if it is close people will understand it. If it is a little wrong, it won’t run at all.
This kind of thing will come up often as you are writing code. Thankfully there are tools called “Integrated Development Environments” that will underline code that is incorrect. More on this later. For now know that often the best thing to do, if you can’t figure out the error, is copy and paste the exact error message you get, such as “syntax: incomplete: premature end of input” and put it into google, usually you can find an answer.
Mathematical Operations¶
All of the mathematical operations that you would expect to have are included in Julia. There are also many other functions to do other mathmetical operations. Documentation
println(1 + 1)
println(1 - 1)
println(5*5)
println(3 / 1.5)
println(11 ÷ 4) # this is an integer division
println(11 % 4) # this is an division remainder
println(2^8)
println(2 > 1)
println(round(2.4))
println(abs(-23))
# etc...
2
0
25
2.0
2
3
256
true
2.0
23
Now lets do a function that “returns” a numerical result.
function square_root(number)
return number ^ (1/2)
end
println(square_root(16))
println(square_root(square_root(16))) # notice that you can nest function calls just like in math f(g(x)) or in this case f(f(x))
4.0
2.0
Types and Variables¶
One main concept in writing code is the usage of “variables.” If you think of the code you write as one big function, there are two three types of elements: We discussed the first, which was calling other functions, e.g. the sine function in f(x) = 15*x * sin(x)
. The others are variables and constants.
In mathematics, all variables and constants are numbers, e.g. in f(x) = 15*x * sin(x)
15 is a constant and x is the variable. However, in programming you have more freedom there are more than just numbers. We will not introduce all of these types at one, but introduce them as we go along. The following code shows how you “initialize a variable” with a particular type of data.
The statements start with the name of the variable or constant (and optionally a type description), the equals sign (which in this context means “assignment”) and then and the value. The Julia language and interpreter don’t force you to declare what type a variable is like in many other languages, however it is good practice to specify the variable type (more discussion of this in advanced topics).
Numbers¶
We will start with numbers, which come in two main “flavors”,
integers
whole numbers, e.g. 0, 1, -15, 256, 1202, etc
decimal numbers called floating point numbers
(Don’t worry just yet what those mean, it has to do with how they are stored on a computer with how many bits of information).
e.g. 0.000000, 1.2, -12.34, etc.
Many operations in Julia can be used with floats and integer without having to specify the specific type of number. in that case you can use
Number
.
an_integer = 0
a_float = -10.2
float_zero = 0.0000
println(an_integer)
println(a_float)
println(float_zero)
0
-10.2
0.0
Boolean¶
The next type is called boolean: A boolean can take the only one of two values:
true
false
an example of how this is used is when comparing two values.
example of true statement:
1 + 2 > 2
example of a false statement:
1 > 3
Value Comparison¶
Boolean values often come from comparison of two values. We saw above how we could compare two numbers in the mathematical way. This concept can be applied to many other types of variables. The most important extension of this mathematical idea is the idea of “equality.” An equality check is performed by using the ==
operation. The opposite, non-equality, can be checked with the !=
operation.
Example:
are_they_equal = 12 == 3*4
are_the_strings_equal = "Hello world" == "Hello universe"
println(are_they_equal)
println(are_the_strings_equal)
are_they_equal = 12 == 3*4
are_the_strings_equal = "Hello world" == "Hello universe"
are_the_strings_not_equal = "Hello world" != "Hello universe"
println(are_they_equal)
println(are_the_strings_equal)
println(are_the_strings_not_equal)
true
false
true
The use of = and == may not be intuitive at first. We are used to the “=” meaning equal to. In programming “=” is the assignment operator and “==” is “are the left and right equal?”
First Boolean Operator: Not¶
With boolean variables, there is an operator that flips the value to the other value. i.e. a value of true is converted into false, a value of false is converted to true. The syntax is to put a !
symbol in front of the variable. The way it is said is not, e.g. !x
is said not x.
my_boolean = true
print("my_boolean = ")
println(my_boolean)
not_my_boolean = !my_boolean
print("not_my_boolean = ")
println(not_my_boolean)
print("! not_my_boolean = ")
println(!not_my_boolean)
my_boolean = true
not_my_boolean = false
! not_my_boolean = true
In the above you can see that !!x
is equal to x
.
This can be extended to as many times as you want. An odd number of !s is the same as one !. An even number of !s is the same as the original value.
Example Function¶
Below is a function that initializes some variables.
function some_variables(input_variable:: Int)
the_number_one :: Int = 1 # an integer with the value of one
decimal_one :: Float32 = 1.0 # a floating point decimal number with the value of 1.0
does_jackson_like_icecream :: Bool = true # a boolean with the value of true.
two_is_bigger_than_one = 2 > 1
added_numbers = the_number_one + decimal_one
println(input_variable * added_numbers)
print("Does Jackson Like Ice Cream ")
println(does_jackson_like_icecream)
end
const unchanging_number = 15 # a global constant value
some_variables(unchanging_number)
some_variables(30)
30.0
Does Jackson Like Ice Cream true
60.0
Does Jackson Like Ice Cream true
Variable names¶
as long as the variables follow the allowed syntax (don’t use any disallowed characters) you can name a variable anything you want. It is always recommended to use variable names that describe what the variable is.
address = "123 main street"
is preferred to
input_string = "123 main street"
or worse still
x = "123 main street"
A great book on coding “style”: Clean Code by Robert C. Martin
A quick summary of my thoughts on style can be found in the Software Engineering page.
Control Flow¶
Control flow is changing what your code does based on the values that are passed in (the “state” of the system).
This is accomplished by using boolean values, which again can either take the value of true or false. These boolean values used in a conditional statement that decides what to do based on the truth of the value passed in. These statements are called if-else statements.
lets start with a statement that only has an if.
The syntax is:
if 2 > 1
print("This is always printed because 2 is always greater than 1")
end
# copy the code here
Now an if-else in a function where we can control what the function does by changing the input. In the following example we have some code that might be used in a retail store application. In our hypothetical “store” we sell one item that is sometimes on sale for 30% off.
function get_item_price(give_discount::Bool)
item_price = 100.00
if give_discount
return .7 * item_price
else
return item_price
end
end
println(get_item_price(false))
println(get_item_price(true))
100.0
70.0
Boolean Operations and Logic¶
There are several operations that one can apply to boolean values. Several of them we have already discussed. These operations are:
== (Equality)
!= (Inequalty)
! (not)
&& “And” (Are both values true)
|| “Or” (Is either one true)
Examples:
println("true and true is: $(true && true)") # $() converts values into a string "inline"
println("true and false is: $(true && false)")
println("false and true is: $(false && true)")
println("false and false is: $(false && false)")
println()
println("true or true is: $(true || true)")
println("false or false is: $(true || true)")
println("true and true is: $(true && true)") # $() converts values into a string "inline"
println("true and false is: $(true && false)")
println("false and true is: $(false && true)")
println("false and true is: $(false && false)")
println()
println("true or true is: $(true || true)")
println("true or false is: $(true || false)")
println("false or false is: $(false || false)")
true and true is: true
true and false is: false
false and true is: false
false and true is: false
true or true is: true
true or false is: true
false or false is: false
Below is an example of using booleans to control flow, using the operations we have discussed above. We will test check against known names and email addresses and say if they are in “our contacts.” What this shows is that you can do the same kind of thing two different ways with booleans. The first way in both cases is better, but the second can help you better understand what &&
and ||
do.
function print_is_in_contacts_message(name::String, email_address::String) :: String
#an example of how the && operation works
is_jackson_message = "I am this person!"
if name == "Jackson" && email_address == "jhayes1@iastate.edu"
return is_jackson_message
end
if name == "Jackson"
if email_address == "jhayes1@iastate.edu"
return is_jackson_message # this code is unreachable because the if block is the same as the check above
end
end
# here we show that || is like doing two if statements that both do the same thing
if name == "Joe" || email_address == "joechem@iastate.edu"
return "I know $(name)"
end
if name == "Nick"
return "I know $(name)"
elseif email_address == "nick@iastate.edu"
return "I know $(name)"
end
return "I don't know this person"
end
# output = print_is_in_contacts_message("Jackson", "jhayes1@iastate.edu")
# println(output)
# output = print_is_in_contacts_message("Joe", "joeWrongEmail@blah.edu")
# println(output)
# output = print_is_in_contacts_message("Nick", "nick@iastate.edu")
# println(output)
# output = print_is_in_contacts_message("Sam", "sam@blahblah.edu")
# println(output)
print_is_in_contacts_message (generic function with 1 method)