Mojo – How to input an integer

Version: mojo 0.6.3 (f58f8b94)

If you come from other programming languages, the “input” function is supported natively to take the input from the user. The names are various depending on the languages (prompt() in Javascript, input() in Python, stdin.readLineSync() in Dart). Below is an example in Python using input() function:

# Take a name (string) from user then print it out
name = input('Enter your name: ')
print(name)

# Output: 
Enter your name: Phuc
Phuc
# Take a number (integer) from user then print it out
# Let's ignore the case that user enters a non-integer value, which will cause the exception
n = int(input('Please enter an integer: '))
print(n)

# Output: 
Please enter an integer: 10
10

At the time I am writing this blog, Mojo (v0.6.3) does not provide any similar “input” method. In this post, I am sharing a few approaches to take user input in Mojo by using Python integration. I am not sure these are the best ways though, any feedback is welcome.

1. Using Python.import_module()

fn inputInteger(message: String) raises -> Int:
    '''Take an integer from user and return it.

    Args:
        message: The message to show to the user before entering the integer.
    '''
    let input = Python.import_module('builtins').input
    # input(message).__str__() -> Convert the input (PythonObject) from user to string
    # atol -> Parse input string to integer
    let i = atol(input(message).__str__())
    return i

fn main() raises:
    let n = inputInteger('Please enter an integer: ')
    print(n)

# Output
Please enter an integer: 2024
2024

2. Using Python.evaluate()

from python import Python

fn inputInteger(message: StringLiteral) raises -> Int:
    '''Take an integer from user and return it.
    Args:
        message: The message to show to the user before entering the integer.
    '''
    # Create a string which represents Python code
    let pythonCode = "int(input('" + message + "'))"
    # Create a StringRef, in the next line of code, 
    # the Python.evaluate() function requires a StringRef
    let pythonCodeStringRef = StringRef(pythonCode)
    # Cast the string to integer. 
    # An exception will occurs if the value is not a valid integer
    let number = Python.evaluate(pythonCodeStringRef).to_float64().to_int()
    return number

fn main() raises:
    let n = inputInteger('Please enter an integer: ')
    print(n)

# Output
Please enter an integer: 2024
2024

It is obvious that those implementations are just workarounds for now, I hope that Mojo will support the input function in the future.

Happy coding!

Tagged : / / / /
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x