Notebook

Tabla de Contenido

 

L 1.2.2 — Casting y Activity 1

Programación con Python I — Fundamentos · Módulo 1 · Unidad 1.2


Casting es convertir un valor de un tipo a otro de forma explícita. Ya vimos int() y float() en L 1.1.3 aplicados a valores literales. Aquí los usamos con variables.

Al final completamos la, Activity 1 del libro — el primer ejercicio que combina variables, operaciones y tipos.


Tipado dinámico: el tipo sigue al valor

Sigue la secuencia exacta del libro. Predice el resultado de cada celda antes de ejecutarla.

y pasó de int a float con solo asignarle un valor diferente. El tipo cambió automáticamente — no tuviste que indicárselo a Python.


Casting explícito: int() y float()

El casting te da control sobre el tipo — no tienes que esperar que Python lo deduzca. Usamos int() para convertir y de vuelta a entero.

Recuerda: int() trunca, no redondea.

(1, 1.0)

 

int(1.0) da 1 — el decimal .0 se descarta. El tipo ahora es int.

Nota: el casting no modifica la variable original. int(x) convierte temporalmente. Para que el cambio persista hay que asignarlo: x = int(x) o, como hicimos aquí, x_entero = int(x).

La dirección contraria — int a float — también funciona:


Actividad 1 — Primer programa integrador

Enunciado: 1. Asigna el número 14 a la variable w 2. Súmale 1 a w, 3. Finalmente divíde w entre 5 y eleva el resultado al cuadrado.

Muestra el resultado final.


Antes de ejecutar — predice el tipo del resultado final:

  • 14 → int

  • 14 + 1 = 15 → int

  • 15 / 5 = 3.0 → float (la división / siempre da float)

  • 3.0 ** 2 = 9.0 → float

Resultado esperado: 9.0

Ahora síguela paso a paso:

(int, int)


Actividad 1 — Primer programa integrador

Enunciado: 1. Asigna el número 14 a la variable w 2. Súmale 1 a w, 3. Finalmente divíde w entre 5 y eleva el resultado al cuadrado.

Muestra el resultado final.


Antes de ejecutar — predice el tipo del resultado final:

  • 14 → int

  • 14 + 1 = 15 → int

  • 15 / 5 = 3.0 → float (la división / siempre da float)

  • 3.0 ** 2 = 9.0 → float

Resultado esperado: 9.0

Ahora síguela paso a paso: 9.0 — exactamente lo que predijimos.


¿Y si quisiéramos un entero?

Aplicaríamos int() al resultado final: ¡Ahí está el cambio! 15 / 5 = 3.0 — int se convirtió en float. La barra simple / siempre devuelve float, como vimos en L 1.1.1. 9.0 — exactamente lo que predijimos.


¿Y si quisiéramos un entero?

Aplicaríamos int() al resultado final:

9 — sin el .0. El casting explícito nos da control sobre el tipo del resultado.


Resumen

ConceptoEjemploResultado
Tipado dinámicoy = 1 luego y = 1.0y cambia de int a float
Casting a intint(1.0)1 (trunca, no redondea)
Casting a floatfloat(5)5.0
Activity 114 → +1 → /5 → **29.0 (float)

→ Siguiente lección: L 1.2.3 — Nombres de variables y variables múltiples

¿Qué nombres puede tener una variable en Python? ¿Y cuáles están prohibidos? 3. Change x to 3.0, set x equal to x+1, and check the value of x:

The output is as follows: 4.0 In this step, we changed the value of x by setting x equal to x+1. This is permissible in Python because of the right to left order in variable assignment. On the right-hand side, x+1 has a value of 4.0; this value may be assigned to any variable, including x. By the end of this exercise, you may have noticed that, in programming, you can assign a variable in terms of its previous value. This is a powerful tool, and many developers use it quite often. Furthermore, the type of x changed. x started as an int, but later became a float. This is allowed in Python because Python is dynamically typed.