JULIA / CHAPTER 01

Values, types, and functions

Beginner

Build small Julia calculations with deliberate numeric operations.

By the end of this chapter

  • Define reusable functions
  • Distinguish integer and floating-point division
  • Inspect the types of values

The idea

Julia values have types, and functions can often work with several compatible types without annotating every argument. A variable name refers to a value; an annotation should express a useful constraint rather than merely repeat something obvious. Define a short function with an assignment form or use a function block for several steps. The last evaluated expression supplies the result unless an explicit return exits earlier.

The / operator performs division, while ÷ requests integer division when its arguments are integers. Choose the operation that matches the problem before deciding how to display the answer. Parentheses make evaluation order clear. A function that returns its result is easier to reuse than one that only prints, so keep calculation and presentation as separate responsibilities in a small program.

Julia example
pages_per_day(pages, days) = pages / days
function remaining_pages(total, completed)
    total - completed
end
println(pages_per_day(9, 2))
println(9 ÷ 2)
println(remaining_pages(12, 5))
Result
4.5
4
7

The first calculation retains a fractional quotient. Integer division returns the whole quotient, and the block function returns its final subtraction expression.

Try it yourself

Write a function returning the total cost of several items plus a fixed fee, without printing inside the function.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What does this print?
f(x) = x * 2 + 1
println(f(4))