Explore compiled Mojo basics after learning general programming concepts.

Before starting: Understand variables, functions and a command-line compiler.

Practice project: Extend the examples into a small Mojo study demo. Explain the setup, one normal case and one failure or boundary case.

Start here: concepts and guided practice

  1. Mojo: typed values and arithmetic

    Mojo is a compiled language with Python-like indentation. A typed variable stores a value of a specified type. Here the result is an integer; similar-looking Python code does not make the two languages interchangeable.

    Mojo toolchain matching the linked manual (1.0.0b2 syntax). Save as study.mojo and run mojo study.mojo. This evolving language is not the recommended first language.

    def main():
        var lessons: Int = 4
        var minutes: Int = 15
        print(lessons * minutes)
    Check the output
    60

    Change lessons to 0 and predict the result.

  2. Mojo: choose a branch

    An if statement chooses a block according to a condition. Indentation marks the block. Test both sides of the threshold, including the exact boundary.

    Mojo toolchain matching the linked manual (1.0.0b2 syntax). Save as study.mojo and run mojo study.mojo. This evolving language is not the recommended first language.

    def main():
        var score: Int = 70
        if score >= 60:
            print("Pass")
        else:
            print("Practice")
    Check the output
    Pass

    Try 59, 60 and 61; explain each output.

  3. Mojo: return a calculated value

    A function can accept a typed input and return a typed result. A return statement gives the caller a value; it does not display it.

    Mojo toolchain matching the linked manual (1.0.0b2 syntax). Save as study.mojo and run mojo study.mojo. This evolving language is not the recommended first language.

    def doubled(value: Int) -> Int:
        return value * 2
    
    def main():
        print(doubled(9))
    Check the output
    18

    Call doubled with 0 and -3.

Open the Mojo learning path on DevStudyHub · Play coding games on this blog

logoblog

No comments:

Post a Comment

Please do not enter any spam link in the comment box.