Top Banner
01/04/20 Ing. Roberto Martínez Román - [email protected] 1 TOMANDO DECISIONES La instrucción if Ing. Roberto Martínez Román - [email protected] 1 Las estructuras de control Ing. Roberto Martínez Román - [email protected] ¨ Las estructuras de control se utilizan para definir la secuencia de ejecución de las instrucciones. Hay 3 estructuras: ¤ Secuencia. Hacer una instrucción después de la otra. ¤ Selección . Ejecutar, o no. instrucciones dependiendo de si se cumple, o no, una condición. ¤ Iteración (ciclos). Ejecutar de manera repetitiva instrucciones. 2
15

TOMANDO DECISIONES · 2020. 4. 2. · TOMANDO DECISIONES La instrucción if Ing. Roberto Martínez Román [email protected] 1 Las estructuras de control Ing. Roberto Martínez Román

Aug 15, 2021

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: TOMANDO DECISIONES · 2020. 4. 2. · TOMANDO DECISIONES La instrucción if Ing. Roberto Martínez Román -rmroman@itesm.mx 1 Las estructuras de control Ing. Roberto Martínez Román

01/04/20

Ing. Roberto Martínez Román [email protected] 1

TOMANDO DECISIONESLa instrucción if

Ing. Roberto Martínez Román - [email protected]

1

Las estructuras de control

Ing. Roberto Martínez Román - [email protected]

¨ Las estructuras de control se utilizan para definir la secuencia de ejecución de las instrucciones. Hay 3 estructuras:¤ Secuencia. Hacer una instrucción después de la otra.

¤Selección. Ejecutar, o no. instrucciones dependiendo de si se cumple, o no, una condición.

¤ Iteración (ciclos). Ejecutar de manera repetitiva instrucciones.

2

Page 2: TOMANDO DECISIONES · 2020. 4. 2. · TOMANDO DECISIONES La instrucción if Ing. Roberto Martínez Román -rmroman@itesm.mx 1 Las estructuras de control Ing. Roberto Martínez Román

01/04/20

Ing. Roberto Martínez Román [email protected] 2

Selección simple

Ing. Roberto Martínez Román - [email protected]

¨ Esta estructura permite ejecutar o no, un conjunto de instrucciones dependiendo del resultado de una condición.

Condición

Instrucciones

3

Selección simple en Python

Ing. Roberto Martínez Román - [email protected]

¨ Esta estructura ejecuta las instrucciones SOLO cuando la condición evaluada es cierta.

¨ La sintaxis es:

if condición:

instrucciones

Verdadero

Falso

4

Page 3: TOMANDO DECISIONES · 2020. 4. 2. · TOMANDO DECISIONES La instrucción if Ing. Roberto Martínez Román -rmroman@itesm.mx 1 Las estructuras de control Ing. Roberto Martínez Román

01/04/20

Ing. Roberto Martínez Román [email protected] 3

Operadores relacionales

Ing. Roberto Martínez Román - [email protected]

Operador Significado

< Menor que

> Mayor que

<= Menor o igual que

>= Mayor o igual que

== Igual a

!= Diferente de

5

Ejemplo

Ing. Roberto Martínez Román - [email protected]

¨ Escribe un programa que lee un valor entero. Imprime el doble del número y, si el doble es mayor que 70, imprime "Número afortunado".

6

Page 4: TOMANDO DECISIONES · 2020. 4. 2. · TOMANDO DECISIONES La instrucción if Ing. Roberto Martínez Román -rmroman@itesm.mx 1 Las estructuras de control Ing. Roberto Martínez Román

01/04/20

Ing. Roberto Martínez Román [email protected] 4

Selección doble

Ing. Roberto Martínez Román - [email protected]

¨ Esta estructura permite ejecutar uno de dos caminos dependiendo del resultado de una condición.

Condición

instrucciones_A instrucciones_B

7

Selección doble en Python

Ing. Roberto Martínez Román - [email protected]

¨ Esta estructura permite ejecutar un conjunto de instrucciones cuando la condición evaluada es cierta y otro conjunto cuando es falsa.

¨ La sintaxis es:

if condición:instrucciones_A

else:instrucciones_B

Verdadero

Falso

8

Page 5: TOMANDO DECISIONES · 2020. 4. 2. · TOMANDO DECISIONES La instrucción if Ing. Roberto Martínez Román -rmroman@itesm.mx 1 Las estructuras de control Ing. Roberto Martínez Román

01/04/20

Ing. Roberto Martínez Román [email protected] 5

Ejemplo

Ing. Roberto Martínez Román - [email protected]

¨ Escribe un programa que lee la carrera de un alumno (LAD, LCMD). Si la carrera es LAD imprimes el mensaje "Estás en el salón correcto"; si es LCMD imprimes el mensaje "Estás en el salón correcto". Si no es ninguno de los dos, imprimes el mensaje "Estás en el salón incorrecto"

9

Operadores relacionales

Ing. Roberto Martínez Román - [email protected]

Operador Significado

< Menor que

> Mayor que

<= Menor o igual que

>= Mayor o igual que

== Igual a

!= Diferente de

10

Page 6: TOMANDO DECISIONES · 2020. 4. 2. · TOMANDO DECISIONES La instrucción if Ing. Roberto Martínez Román -rmroman@itesm.mx 1 Las estructuras de control Ing. Roberto Martínez Román

01/04/20

Ing. Roberto Martínez Román [email protected] 6

Ejercicio

Ing. Roberto Martínez Román - [email protected]

Escribe un programa con funciones que haga lo siguiente:¨ Carga una imagen desde el disco.¨ Clasifica la imagen en uno de dos tipos:

¤ Portrait.¤ Landscape.

¨ Clasifica la imagen en una de 3 categorías:¤ Pequeña. Número de pixeles menor o igual a 16,000.¤ Mediana. Número de pixeles mayor a 16,000 pero, menor

a 300,000.¤ Grande. Número de pixeles mayor o igual a 300,000.

11

Operadores lógicos

Ing. Roberto Martínez Román - [email protected]

Operador Significado

and Y lógico, conjunción

or O lógico, disyunción

not NO lógico, negación

12

Page 7: TOMANDO DECISIONES · 2020. 4. 2. · TOMANDO DECISIONES La instrucción if Ing. Roberto Martínez Román -rmroman@itesm.mx 1 Las estructuras de control Ing. Roberto Martínez Román

01/04/20

Ing. Roberto Martínez Román [email protected] 7

Tablas de verdad

Ing. Roberto Martínez Román - [email protected]

a b a and b a or b not a

True True

True False

False True

False False

a b a and b a or b not a

True True True True False

True False False True

False True False True True

False False False False

13

Ejemplos

Ing. Roberto Martínez Román - [email protected]

54 > 22*3 < 5+13-2 == 5/52 > 223%5 != 13%5

a>=70 and a<=100a<70 and a>=05>7 or 7!=10x>=18not (x < 18)

14

Page 8: TOMANDO DECISIONES · 2020. 4. 2. · TOMANDO DECISIONES La instrucción if Ing. Roberto Martínez Román -rmroman@itesm.mx 1 Las estructuras de control Ing. Roberto Martínez Román

01/04/20

Ing. Roberto Martínez Román [email protected] 8

If's anidados

Ing. Roberto Martínez Román - [email protected]

¨ Esto ocurre cuando nuestra lógica necesita que haya una estructura if dentro de un if o un else.

15

Ejercicios con if

Ing. Roberto Martínez Román - [email protected]

¨ Dibuja un diagrama de flujo para resolver cada uno de los siguientes problemas:¤ Leer dos números enteros e imprimir el mayor. ¤ Leer tres números enteros e imprime el mayor.¤ Leer cuatro números enteros e imprime el mayor.

16

Page 9: TOMANDO DECISIONES · 2020. 4. 2. · TOMANDO DECISIONES La instrucción if Ing. Roberto Martínez Román -rmroman@itesm.mx 1 Las estructuras de control Ing. Roberto Martínez Román

01/04/20

Ing. Roberto Martínez Román [email protected] 9

Ejercicios con if

Ing. Roberto Martínez Román - [email protected]

¨ Usa funciones para resolver los siguientes problemas:¤ Escribe un programa que lee dos números enteros e

imprime el mayor. ¤ Escribe un programa que lee tres números enteros e

imprime el mayor.¤ Escribe un programa que lee cuatro números enteros

e imprime el mayor.

17

Ejercicios

Ing. Roberto Martínez Román - [email protected]

¨ Escribe una función que valide si una calificación es correcta. Regresa True si es correcta, False en otro caso. Es correcta si se encuentra en el rango [0, 100].

¨ Escribe una función que valide si una calificación es aprobatoria. Es aprobatoria si está en [70, 100]

¨ Escribe una función que recibe como parámetro una calificación entera. Regresa una cadena indicando: "Reprobado", "Aprobado" o "Error".

18

Page 10: TOMANDO DECISIONES · 2020. 4. 2. · TOMANDO DECISIONES La instrucción if Ing. Roberto Martínez Román -rmroman@itesm.mx 1 Las estructuras de control Ing. Roberto Martínez Román

01/04/20

Ing. Roberto Martínez Román [email protected] 10

Ejercicios con if y funciones

Ing. Roberto Martínez Román - [email protected]

¨ Escribe una función que recibe un valor entero y regresa True si es par, False en otro caso.

¨ Escribe una función que recibe tres parámetros que representan los lados de un triángulo. Regresa True si es un triángulo rectángulo, False en otro caso.

¨ Escribe un programa que usa una función para resolver la ecuación de segundo grado. Si hay raíces reales las calcula y las imprime; si no, calcula e imprime las raíces complejas. La función recibe los tres coeficientes como parámetros.

19

Ejercicios

Ing. Roberto Martínez Román - [email protected]

¨ Una empresa que se dedica a ofrecer banquetes para fiestas tiene los siguientes precios:

¨ Escribe una función que recibe el número de personas y regresa el costo total del banquete.¤ Elabora, al menos, dos algoritmos para resolver el

problema.

Número de personas Precio por persona

Menor a 50 190

De 50 a 85 155

De 86 en adelante 137

20

Page 11: TOMANDO DECISIONES · 2020. 4. 2. · TOMANDO DECISIONES La instrucción if Ing. Roberto Martínez Román -rmroman@itesm.mx 1 Las estructuras de control Ing. Roberto Martínez Román

01/04/20

Ing. Roberto Martínez Román [email protected] 11

If's anidados

Ing. Roberto Martínez Román - [email protected]

¨ Esto ocurre cuando nuestra lógica necesita que haya una estructura if dentro de un if o un else.

21

Ejercicio

Ing. Roberto Martínez Román - [email protected]

¨ Codifica en Python la siguiente estructura.

condA

condEcondD

condCcondB

InstrucA

InstrucB InstrucC InstrucD

InstrucE

22

Page 12: TOMANDO DECISIONES · 2020. 4. 2. · TOMANDO DECISIONES La instrucción if Ing. Roberto Martínez Román -rmroman@itesm.mx 1 Las estructuras de control Ing. Roberto Martínez Román

01/04/20

Ing. Roberto Martínez Román [email protected] 12

Tipos de if

Ing. Roberto Martínez Román - [email protected]

Simpleif condición :

Instrucciones

Dobleif condición :

Instruccioneselse :

Instrucciones

23

Tipos de if

Ing. Roberto Martínez Román - [email protected]

Múltipleif condicionA :

InstrAelif condicionB :

InstrBelif condicionC :

InstrCelif condicionD :

InstrDelse :

InstrX

A

B

C

D

InstrA

InstrB

InstrC

InstrD InstrX

24

Page 13: TOMANDO DECISIONES · 2020. 4. 2. · TOMANDO DECISIONES La instrucción if Ing. Roberto Martínez Román -rmroman@itesm.mx 1 Las estructuras de control Ing. Roberto Martínez Román

01/04/20

Ing. Roberto Martínez Román [email protected] 13

Ejercicio

Ing. Roberto Martínez Román - [email protected]

¨ Escribe un programa que pide el número de día (0-6) e imprime el nombre del día de la semana.

¨ 0-Domingo¨ 1-lunes¨ …¨ 6-sábado

25

Práctica en parejas

Ing. Roberto Martínez Román - [email protected]

¨ Venta de canciones.¤ Una compañía vende canciones a $17.50, se aplica un descuento de

acuerdo al número de canciones descargadas por sesión. ¤ Escribe un programa que pregunta el número de canciones descargadas

y calcula e imprime la cantidad a pagar. Si el usuario teclea un valor negativo o cero, el programa imprime un mensaje de error y termina.

Cantidad Descuento

1-5 10%

6 - 10 18%

11 – 20 38%

Más de 20 50%

¿Qué sale más barato, comprar 20 canciones o comprar 22?, el programa debe calcular e imprimir la respuesta.

OBLIGATORIOUsar funciones

Asunto: Ejercicio canciones, grupo 02

26

Page 14: TOMANDO DECISIONES · 2020. 4. 2. · TOMANDO DECISIONES La instrucción if Ing. Roberto Martínez Román -rmroman@itesm.mx 1 Las estructuras de control Ing. Roberto Martínez Román

01/04/20

Ing. Roberto Martínez Román [email protected] 14

Práctica en parejas

Ing. Roberto Martínez Román - [email protected]

¿Sabes en qué día de la semana naciste?Escribe un programa que pregunta al usuario su fecha de nacimiento (día, mes, año) y que imprima el día de la semana que corresponda a esa fecha. TODAS LAS DIVISIONES SON ENTERAS.

27

28

Page 15: TOMANDO DECISIONES · 2020. 4. 2. · TOMANDO DECISIONES La instrucción if Ing. Roberto Martínez Román -rmroman@itesm.mx 1 Las estructuras de control Ing. Roberto Martínez Román

01/04/20

Ing. Roberto Martínez Román [email protected] 15

Ejercicio en parejas

Ing. Roberto Martínez Román - [email protected]

If you are given three sticks, you may or may not be able to arrange them in a triangle. For example, if one of the sticks is 12 inches long and the other two are one inch long, it is clear that you will not be able to get the short sticks to meet in the middle. For any three lengths, there is a simple test to see if it is possible to form a triangle:

¤ If any of the three lengths is greater than the sum of the other two, then you cannot form a triangle. Otherwise, you can. (If the sum of two lengths equals the third, they form what is called a “degenerate” triangle.)

¨ Write a function named isTriangle that takes three integers as arguments, and that returns either True or False, depending on whether you can or cannot form a triangle from sticks with the given lengths.

¨ Write a function main that prompts the user to input three stick lengths, converts them to integers, and uses isTriangle to check whether sticks with the given lengths can form a triangle.

¨ CHALLENGE: If triangle exists, draw it. JThink Python.

How to Think Like a Computer ScientistAllen B. Downey

O'Reilly

29