Mojo user input

how can i take user input in mojo
37 Replies
TeamPuzel
TeamPuzel13mo ago
You could use scanf or python interop for this, I will try show an example
4a6f6e69
4a6f6e6913mo ago
Something I tried and worked looked like this:
from python import Python

fn ask_name() raises -> String:
let user_input = Python.evaluate("input('What is your name? ')").to_string()
return user_input
from python import Python

fn ask_name() raises -> String:
let user_input = Python.evaluate("input('What is your name? ')").to_string()
return user_input
aviral shastri
aviral shastri13mo ago
from python import Python fn ask_name() raises -> String: let user_input = Python.evaluate("input('What is your name? ')").to_string() return user_input fn main(): let a=ask_name() print(a) test.mojo:8:19: error: cannot call function that may raise in a context that cannot raise let a=ask_name() ~~~~^~ test.mojo:8:19: note: try surrounding the call in a 'try' block let a=ask_name() ^ test.mojo:7:1: note: or mark surrounding function as 'raises' fn main(): ^ mojo: error: failed to parse the provided Mojo its giving errors
TeamPuzel
TeamPuzel13mo ago
you must also have fn main() raises:
aviral shastri
aviral shastri13mo ago
from python import Python fn main() raises -> String: let user_input = Python.evaluate("input('What is your name? ')").to_string() print(user_input) test.mojo:3:1: error: expected 'main' function to return 'None' fn main() raises -> String: ^ mojo: error: failed to parse the provided Mojo still errors
TeamPuzel
TeamPuzel13mo ago
Well. fn main() raises:, not fn main() raises -> String:
aviral shastri
aviral shastri13mo ago
lets goo its working thanks
TeamPuzel
TeamPuzel13mo ago
Yay good luck with whatever you're trying to do
aviral shastri
aviral shastri13mo ago
another doubt
ModularBot
ModularBot13mo ago
Congrats @aviral shastri, you just advanced to level 1!
aviral shastri
aviral shastri13mo ago
how can i get integer input or i have to directly use python eval from python import Python fn main() raises: let user_input1= Python.evaluate("input('Num 1')").to_int() let user_input2= Python.evaluate("input('Num 2')").to_int() let add: Int= user_input1 + user_input2 print(add)
TeamPuzel
TeamPuzel13mo ago
You would do it like in python yes
aviral shastri
aviral shastri13mo ago
not working
TeamPuzel
TeamPuzel13mo ago
what's the error?
aviral shastri
aviral shastri13mo ago
test.mojo:6:31: error: cannot implicitly convert 'PythonObject' value to 'Int' in 'let' initializer let add: Int= user_input1 + user_input2 ~~^~~ mojo: error: failed to parse the provided Mojo
Want results from more Discord servers?
Add your server