Skip to content

Mojo Reading Input

Command-line arguments are fixed when the program starts. Sometimes you’d rather ask while it runs: “What’s your name?”, “Pick a number”. Mojo’s input() does that, and it looks a lot like Python’s. There’s one real difference (it can raise an error) and one surprise with piped input, both covered below.

These programs wait for you to type, so each example shows a session from a real terminal under “You’ll see”: the prompt, what we typed, and what the program printed. All of it was run with Mojo 1.2 on Linux.

input() prints a prompt, waits for the user to type a line and press Enter, then gives you that line as a String:

def main() raises:
var name = input("What's your name? ")
print(t"Nice to meet you, {name}!")
Terminal window
mojo run name.mojo

You’ll see (we typed Ada):

What's your name? Ada
Nice to meet you, Ada!

Three details:

  • The prompt is printed without a newline, so the cursor waits right after it. End your prompt with a space so the answer doesn’t stick to it.
  • The newline from pressing Enter is not part of the result: name is just "Ada".
  • The prompt is optional: the input() reference shows it defaults to an empty string, so input() with no argument just waits.

In Python, input() raises EOFError if there’s nothing left to read, but you’re never forced to think about it. In Mojo, input() is a function that can raise, and the compiler makes you deal with that. Leave out raises and it won’t build:

def main():
var name = input("Name: ")
print(name)
name.mojo:2:21: error: cannot call function that may raise in a context that cannot raise
var name = input("Name: ")
~~~~~^~~~~~~~~~
name.mojo:2:21: note: try surrounding the call in a 'try' block
var name = input("Name: ")
^
name.mojo:1:5: note: or mark surrounding function as 'raises'
def main():
^
mojo: error: failed to parse the provided Mojo source module

The compiler even suggests both fixes: mark main as raises, or put the call inside try. The Mojo Errors lesson explains raising functions in general. Further down you’ll see when input() actually raises.

input() always gives you text. For a number, convert it with Int() or Float64(). It’s a good habit to call .strip() first, which removes spaces the user typed by accident:

def main() raises:
var text = input("How old are you? ")
var age = Int(text.strip())
print(t"In ten years you'll be {age + 10}.")

You’ll see (we typed 36):

How old are you? 36
In ten years you'll be 46.

If you type thirty instead, Int() raises, and since nothing catches it, the program stops:

How old are you? thirty
stack trace was not collected. Enable stack trace collection with environment variable `MODULAR_DEBUG=stack-trace-on-error`
Unhandled exception caught during execution: String is not convertible to integer with base 10: 'thirty'
mojo: error: execution exited with a non-zero result: 1

That’s fine for a quick script, but people mistype all the time. The friendly thing is to ask again.

Put the question in a loop. Return when the answer is good; print a hint and go round again when it isn’t:

def ask_number(prompt: String, low: Int, high: Int) raises -> Int:
while True:
var text = input(prompt)
try:
var n = Int(text.strip())
if low <= n <= high:
return n
print(t"Please pick a number from {low} to {high}.")
except:
print(t"'{text}' isn't a whole number. Try again.")
def main() raises:
var n = ask_number("Pick a number from 1 to 10: ", 1, 10)
print(t"You picked {n}.")

You’ll see (we typed seven, then 42, then 7):

Pick a number from 1 to 10: seven
'seven' isn't a whole number. Try again.
Pick a number from 1 to 10: 42
Please pick a number from 1 to 10.
Pick a number from 1 to 10: 7
You picked 7.

The try only wraps the conversion, so a bad number is caught right there and the loop continues. low <= n <= high is a chained comparison, just like in Python. Putting all this in its own function keeps main short, and you can reuse ask_number for every question that needs a number.

To collect several answers, keep calling input() and stop on an agreed signal. An empty line is a natural one:

def main() raises:
print("What do you need? Press Enter on an empty line when you're done.")
var items: List[String] = []
while True:
var item = input("- ").strip()
if item == "":
break
items.append(String(item))
print(t"Your list has {len(items)} items:")
for i in range(len(items)):
print(t"{i + 1}. {items[i]}")

You’ll see (we typed eggs, milk, bread and an empty line):

What do you need? Press Enter on an empty line when you're done.
- eggs
- milk
- bread
-
Your list has 3 items:
1. eggs
2. milk
3. bread

.strip() gives back a string view, so String(item) turns it into a String the list can keep. Thanks to .strip(), milk was saved as plain milk.

input() raises when there’s nothing left to read. In a terminal that happens when the user presses Ctrl+D (on Linux and macOS). Catch it to end politely instead of crashing:

def main():
try:
var name = input("Name: ")
print(t"Hi, {name}!")
except e:
print()
print(t"No name given ({e}).")

You’ll see (we pressed Ctrl+D instead of typing):

Name:
No name given (EOF).

The error message is simply EOF (“end of file”). The extra print() moves to a new line, because the cursor was still sitting after the prompt.

You can also feed a program from another command or a file, with | or <. Here’s a small surprise in Mojo 1.2. This program asks twice:

def main() raises:
var first = input("First: ")
var second = input("Second: ")
print(t"Got {first} and {second}")

Typed by hand, it works as expected (Got Ada and Linus). But when both lines arrive together through a pipe, the second input() finds nothing:

Terminal window
printf 'Ada\nLinus\n' | mojo run two.mojo

You’ll see:

First: Second: stack trace was not collected. Enable stack trace collection with environment variable `MODULAR_DEBUG=stack-trace-on-error`
Unhandled exception caught during execution: EOF
mojo: error: execution exited with a non-zero result: 1

In our tests, the first input() read both lines from the pipe in one go and kept only the first one, so Linus was lost. If your program should accept piped text, don’t use input() for it. Read everything at once instead, then split it into lines:

from std.sys import stdin
def main() raises:
if stdin.isatty():
print("Type some lines, then press Ctrl+D on an empty line.")
var text = open("/dev/stdin", "r").read()
var lines = text.splitlines()
print(t"{len(lines)} lines:")
for line in lines:
print(t"> {line}")
Terminal window
printf 'eggs\nmilk\nbread\n' | mojo run lines.mojo

You’ll see:

3 lines:
> eggs
> milk
> bread

/dev/stdin is the program’s input, opened like any file (files get their own lesson next). .read() reads until the input ends, and .splitlines() cuts the text into lines. stdin.isatty() from std.sys is True when a person is typing at a terminal, so the hint only shows up for humans, not for pipes. mojo run lines.mojo < list.txt works the same way.

Task Python Mojo
Read a line name = input("Name: ") var name = input("Name: ") in a raises function
Read a number int(input()) Int(input().strip())
Bad number ValueError an error you catch with try / except
Nothing left to read EOFError an error with the message EOF
Read all piped input sys.stdin.read() open("/dev/stdin", "r").read()

Ask for a name and an age, then print <name>, next year you'll be <age + 1>.

Hint: you can call .strip() straight on the result of input().

Show solution
def main() raises:
var name = input("Name: ")
var age = Int(input("Age: ").strip())
print(t"{name}, next year you'll be {age + 1}.")

You’ll see (we typed Sam and 29):

Name: Sam
Age: 29
Sam, next year you'll be 30.

main is raises because both input() and Int() can raise. For a friendlier version, reuse ask_number from above for the age.

Ask for numbers one per line until the user enters an empty line. Skip anything that isn’t a number (say so), then print how many numbers you got and their total. Allow decimals like 2.5.

Hint: use Float64() inside try, and continue the loop or just print a message in except.

Show solution
def main() raises:
print("Type numbers, one per line. Press Enter on an empty line to finish.")
var total = 0.0
var count = 0
while True:
var line = input("> ").strip()
if line == "":
break
try:
total += Float64(line)
count += 1
except:
print(t"skipping '{line}'")
print(t"{count} numbers, total {total}")

You’ll see (we typed 4, 2.5, abc, 10 and an empty line):

Type numbers, one per line. Press Enter on an empty line to finish.
> 4
> 2.5
> abc
skipping 'abc'
> 10
>
3 numbers, total 16.5

The try around Float64(line) means one bad line doesn’t end the program. total starts as 0.0, so it’s a Float64 from the start.

  • input("prompt ") prints the prompt, waits for a line, and returns it as a String without the newline.
  • input() can raise, so call it in a raises function or inside try.
  • Convert answers with Int(text.strip()) or Float64(...); both raise on bad text.
  • For friendly programs, ask again in a loop until the answer is valid.
  • Ctrl+D (end of input) makes input() raise with the message EOF.
  • For piped input, read it all with open("/dev/stdin", "r").read() and .splitlines(); in Mojo 1.2, repeated input() calls can lose piped lines.

Next up: Mojo file I/O, reading and writing files on disk.

Quick check

1. Why does def main(): var s = input() fail to compile?
2. The user types 42 (with spaces). What is the safest way to get the number?
3. The user presses Ctrl+D at a prompt. What does input() do?
4. Your program should read many lines piped in with cat data.txt | mojo run app.mojo. What does this page recommend?