0Pricing
Mojo Academy · Lección

Escribir una función fn

Estric­ta, tipada y centrada en el rendimiento.

Escribir una función fn es una lección gratuita de Mojo Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Mojo Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Mojo Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Meet the fn Keyword

The fn keyword defines a stricter function. It trades some flexibility for safety and the speed Mojo is famous for. ⚡

fn greet():
    print("Hello")

Types Are Required

Every parameter in an fn must declare its type. This lets the compiler check your code and generate fast machine code.

fn add(a: Int, b: Int) -> Int:
    return a + b

Declare the Return Type

An fn states what it returns with an arrow, like -> Int. If it returns something, the type must be spelled out.

fn square(x: Int) -> Int:
    return x * x

No Return Type Means None

Leave off the arrow when an fn returns nothing. It performs an action, like printing, and hands back no value.

fn shout(msg: String):
    print(msg)

Arguments Are Immutable by Default

In an fn, arguments are read-only by default. Trying to reassign one is a compile error, which prevents subtle bugs.

fn show(x: Int):
    print(x)

The Compiler Has Your Back

Because types are known, the compiler catches mismatches before the program runs, turning many runtime crashes into early errors.

Strictness Unlocks Speed

Knowing every type ahead of time lets Mojo skip dynamic checks, so an fn can reach the performance of low-level languages.

Local Variables Need var

Inside an fn, declare new local variables with var. The strict scope rules keep your function predictable.

fn total() -> Int:
    var sum = 0
    sum = sum + 5
    return sum

Errors Must Be Declared

An fn that can fail must say so with raises. Without it, the compiler assumes the function never throws.

fn risky() raises:
    raise Error("nope")

Same Indentation Rules

Like def, an fn uses indentation for its body. The difference is the strictness of types, not the surrounding layout.

fn info():
    print("a")
    print("b")

Built for Hot Paths

Reach for fn in the parts of your program that run millions of times, where every saved nanosecond truly adds up.

Quick Check

Recall the default behavior of fn arguments.

Recap

You met fn: strict, typed, and fast. Types are required, arguments are read-only by default, and the compiler guards correctness. 🎯

Preguntas frecuentes

¿La lección «Escribir una función fn» es gratis?

Sí — el texto completo de «Escribir una función fn» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Mojo Academy, actualiza a CoddyKit PRO. El curso de Mojo Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Escribir una función fn»?

Estric­ta, tipada y centrada en el rendimiento. Practicas Mojo Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Mojo Academy?

No se requiere experiencia previa. Mojo Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «Escribir una función fn»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Mojo Academy?

Sí. Cada lección de Mojo Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Escribir una función def
  2. Escribir una función fn
  3. Cuándo elegir cada una
  4. Tipos de retorno y None
← Volver a Mojo Academy