Basic programming course: Lesson #2 - Variables and Types of Data [ESP-ENG]

in #devwithseven4 days ago

Lesson #2 .jpg

Creado con canva

ESP

Untitled design.png

Las variables


Al momento de programar se hace necesario utilizar datos que vamos recolectando del usuario a medida nuestra aplicación esta funcionando para poder ser reutilizados mas adelante. Para esta tarea llegan a nuestra vida las variables, que son “cajas” de información que nos permiten almacenar datos específicos y poder utilizarlos mas adelante.

Imaginate que eres un profesor y tienes que recopilar los nombres de todos tus alumnos, para ellos pides a cada uno de ellos que te entreguen una caja con un papel por fuera que diga “Nombre”, y dentro de la caja un papel con el nombre escrito del alumno. Algo así funcionan las variables, el nombre de la variable sería “nombre”, y lo que este dentro de la caja sería su valor. Todas las cajas tienen el mismo nombre, pero cada contenido dentro de ellas varia según el alumno.


Tipos de datos


En programación debemos especificar que tipo de información vamos a guardar dentro de las variables, para ello existen 4 tipos de datos fundamentales:

  • Entero: Estas variables almacenan datos de tipo entero, es decir, números positivos o negativos sin decimales (Ej: 23, -4, 0). Por ejemplo: podríamos guardar en una variable de tipo entero edades, número de pisos de un edificio, cantidad de alumnos en una sección, etc.
  • Real: Las variables reales guardan números positivos o negativos con decimales. Te preguntarás ¿Por qué no siempre utilizar una variable real y utilizar una de enteros? La respuesta es por cuestiones de memoria, las variables reales ocupan mas memoria que una de solo enteros, por eso es importante siempre utilizar el tipo de dato correcto para mantener nuestros programas lo mas ligeros posible (Ej: 3.14, 0.15, -5.5). Algunos ejemplos de variables reales son: peso de una persona, altura de una persona, precio del STEEM, precio del BTC, etc.
  • Caracter: Estas variables se usan para guardar texto (Ej: “Eduard”, “Calle 3, casa 5”, “Hombre”), por ejemplo: nombre, dirección, grupo sanguíneo, sexo, etc.
  • Lógica: Las variables lógicas se usan para almacenar únicamente 2 valores (verdadero/falso).

Es importante que al momento de crear una variable identifiques bien que tipo de dato utilizará. Puede que ahora no lo comprendas bien, pero veremos ejemplos prácticos que te ayudarán a comprender mejor este tema mas adelante.


Constantes


Las constantes funcionan igual que las variables, pero estas no se pueden modificar después de haber sido creadas, por ejemplo: el valor de Pi, los grados de una circunferencia, etc.


Declarar variables


Para declarar una variable en pseudo código utilizaremos la palabra clave Definir seguida del nombre de la variable y después la palabra Como seguida del tipo de dato (Entero, Real, Logico, Caracter). el nombre de la variable no debe contener espacios en blanco o caracteres latinos como ñ o acento. A continuación vamos a declarar una variable llamada edad de tipo entero:

Algoritmo datos
Definir edad Como Entero;
FinAlgoritmo

Ahora guardaremos un valor en esa variable en una nueva línea, esto se hace llamando al nombre de la variable, y asignándole el valor con el signo = y la mostraremos en pantalla:

Algoritmo datos
Definir edad Como Entero;
edad=23;
Escribir edad;
FinAlgoritmo

Si en la instrucción Escribir colocamos edad, sin comillas mostrará entonces el valor de esta variable.

Captura de pantalla 2024-09-08 a la(s) 5.23.50 p. m..png


Otros elementos importantes a la hora de escribir código


Al momento de programar, es recomendable tener en cuenta algunas cosas para escribir un código comprensible y fácil de leer, por ejemplo:

  • Identación: La identación del código no es mas que agregar sangrías acorde al nivel en que estemos programando, por ejemplo, los mas observadores seguro ya notaron que todo lo que escribo entre Algoritmo y FinAlgoritmo lleva una sangría, esto se hace para poder identificar de forma visual que es lo que esta dentro de cada proceso.
  • Comentarios: Los comentarios en el código sirven para dejar anotaciones en el mismo sobretodo para poder recordar que hace cada cosa, los comentarios son ignorados por la computadora al momento de leer las instrucciones. En pseudo-código puedes escribir comentarios colocando 2 símbolos / al principio de la línea, por ejemplo:

Algoritmo datos
// Declarando la variable edad como entero
Definir edad Como Entero;
FinAlgoritmo

El comentario “Declarando la variable edad como entero” será ignorado por la computadora y solo será usado por quien vaya a leer el código.


Solicitar (leer) datos del usuario


Ya vimos en la lección anterior como mostrar mensajes en la pantalla, esto se conoce como salidas en programación. Ahora, de forma contraria vamos a ver lo que es una entrada, y para que puede servirnos.

Podemos necesitar información del usuario en determinado punto de nuestra aplicación, imaginemos que tenemos un sistema y un usuario se está registrando, queremos preguntarle su nombre y su año de nacimiento y a partir de allí calcular su edad ¿Como lo haríamos?

La forma mas fácil sera que el mismo usuario nos de esa información, para ello utilizamos operaciones de entrada y guardaremos la información que nos de el usuario en variables. Lo primero que necesitaríamos es crear las variables con sus tipos de datos bien definidos, después necesitaremos pedir los datos al usuario, una vez hayamos rellenado nuestras variables vamos a usar esta información para calcular la edad del usuario y por último mostraremos en pantalla la información procesada. Vamos a crear un algoritmo para esta tarea:

  1. Crear variables
  2. Recopilar datos
  3. Calcular edad (restamos el año actual con el año suministrado por el usuario)
  4. Mostrar resultados

Sabemos que un nombre esta compuesto de letras y el año de nacimiento y edad son un número entero, entonces el primer paso será crear nuestras variables:

Definir nombre Como Caracter;
Definir ano_nacimiento, edad Como Entero;

Podemos crear muchas variables en una sola línea, solo debemos separarlas con comas (,).

Vamos a recolectar los datos, esto podemos hacerlo con la instrucción “Leer” seguida del nombre de la variable donde vamos a guardar la información. Antes de esta instrucción podemos mostrar un mensaje en pantalla para notificarle al usuario que es lo que se está pidiendo:

Imprimir "Ingrese su nombre:”;
Leer nombre;
Imprimir "Ingrese su año de nacimiento:”;
Leer ano_nacimiento;

En esta parte el programa mostrará la pregunta y se detendrá a esperar que el usuario ingrese la información, una vez escriba algo y presione ENTER, el programa continuará su flujo habitual. Esto lo veremos de forma mas clara cuando ejecutemos el código, no te preocupes.

Lo siguiente será calcular la edad, para ello almacenaremos la información dentro de la variable edad que creamos al principio. Colocaremos el nombre de la variable seguida del signo de igualdad (=) y la operación a realizar, de esta forma asignaremos el resultado de la operación en esta variable. Sabemos que vamos a restar el año actual (2024) con el año de nacimiento del usuario que esta en la variable ano_nacimiento esto se logra colocando el 2024 seguido del signo menos (-) y la variable a utilizar.

edad = 2024-ano_nacimiento;

Ya solo nos quedaría mostrar el mensaje con los resultados, podemos hacerlo bonito y mostrar el nombre, y la edad del usuario:

Imprimir "Bienvenido " nombre ", tu edad es " edad " años”;

Cuando colocamos texto fuera de las comillas la computadora reconoce ese texto como variables y muestra su valor. Vamos a ejecutar este ejercicio:

Captura de pantalla 2024-09-10 a la(s) 9.40.21 p. m..png

Al ejecutar veremos como el programa nos pide escribir algo. Le daremos mi nombre.

Captura de pantalla 2024-09-10 a la(s) 9.40.35 p. m..png

Al hacer click en ENTER el programa seguirá:

Captura de pantalla 2024-09-10 a la(s) 9.40.52 p. m..png

Ahora nos pide nuestro año de nacimiento, al hacer click en ENTER el flujo seguirá, veremos el resultado y el programa terminará.

Captura de pantalla 2024-09-10 a la(s) 9.41.01 p. m..png

En este caso tuve un error en el mensaje, vamos a corregirlo y usaremos otros datos:

Captura de pantalla 2024-09-10 a la(s) 9.46.40 p. m..png


Ejercicio práctico resuelto


1. Escribe un algoritmo en pseudo-código para calcular el promedio de notas de 3 alumnos.

Para resolver este ejercicio vamos a crear si algoritmo primero:

  1. Declarar variables donde almacenaremos las notas.
  2. Pedir datos al usuario y rellenar variables.
  3. Calcular promedio: Esto se hace sumando todos los datos y dividiéndolo entre la cantidad de los mismos.
  4. Mostrar resultados.

En el primer paso declararemos las variables para 3 notas, en este caso las haremos como Real para poder incluir decimales, además una variable del mismo tipo para calcular y almacenar el promedio.

Definir nota1, nota2, nota3, promedio Como Real;

Después solicitaremos los datos al usuario y los guardaremos en las variables correspondientes.

    Imprimir "Ingrese la calificacion del alumno 1:";
    Leer nota1;
    Imprimir "Ingrese la calificacion del alumno 2:";
    Leer nota2;
    Imprimir "Ingrese la calificacion del alumno 3:";
    Leer nota3;

Ahora haremos el calculo necesario, sabemos que estamos trabajando con 3 notas entonces las sumaremos y lo dividiremos entre 3.

promedio = (nota1+nota2+nota3)/3;

Finalmente mostraremos un mensaje en pantalla con el resultado.

Imprimir "El promedio de nota de los tres alumnos es de " promedio;

El algoritmo quedaría así:

Algoritmo promedios
    // 1. Declarar variables
    Definir nota1, nota2, nota3, promedio Como Real;
    // 2. Pedir datos
    Imprimir "Ingrese la calificacion del alumno 1:";
    Leer nota1;
    Imprimir "Ingrese la calificacion del alumno 2:";
    Leer nota2;
    Imprimir "Ingrese la calificacion del alumno 3:";
    Leer nota3;
    // 3. Calcular promedio
    promedio = (nota1+nota2+nota3)/3; 
    // 4. Mostrar resultados
    Imprimir  "El promedio de nota de los tres alumnos es de " promedio;
FinAlgoritmo

Si lo ejecutamos:

Captura de pantalla 2024-09-15 a la(s) 11.52.46 a. m..png


Tarea


Es tu turno de brillar pequeño programador Jr. Para asegurarme que hayas entendido el tema te dejo las siguientes tareas:

  • ¿Qué son las variables y para qué se utilizan?
  • Asigna un tipo de dato a las siguientes variables y explica por qué: email, telefono, horas_trabajadas, precio_steem, y edad.
  • Explica el funcionamiento del siguiente código:
Algoritmo nombres
    Definir nombre, apellido Como Caracter;
    
    Imprimir  "Ingresa tu nombre:";
    Leer nombre;
    Imprimir "Ingresa tu apellido:";
    Leer apellido;
    
    Imprimir "Hola " nombre " " apellido ", bienvenido";
FinAlgoritmo
  • Desarrolla un pseudo-código para calcular el valor en USD de X STEEM. Para ello puedes basarte en este algoritmo:
  1. Declarar variables precio_steem, total y cantidad_steem.
  2. Solicitar al usuario los datos necesarios.
  3. Calcular de la siguiente manera: total = cantidad_steem*precio_steem.
  4. Mostrar resultado en pantalla.

Estaré resolviendo todas tus dudas en los comentarios, no temas equivocarte, estoy acá para ayudarte.

Cada tarea tiene un valor de 2.5 puntos para sumar un total de 10 puntos. Para presentar tu código puedes escribirlo dentro de tu propia publicación.

Puedes consultar las clases anteriores:
Basic programming course: Lesson #1 - Introduction to programming [ESP-ENG]

Normas


  • El contenido debe ser #steemexclusive.
  • El artículo debe contener la etiqueta #devjr-s20w2.
  • 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 16 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

Untitled design.png

Variables


At the time of programming it is necessary to use data that we are collecting from the user as our application is working so that they can be reused later. For this task, variables come into our lives, which are "boxes" of information that allow us to store specific data and be able to use them later.

Imagine that you are a teacher and you have to collect the names of all your students, for them you ask each of them to give you a box with a paper on the outside that says "Name", and inside the box a paper with the student's written name. The variables work like this, the name of the variable would be "name", and what is inside the box would be its value. All the boxes have the same name, but each content inside them varies according to the student.


Types of data


In programming we must specify what type of information we are going to save within the variables, for this there are 4 types of fundamental data:

  • Integer: These variables store integer data, that is, positive or negative numbers without decimals (Eg: 23, -4, 0). For example: we could save in an integer variable ages, number of floors of a building, number of students in a section, etc.
  • Real: Real variables keep positive or negative numbers with decimals. You may wonder why not always use a real variable and use an integer one? The answer is for memory reasons, the real variables occupy more memory than a single integer, so it is important to always use the correct type of data to keep our programs as light as possible (Ex: 3.14, 0.15, -5.5). Some examples of real variables are: weight of a person, height of a person, STEEM price, BTC price, etc.
  • Character: These variables are used to save text (Ex: "Eduard", "Calle 3, house 5", "Man"), for example: name, address, blood type, sex, etc.
  • Logic: Logic variables are used to store only 2 values (true/false).

It is important that when creating a variable you clearly identify what type of data it will use. You may not understand it well now, but we will see practical examples that will help you better understand this topic later.


Constants


Constants work the same as variables, but these cannot be modified after they have been created, for example: the value of Pi, the degrees of a circle, etc.


Declare variables


To declare a variable in pseudo code we will use the keyword Define followed by the name of the variable and then the word As followed by the data type (Integer, Real, Logic, Character). The name of the variable must not contain blank spaces or Latin characters such as ñ or accent. Next we are going to declare a variable called integer type age:

Algorithm datas
   Define age As Integer;
EndAlgorithm

Now we will save a value in that variable in a new line, this is done by calling the name of the variable, and assigning the value with the sign = and we will show it on the screen:

Algorithm datas
   Define age As Integer;
   age=23;
   Print age;
EndAlgorithm

If in the Print instruction we put age, without quotation marks then it will show the value of this variable.

Captura de pantalla 2024-09-15 a la(s) 12.25.03 p. m..png


Other important elements when writing code


When programming, it is advisable to take into account some things to write an understandable and easy-to-read code, for example:

  • Identification: The identification of the code is no more than adding indents according to the level at which we are programming, for example, the most observants surely already noticed that everything I write between Algorithm and FinAlgoritmo has an indentation, this is done to be able to visually identify what is within each process.
  • Comments: The comments in the code serve to leave annotations in it, especially to be able to remember that it does each thing, the comments are ignored by the computer when reading the instructions. In pseudo-code you can write comments by placing 2 symbols / at the beginning of the line, for example:
Algorithm datas
   // Creating age variable
   Define age As Integer;
   age=23;
   Print age;
EndAlgorithm

The comment "Creating age variable" will be ignored by the computer and will only be used by whoever is going to read the code.


Request (read) user data


We already saw in the previous lesson how to display messages on the screen, this is known as programming outputs. Now, on the contrary, let's see what an entry is, and what it can serve us for.

We may need user information at a certain point in our application, imagine that we have a system and a user is registering, we want to ask him for his name and year of birth and from there calculate his age. How would we do it?

The easiest way will be for the same user to give us that information, for this we use input operations and we will save the information that the user gives us in variables. The first thing we would need is to create the variables with their well-defined data types, then we will need to ask the user for the data, once we have filled in our variables we will use this information to calculate the age of the user and finally we will show the processed information on the screen. Let's create an algorithm for this task:

  1. Create variables
  2. Collect data
  3. Calculate age (we supt the current year with the year provided by the user)
  4. Show results

We know that a name is composed of letters and the year of birth and age are an integer, so the first step will be to create our variables:

Define name As Character;
Define year_birth, age As Integer;

We can create many variables on a single line, we just have to separate them with commas (,).

We are going to collect the data, we can do this with the instruction "Read" followed by the name of the variable where we are going to save the information. Before this instruction we can show a message on the screen to notify the user that what is being requested:

Print "Enter your name:";
Read name;
Print "Enter your year of birth:";
Read year_birth;

In this part the program will show the question and will stop to wait for the user to enter the information, once he writes something and press ENTER, the program will continue its usual flow. We will see this more clearly when we execute the code, don't worry.

The next thing will be to calculate the age, for this we will store the information within the variable age that we created at the beginning. We will place the name of the variable followed by the equal sign (=) and the operation to be performed, in this way we will assign the result of the operation in this variable. We know that we are going to subtract the current year (2024) with the year of birth of the user that is in the variable year_birth this is achieved by placing 2024 followed by the minus sign (-) and the variable to be used.

age = 2024-year_birth;

We would only have to show the message with the results, we can make it nice and show the name, and the age of the user:

Print "Welcome " name ", your age is " age " years";

When we place text outside the quotation marks, the computer recognizes that text as variables and shows its value. Let's run this exercise:

Captura de pantalla 2024-09-15 a la(s) 12.39.54 p. m..png

When running we will see how the program asks us to write something. We'll give you my name. By clicking on ENTER the program will follow:

Captura de pantalla 2024-09-15 a la(s) 12.40.03 p. m..png

Now it asks us for our year of birth, by clicking on ENTER the flow will follow, we will see the result and the program will end.

Captura de pantalla 2024-09-15 a la(s) 12.40.14 p. m..png


Practical exercise solved


1. Write a pseudo-code algorithm to calculate the average grades of 3 students.

To solve this exercise we are going to create an algorithm first:

  1. Declare variables where we will store the grades.
  2. Ask the user for data and fill in variables.
  3. Calculate average: This is done by adding all the data and dividing it between the amount of them.
  4. Show results.

In the first step we will declare the variables for 3 grades, in this case we will make them as Real to be able to include decimals, in addition to a variable of the same type to calculate and store the average.

Define grade1, grade2, grade3, avarage As Real;

Then we will request the data from the user and save them in the corresponding variables.

Print "Enter student grade 1:";
Read grade1;
Print "Enter student 2s grade":
Read grade2;
Print "Enter student 3 grade";
Read grade3;

Now we will do the necessary calculation, we know that we are working with 3 notes so we will add them up and divide it by 3.

avarage = (grade1+grade2+grade3)/3;

Finally we will show a message on the screen with the result.

Print "The grade point average of the three students is " average;

The algorithm would look like this:

Algorithm avarage
    // 1. Creat variables
    Define grade1, grade2, grade3, avarage As Real;
    // 2. Collect data
    Print "Enter student grade 1:";
    Read grade1;
    Print "Enter student 2s grade":
    Read grade2;
    Print "Enter student 3 grade";
    Read grade3;
    // 3. Calc avarage
    avarage = (grade1+grade2+grade3)/3;
    // 4. Show results
    Print "The grade point average of the three students is " average;
EndAlgorithm

If we execute it:

Captura de pantalla 2024-09-15 a la(s) 12.51.32 p. m..png


Homework


It's your turn to shine little programmer Jr. To make sure you have understood the subject, I leave you the following tasks:

  • What are variables and what are they used for?
  • Assign a type of data to the following variables and explain why: email, phone, working_hours, price_steem, and age.
  • Explain how the following code works:
Algorithm names
   Define name, last_name as Character;
   Print "Enter your name:";
   Read name;
   Print "Enter your last name:";
   Read last_name;
   Print "Hello " name " " last_name ", welcome";
EndAlgorithm
  • Develop a pseudo-code to calculate the value in USD of X STEEM. For this you can rely on this algorithm:
  1. Declare variables price_steem, total and amount_steem.
  2. Request the user the necessary data.
  3. Calculate as follows: total = amount_steem*price_steem.
  4. Show result on screen.

I will be solving all your doubts in the comments, don't be afraid to make a mistake, I'm here to help you.

Each task has a value of 2.5 points to add a total of 10 points. To present your code you can write it within your own publication.

You can check the previous classes:
Basic programming course: Lesson #1 - Introduction to programming [ESP-ENG]

Rules


  • The content must be #steemexclusive.
  • The article must contain the tag #devjr-s20w2.
  • 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 16. 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.
Sort:  

This will be another great week. Thanks, Professor!

@alejos7ven, please what is the name of the editor you are using? Can you share the link with me.

Sorry to intrude, but I think it's https://pseint.sourceforge.net/
and I also have a question about this

  1. does this program have at least an English interface?
  2. is it possible to perform tasks not in pseudocode, but in any real programming language?

Thanks 🙏, let's wait for the professor to assist with the question you have highlighted above. It would be nice if we could run the pseudo code as well.

You can use any language if you already know it. I suggest C++ or JS that are languages that I already know too.

Great to know that we can use C++. I am also familiar with this language as my programming journey started from this language.

Okay sir. But please can I use Python, because that's the language I've been learning so far 🙏

Hi, it is PSeint but it is only available in Spanish, you can use any other such VS Code

Your post has been rewarded by the Seven Team.

Support partner witnesses

@seven.wit
@cotina
@xpilar.witness

We are the hope!

Coin Marketplace

STEEM 0.18
TRX 0.15
JST 0.028
BTC 63064.93
ETH 2468.39
USDT 1.00
SBD 2.55