Creado con canva
ESP
Ya aprendimos a hacer a nuestra computadora mostrarnos mensajes a preguntar al usuario cuando necesite alguna información, a recordar cosas con las variables, e incluso a realizar operaciones sencillas. Sin embargo, nuestras aplicaciones actuales son un poco planas, son aplicaciones que sirven para hacer una cosa pequeña y culminar de forma breve.
¿Y si te digo que podemos aprender a como decirle a nuestra computadora que tome decisiones por nosotros? Eso es posible, gracias a las estructuras de control de flujo.
Ya sabemos que tal y como los algoritmos nuestros programas se van ejecutando de arriba a abajo, empezando por la linea 1 hasta la ultima linea del código. Las estructuras de control de flujo nos ayudarán a modificar el flujo de nuestro programa, tal y como su nombre sugiere, permitiendo que hagamos programas capaces de tomar decisiones y ejecutar una parte del código u otra de acuerdo a nuestras necesidades. No te preocupes, esto lo veremos con ejemplos un poco mas adelante.
Imaginemos que queremos hacer un algoritmo para ir a pasear, pero no sabemos como estará el clima hoy. Entonces el plan puede ser ir al parque si no va a llover, o ir al cine si lloverá, con las estructuras de control podemos, por ejemplo, hacer un algoritmo donde primero chequeemos como estará el clima, y poder decidir hacer una cosa u otra dependiendo de los resultados de nuestra consulta.
Estructuras condicionales
Con las estructuras condicionales como su nombre lo dice permite a nuestros programas evaluar condiciones y actuar de acuerdo a su resultado. Podemos hacer que nuestro programa haga una cosa u otra de acuerdo a los resultados de una operación lógica, las cuales vimos en la lección anterior.
Vamos a declarar una variable llamada weather de tipo caracter donde preguntaremos al usuario como está el clima.
Definir weather Como Caracter;
// 1- Preguntar como estara el clima esta tarde
Imprimir "Como estara el clima esta tarde? (soleado/nublado)";
Leer weather;
El usuario deberá responder si está soleado o nublado. Para escribir un condicional empezaremos nuestra instrucción con la palabra Si, después entre paréntesis haremos una operación lógica y después la palabra Entonces. Dos lineas mas abajo colocaremos FinSi para indicar que nuestra evaluación ha culminado. En este caso vamos a evaluar que nos dijo el usuario, es decir vamos a ver si en la variable weather tiene el valor de “soleado”.
// 2- Evaluar la respuesta
Si (weather == "soleado") Entonces
Imprimir "Podrias ir al parque";
FinSi
Todo lo que esté dentro del sí lo colocaremos con un nivel de indentación, lo cual indicará que todo lo que esté allí dentro se ejecutará si se cumple esa condición. Básicamente con el operador == estamos preguntando si la variable contiene ese valor de forma exacta, si el resultado de esa operación lógica es verdadero entonces todo lo que esté dentro del sí se ejecutará.
Ya evaluamos qué pasará si el clima está soleado, ahora necesitamos una manera de evaluar qué pasará si el clima está nublado. Podríamos hacer un condicional nuevo para cada caso, pero eso no es muy eficiente. En este caso dentro de la misma estructura podemos colocar Sino Y en la línea siguiente con otro nivel de orientación colocar lo que pasará si no se cumple la primera condición.
Si (weather == "soleado") Entonces
Imprimir "Podrias ir al parque";
Sino
Imprimir "Podrias ir al cine";
FinSi
Si la primera condición se cumple entonces se ejecutará lo que está dentro del primer sí, y si no se cumple se ejecutará lo que está dentro del sino y se ignorará completamente la instrucción que está en el sí. Veamos este programa en ejecución:
En esta ejecución le dijimos al programa que estará soleado, y me mostró el mensaje de qué podría ir al parque. Ahora vamos a volver a ejecutarlo y le vamos a decir que está nublado.
Cómo pueden observar ahora el mensaje es distinto ya que se ejecutó la instrucción contraria ya que no se cumplió la primera condición.
Condicionales anidados
A partir de aquí la cosa se puede complicar tanto como sea necesario, es posible incluir más estructuras condicionales dentro de otras estructuras condicionales y lograr así crear programas bastante complejos que puedan tomar decisiones de forma impresionante. De hecho se presume que las inteligencias artificiales generativas modernas funcionan de esta manera, con un montón de estructuras condicionales evaluando infinitamente las preguntas que los usuarios les hacen.
Vamos a realizar un programa que pregunte la edad de el usuario, si el usuario tiene más de 18 años entonces vamos a preguntarle cuál es su estado civil, si es una persona soltera entonces le diremos que el programa no está disponible y si es una persona casada le daremos un mensaje de bienvenida. Si el usuario tiene menos de 18 años entonces calcularemos cuántos años le faltan para ser mayor de edad y se lo diremos en un mensaje.
Ese programa puede parecer complejo, porque es algo más largo de lo usual, sin embargo utilizaremos muchas cosas que hemos visto a lo largo de todas las lecciones.
Primero vamos a definir todas las variables que vamos a utilizar, finalizamos el programa podemos deducir que estas son: nombre, estado_civil, edad y diferencia, esta última será una variable para calcular la diferencia que hay entre 18 y la edad del usuario si es menor a 18.
Después vamos a pedir los datos, que en este caso primero sería nombre y la edad.
// 1- Definir las variables a utilizar
Definir nombre,estado_civil Como Caracter;
Definir edad, diferencia Como Entero;
// 2- Preguntar nombre y edad del usuario
Imprimir "Introduzca su nombre:";
Leer nombre;
Imprimir "Introduzca su edad:";
Leer edad;
Ahora viene lo divertido, vamos a crear un condicional que evalúe si la edad introducida es mayor o igual que 18.
// 3- Evaluar la edad
Si (edad >= 18) Entonces
// Si en mayor esto pasará
Sino
// Si es menor de edad, ejecutaremos esta parte
FinSi
Ya que la primera estructura condicional definida vamos a ver qué tenemos que hacer en cada caso. Si el usuario es mayor de edad entonces vamos a preguntarles por su estado civil, y después de recoger esta información vamos a evaluar si el usuario es soltero o casado. En caso de ser soltero le diremos que el programa no está disponible, Y si no le daremos un mensaje de bienvenida personalizado.
Si (edad >= 18) Entonces
Imprimir nombre " Introduce tu estado civil (soltero/casado)";
Leer estado_civil;
Si (estado_civil == "soltero") Entonces
Imprimir "Lo siento, debes estar casado para usar este programa.";
SiNo
Imprimir "Bienvenido/a " nombre ", puedes unirte!";
FinSi
Sino
FinSi
Para que no te pierdas básicamente si la condición de qué es mayor de edad es verdadera vamos a pedir su estado civil y vamos a crear otra estructura condicional dentro de esa misma parte que evaluará si el usuario ha dicho que es soltero o casado y lo mostrará el mensaje adecuado con respecto a su situación actual.
Ahora tenemos que realizar la acción que el programa va a ejecutar en caso de qué el usuario sea menor de edad. Habíamos dicho que calcularíamos cuantos años le faltan para ser mayor y se lo diríamos en un mensaje. Entonces en la variable diferencia vamos a restar 18 con la edad de el usuario. Después le diremos que la diferencia es la cantidad de años que le faltan para ser mayor de edad.
Si (edad >= 18) Entonces
Imprimir nombre " Introduce tu estado civil (soltero/casado)";
Leer estado_civil;
Si (estado_civil == "soltero") Entonces
Imprimir "Lo siento, debes estar casado para usar este programa.";
SiNo
Imprimir "Bienvenido/a " nombre ", puedes unirte!";
FinSi
Sino
diferencia = 18-edad;
Imprimir "Te faltan " diferencia " anios para usar este programa.";
FinSi
Para probar este programa vamos a realizar tres ejecuciones, primero vamos a decirle que tenemos 18 años y que estamos solteros.
Después vamos a decirle que tenemos 12 años.
Finalmente le diremos que tenemos 23 y que estamos casados.
Cómo podemos observar el programa reacciona de forma distinta dependiendo de la información que le proporcionemos. A partir de aquí nuestra creatividad será el límite para resolver problemas cada vez más complejos.
Tarea
- Describe tu comprensión sobre las estructuras condicionales y menciona 2 situaciones de la vida cotidiana donde podrías aplicar este concepto.
- Crea un programa que le diga al usuario “Bienvenido a la habitación Que deseas hacer?”, si el usuario escribe 1 entonces muestra un mensaje que diga “has encendido la luz”, si el usuario escribe 2 entonces muestra un mensaje que diga “has dejado la habitación”. Utiliza condicionales.
- Crea un programa que pida al usuario 4 calificaciones distintas, calcula el promedio y si este es mayor a 70 muestra un mensaje diciendo que la sección aprobó, si no, muestra un mensaje diciendo que la sección puede mejorar.
Las primeras 2 preguntas tendrán un valor de 3 puntos, y la última 4 puntos.
Normas
- El contenido debe ser #steemexclusive.
- El artículo debe contener la etiqueta #devjr-s20w4.
- El plagio no está permitido.
- El link de tu tarea debe ser agregado en los comentarios de esta publicación.
- El curso estará abierto durante 7 días a partir de las 00:00 UTC del 30 de Septiembre. Después de la fecha limite los usuarios podrán seguir participando sin optar a premios con el objetivo de permitir a mas personas en el tiempo de aprovechar este contenido.
ENG
We have already learned how to make our computer show us messages to ask the user when they need some information, to remember things with the variables, and even to perform simple operations. However, our current applications are a bit flat, they are applications that serve to do a small thing and culminate briefly.
What if I tell you that we can learn how to tell our computer to make decisions for us? That is possible, thanks to the flow control structures.
We already know that just like the algorithms, our programs run from top to bottom, starting with line 1 to the last line of the code. Flow control structures will help us modify the flow of our program, as its name suggests, allowing us to make programs capable of making decisions and executing one part of the code or another according to our needs. Don't worry, we'll see this with examples a little later.
Let's imagine that we want to make an algorithm to go for a walk, but we don't know what the weather will be like today. So the plan can be to go to the park if it's not going to rain, or go to the movies if it's raining, with the control structures we can, for example, make an algorithm where we first check how the weather will be, and be able to decide to do one thing or another depending on the results of our consultation.
Conditional structures
With the conditional structures as the name says, it allows our programs to evaluate conditions and act according to their result. We can make our program do one thing or another according to the results of a logical operation, which we saw in the previous lesson.
We are going to declare a variable called weather of character type where we will ask the user how the weather is.
Define weather as Character;
// 1- Ask how the weather will be this afternoon
Print "How will the weather be this afternoon? (sunny/cloudy)";
Read weather;
The user must respond if it is sunny or cloudy. To write a conditional we will start our instruction with the word If, then in parentheses we will make a logical operation and then the word Then. Two lines below we will place EndIf to indicate that our evaluation has been completed. In this case we are going to evaluate what the user told us, that is, we are going to see if in the weather variable it has the value of "sunny".
// 2- Evaluate the answer
If (weather == "sunny") Then
Print "You could go to the park";
EndIf
Everything that is inside the yes will be placed with a level of indentation, which will indicate that everything that is in there will be executed if that condition is met. Basically with the operator == we are asking if the variable contains that value exactly, if the result of that logical operation is true then everything inside the yes will be executed.
We have already evaluated what will happen if the weather is sunny, now we need a way to evaluate what will happen if the weather is cloudy. We could make a new conditional for each case, but that is not very efficient. In this case within the same structure we can place else And in the next line with another level of orientation place what will happen if the first condition is not met.
Yes (weather == "sunny") Then
Print "You could go to the park";
else
Print "You could go to the movies";
EndIf
If the first condition is met then what is inside the first yes will be executed, and if it is not met what is inside the else will be executed and the instruction that is in the yes will be completely ignored. Let's see this running program:
In this execution we told the program that it will be sunny, and it showed me the message of what I could go to the park. Now we are going to run it again and we are going to tell him that it is cloudy.
As you can see now, the message is different since the opposite instruction was executed since the first condition was not met.
Nested conditionals
From here the thing can be complicated as much as necessary, it is possible to include more conditional structures within other conditional structures and thus create quite complex programs that can make decisions in an impressive way. In fact, it is assumed that modern generative artificial intelligences work in this way, with a lot of conditional structures infinitely evaluating the questions that users ask them.
We are going to make a program that asks the age of the user, if the user is over 18 years old then we will ask him what his marital status is, if he is a single person then we will tell him that the program is not available and if he is a married person we will give him a welcome message. If the user is under 18 years old then we will calculate how many years he has left to be of age and we will tell him in a message.
That program may seem complex, because it is somewhat longer than usual, however we will use many things that we have seen throughout all the lessons.
First we are going to define all the variables that we are going to use, we finish the program we can deduce that these are: name, marital_status, age and difference, the latter will be a variable to calculate the difference between 18 and the age of the user if it is less than 18.
Then we are going to ask for the data, which in this case would first be name and age.
// 1- Define the variables to use
Define name, marital_status as a character;
Define age, difference As Integer;
// 2- Ask for the user's name and age
Print "Enter your name:";
Read name;
Print "Enter your age:";
Read age;
Now comes the fun, we are going to create a conditional that evaluates whether the age entered is greater than or equal to 18.
If (age >= 18) Then
else
EndIf
Since the first conditional structure defined, let's see what we have to do in each case. If the user is of legal age then we will ask them about their marital status, and after collecting this information we will evaluate whether the user is single or married. If you are single we will tell you that the program is not available, and if not we will give you a personalized welcome message.
If (age >= 18) Then
Print name "Enter your marital status (single/married)";
Read marital_status;
If (marital_status == "single") Then
Print "I'm sorry, you must be married to use this program." ;
else
Print "Welcome "name", you can join!" ;
EndIf
else
EndIf
So that you do not lose basically if the condition of what is of legal age is true we are going to ask for your marital status and we are going to create another conditional structure within that same part that will evaluate if the user has said that he is single or married and will show the appropriate message regarding his current situation.
Now we have to perform the action that the program is going to execute in case the user is a minor. We had said that we would calculate how many years he has left to be older and we would tell him in a message. So in the difference variable we are going to subtract 18 with the age of the user. Then we will tell you that the difference is the number of years you have left to be of legal age.
If (age >= 18) Then
Print name "Enter your marital status (single/married)";
Read marital_status;
If (marital_status == "single") Then
Print "I'm sorry, you must be married to use this program." ;
else
Print "Welcome "name", you can join!" ;
EndIf
else
difference = 18-age;
Print "You are missing " difference " years to use this program." ;
EndIf
To try this program we are going to perform three executions, first we are going to tell you that we are 18 years old and that we are single.
Then we're going to tell him that we are 12 years old.
Finally we will tell him that we are 23 and that we are married.
As we can see, the program reacts differently depending on the information we provide. From here our creativity will be the limit to solving increasingly complex problems.
Homework
- Describe your understanding of conditional structures and mention 2 situations of everyday life where you could apply this concept.
- Create a program that tells the user "Welcome to the room What do you want to do?", if the user writes 1 then it shows a message that says "you have turned on the light", if the user writes 2 then it shows a message that says "you have left the room". Use conditionals.
- Create a program that asks the user for 4 different ratings, calculate the average and if it is greater than 70 it shows a message saying that the section passed, if not, it shows a message saying that the section can improve.
**The first 2 questions will have a value of 3 points, and the last 4 points. **
Rules
- The content must be #steemexclusive.
- The article must contain the tag #devjr-s20w4.
- Plagiarism is not allowed.
- The link of your task must be added in the comments of this publication.
- The course will be open for 7 days from 00:00 UTC on September 30. After the deadline, users will be able to continue participating without applying for prizes with the aim of allowing more people in time to take advantage of this content.
Pls what programming language did you use sir @alejos7ven
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Your post has been rewarded by the Seven Team.
Support partner witnesses
We are the hope!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Hi @alejos7ven,
my name is @ilnegro and I voted your post using steem-fanbase.com.
Come and visit Italy Community
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
I love it!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Here is my entry:
https://steemit.com/devjr-s20w4/@ahsansharif/basic-programming-course-lesson-4-control-structures-part-1-conditionals
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
This is my entry link:
https://steemit.com/hive-117276/@mahadisalim/basic-programming-course-lesson-4-control-structures-part-1-conditionals
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
My entry.
https://steemit.com/devjr-s20w4/@josepha/basic-programming-course-lesson-4-control-structures-part-1
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Check out my entry: The Importance of Conditional Structures in Programming. Also, the post is shared on Twitter: Twitter Link.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
My entry: https://steemit.com/devjr-s20w4/@jyoti-thelight/basic-programming-course-lesson-4-control-structures-part-1-conditionals
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Here is my entry: https://steemit.com/devjr-s20w4/@mohammadfaisal/basic-programming-course-lesson-4-control-structures-part-1
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
https://steemit.com/hive-145157/@sergeyk/basic-programming-course-lesson-4
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
This post has been upvoted by @italygame witness curation trail
If you like our work and want to support us, please consider to approve our witness
Come and visit Italy Community
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
My entry link
https://steemit.com/devjr-s20w4/@nsijoro/basic-programming-course-lesson-4
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
https://steemit.com/hive-195150/@fombae/basic-programming-course-lesson-4-control-structures-part-1-conditionals
My entry
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Hello
Here is my entry:
https://steemit.com/devjr-s20w4/@ady-was-here/basic-programming-course-lesson-4-control-structures-part-1-conditionals
Thank you.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Mi entrada:
https://steemit.com/devjr-s20w4/@damisvilladiego/basic-programming-course-lesson-4-control-structures-part-1
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
https://steemit.com/devwithseven/@graceleon/basic-programming-course-lesson-4-control-structures-part-1-conditionals
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
My entry
https://steemit.com/devjr-s20w4/@daprado1999/basic-programming-course-lesson-4-control-structures-part-1
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
https://steemit.com/devjr-s20w4/@simonnwigwe/basic-programming-course-lesson-4-control-structures-part-1
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
My entry : https://steemit.com/devjr-s20w4/@walictd/basic-programming-course-lesson-4-control-structures-part-1-conditionals
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
My entry.
https://steemit.com/hive-103393/@aneukpineung78/sec-s20w4-or-or-basic-programming-course-lesson-4-control-structures-part-1-conditionals
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
HERE IS MY PARTICIPATION
https://steemit.com/devjr-s20w4/@arinaz08/basic-programming-course-lesson-4-control-structures-part-1-conditionals
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit