Julia User Input
User input is a value that a person types while a program runs. The program reads the typed line and can then use it.
readline reads a typed name
The typed input is Ana. The program greets that name.
println("What is your name?")
name = readline()
println("Hello, ", name)Typed digits become a number with parse
The typed input is 7. The program doubles it as a number.
println("Enter a whole number:")
number = parse(Int, readline())
println(number * 2)Two typed lines are read in order
The typed inputs are Ana and then 31. The program prints the age for next year.
name = readline()
age = parse(Int, readline())
println(name)
println(age + 1)Example
println("What is your name?")
name = readline()
println("Enter a whole number:")
number = parse(Int, readline())
println("Hello, ", name)
println(number + 10)Key points
- readline: a function that reads one typed line as text.
- Typed text: readline always gives a String, even when the person types digits.
- Greeting: a program can print the typed name back in a message.
- parse with input: parse(Int, readline()) turns typed digits into a whole number.
- Order: the program waits for the typed line before it runs the next line of code.
In this example, the typed inputs are Leo and then 5. The first readline reads the name as text for the greeting. The second readline is parsed into a number, so adding 10 gives 15.
Note
Scripts in this course state the typed input before each example that needs it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What type does readline give back?