Introducción a la programación y la informática - Curso completo

Introducción a la programación y la informática - Curso completo

Bienvenido a Introducción a la programación. Mise llama Steven Y mi nombre es Sean. En los próximos 90 minutos, tomaremosa través de esta serie que consta de 21 diferentes segmentos que esperan cubrir los conceptos básicos deprogramación informática, que puede aplicarse a cualquier y todos los lenguajes de programación que quierasaprender. Comenzaremos con el más simple pregunta de qué es la programación, y deestaremos trabajando hacia arriba mientras hablamos sobre las características comunes de la informáticatales como bucles y matrices. Discutiremos cómo leer y escribir código, depurar código que hasescrito, algunas estrategias para ayudar a planificar tu código y mucho, mucho más. El completolista de temas que se cubrirán en este video estilo conferencia se muestran en elpantalla ahora. Además, habrá marcas de tiempo en la descripción, así que siéntete libre de saltarsi ya eres competente en algunas áreas de informática, o simplemente quiero sabersobre un tema específico que estaremos cubriendo. Con suerte, al final de la serie, podrástener una comprensión básica de qué computadora la ciencia es, junto con un arsenal de útileshabilidades que te ayudarán a desentrañar lo que sea lenguaje de programación que decides aprender primero. Solo cubriremos los principales puntos claveque se aplican a todos los lenguajes de programación, entonces estaremos evitando temas comocodificación orientada a objetos y navegación de línea de comandos, como esas son cosas que son específicas del idioma.Además, no se requerirá software para que pueda descargar para seguircon este tutorial ya que no estaremos escribiendo cualquier código para mantener las cosas simples y concentradas.Este video está destinado a aquellos que estén interesados. en informática y programación pero tieneno tengo idea de por dónde empezar y tengo poco para no hay información de fondo sobre la codificación, y asísi eso suena como tú, entonces ata a Sean y Me abro camino a través del loco mundo deinformática, comenzando por la más grande pregunta probablemente en tu mente, que es quéincluso es la programación? Bueno, el diccionario lo define como el proceso.de preparar un programa de instrucción para un dispositivo, pero eso es realmente confusodefinición, así que en términos simples qué exactamente ¿eso significa? Esencialmente, está intentandohacer que una computadora complete una tarea específica sin cometer errores Imagínese esto, por ejemplo: quiere que su menos inteligenteamigo para construir un set de lego, excepto que tiene Perdí las instrucciones y solo puedo construira sus órdenes. Pero recuerda, tu amigo está lejos de ser competente, y si lo sonno se dan instrucciones muy específicas sobre cómo para construir el set, hay muchos erroresél podría hacer. Si él piensa como una computadora, entonces si hay una sola pieza que tienesNo le dije específicamente dónde colocar y cómo colocarlo, todo el conjunto de legoser arruinado y se le dejará sufrir un colapso mental completo que causa todoobjetivo del proyecto que se corromperá. Dando instrucciones para tu amigo es muy similara cómo codifican los programadores. En lugar de un poco menos que inteligente amigo, tienes una computadora menos que inteligente,y en lugar de instrucciones sobre cómo construir un set de lego, lo estamos alimentando con informaciónsobre cómo completar un programa como un juego o Aplicación web. Una cosa importante a tener en cuentaes que los computadores son realmente muy tontos. Los construimos para ser tan sofisticadospieza de tecnología, cuando en realidad, un la funcionalidad principal de la computadora proviene decómo lo manipulamos para satisfacer nuestras necesidades. Ahora, programar no es tan simple como darsus instrucciones amigo ya que en un programadores caso, la computadora no habla lo mismolenguaje como tú, la computadora solo entiende código de máquina, que es un lenguaje numéricoconocido como binario que está diseñado para que el la computadora puede leerlo rápidamente y llevarlo a cabosus instrucciones Cada instrucción alimentada a la computadora se convierte en una cadena de1 y 0 y luego interpretados por el computadora para realizar una tarea. Volviendo al ejemplo de lego, este procesosería como si él no solo fuera menos que inteligente, pero para empeorar las cosas, no podía entenderinglés y solo habla chino mandarín. Para hablar con él, debes convertirtelas instrucciones que entiendes en inglés en el idioma que tu amigo entiende.Este proceso es esencialmente lo que debes hacer por su computadora para que se entiendaLas instrucciones que le das. La gran diferencia entre los dos ejemplos,sin embargo, es que es muy difícil para que la gente entienda el código de máquina y el binario.Traduciendo directamente lo que quiere la computadora hacer en código máquina es extremadamente difícil,de hecho casi imposible, y tomaría mucho tiempo para hacer si pudieras. Cadael programa se compone de millones y millones de esos 1 y 0, entonces cómo, exactamente,se supone que debemos traducir nuestras instrucciones en el código de la máquina? Aquí es donde entran los lenguajes de programaciónjugar. Los lenguajes de programación son fundamentalmente un intermediario para traducir un programa acodigo de maquina. Estos idiomas son mucho más fáciles. para que los humanos aprendan que el código de máquina, yPor lo tanto, son muy útiles para los programadores. Yendo volviendo a nuestro ejemplo de lego, un lenguaje de programaciónsería una especie de intérprete, eso es capaz de tomar las instrucciones que les dasen inglés, y traducirlos en instrucciones tu amigo que no habla inglés puede entender.Esto hace que los lenguajes de programación sean extremadamente útil y la columna vertebral de casi cualquier bienprograma. Piense en los lenguajes de programación como no inglés, y no código de máquina, sino en algún lugaren el medio. Hay muchos lenguajes de programación diferentes.por ahí que cada uno tiene su propio y único usos. Lenguajes como Python y Java actcomo lenguajes de uso general que pueden realizar una variedad de tareas computacionales, mientras que RobotCo HTML / CSS son lenguajes diseñados para más propósitos específicos como mover un robot oconstruyendo un sitio web. Los idiomas también pueden varían en cuán poderosos son. Por ejemplo,JavaScript es un lenguaje de script que es diseñado para tareas más pequeñas mientras java o pythonpuede llevar a cabo mucho más impuestos computacionalmente procesos. Medimos el poder de un lenguaje de programación,o nivel, por lo similar que es a la máquina código, la serie de 0 y 1 hablamossobre antes Lenguajes de programación de bajo nivel. como el ensamblaje o C están más cerca del binarioque un lenguaje de programación de alto nivel como como Java o python La idea básica es que cuanto más bajo sea el nivelde tu lenguaje de programación, más tu el código se parecerá a lo que la máquina puede interpretarcomo instrucciones Aparte de lo diferente propósitos que cada idioma cumple, eligiendoun lenguaje de programación generalmente baja a una cuestión de preferencia, ya que generalmente haymuchos idiomas que realizan tareas similares. Pruebe diferentes idiomas y decida quélas propias reglas, interfaz y nivel de simplificación que más te guste. Entonces, ahora que sabemos qué es la programación, cómo¿realmente escribimos código? No es como simplemente podemos escribir palabras en un documento de textoy automáticamente asume que la computadora puede traducirlo en código de máquina, leerlo,y llevar a cabo una tarea como abrir un navegador. Y además, no podemos simplemente escribirbasura en ciertos lenguajes de programación mencionados en el episodio anterior y esperamos que la computadoracomprender. Entonces, ¿cómo se supone que debemos escribir? código entonces? Bueno, la respuesta es con un IDE. Un IDE, quesignifica entorno de desarrollo integrado, permite la facilitación del código por una computadora.Los IDE proporcionan una interfaz gráfica en su computadora en la cual el programador puede fácilmenteescribir, ejecutar y depurar código sin tener preocuparse por problemas con la compilación ointerpretación del programa. Piensa en un IDE como cualquier otro programa en su computadoracomo un juego, un navegador o incluso el archivo explorador, excepto que lo usaremos para escribircódigo. Los IDE pueden convertir su código en código de máquina y ejecútelo a través de la computadorapara producir resultados. Además de proporcionar un lugar para programadorespara desarrollar su código, los IDE proporcionan algunos herramientas extremadamente útiles para programadoresfacilitar el trabajo de escribir código, como el incorporado comprobación de errores porque ya hablaremos demás tarde; el código no siempre se ejecuta correctamente, autocompletar para palabras de uso frecuente ofrases y jerarquía de proyecto que ayudarlo a organizar y manipular los archivosdentro de tu proyecto. De vuelta en los viejos tiempos, antes de los IDE, el código solía estar escrito entarjetas perforadas y luego alimentados a las computadoras que tomaría horas y causaría mucho dolor.Los IDE de hoy en día actúan como una especie de vía rápida para escribir código y hacer muchas cosasMás fácil para los programadores. Un ejemplo de un específico IDE se puede ver en su pantalla ahora. En elcentro puedes ver el programa que está actualmente siendo escrito, y justo debajo de la consola,que puede imprimir información útil para El programador. Se usa este IDE específicoescribir código java. Los IDE son extremadamente potente y se utilizará en casi el 100% detus proyectos de programación Entonces a través de estos IDE finalmente podemosescribir y compilar código sin problemas preocupándose de que la computadora no puedapara entenderlo El siguiente problema que corremos en entonces se convierte en cómo escribimos este códigoen el IDE, porque no es como si pudiéramos simplemente escriba palabras al azar de una determinada programaciónlenguaje y esperar que el compilador comprenda eso. Aquí es donde un lenguaje de programaciónLa sintaxis entra en juego. Ahora, como si estuvieras aprendiendo un idioma real,aprender un lenguaje de computadora puede ser muy similar. Algunos tienen diferentes estilos que pueden parecer extraños,algunos pueden hacerte usar conceptos abstractos o extraños lo cual puede ser confuso y, como todos los idiomas,los lenguajes de programación tienen un conjunto de reglas que debe seguir al escribir código enese lenguaje, y a la vanguardia de aquellos Las reglas son la gramática. Se hace referencia a la gramática de programacióncomo sintaxis y es muy similar al mundo real gramática. Cada lenguaje de programación tiene supropia sintaxis o reglas que debe seguir a un tee si quieres que tu programa se ejecute correctamente,como si estuvieras hablando en la vida real. Estas pueden ser cosas como la forma en que escribeciertas funciones, lo que pones al final de una línea de código, y cómo configurar ciertafunciones Cada idioma es único en su sintaxis, y aunque algunos pueden compartir reglas similares,todos tendrán un capricho que lo hará permanecer fuera del resto. La sintaxis es algo quepilla a mucha gente por sorpresa, ya que muchos esperar que todos los lenguajes de programación siganel mismo conjunto de reglas, pero como hablamos sobre en el último segmento, porque cada idiomaestá especializado para una tarea específica, cada uno necesita su propio conjunto de reglas para funcionar. Roturao ignorar estas reglas resultará en un error, como romper o ignorarlas reglas en la vida real darán lugar a un involuntario mensaje. Como ejemplo. Si quisiéramos hacer algosimple como inicializar una variable, que es algo que aún no hemos cubierto peroEl ejemplo sigue siendo relevante. En java tenga en cuenta que tenemos que especificar qué tipo de variableestamos definiendo en este caso un número entero, y también agregue un punto y coma después de la declaración.En python, ni siquiera necesitamos definir que estamos tratando de crear una variable ysolo tenemos que escribir lo que queremos crear, y en javascript, solo especificamos que somoshaciendo una variable, pero no incluye qué tipo de variable que queremos hacer. Incluso eneste simple ejemplo puede ver cuánta sintaxis importa al aprender un nuevo idioma desdemientras que el objetivo de nuestro programa seguía siendo el mismo, defina un número entero con valor tres,todo el lenguaje de programación que se muestra tomó diferente enfoques. Todos estos idiomas requieren quesigues esta sintaxis porque recuerda, las computadoras son extremadamente tontos, si olvidas un punto y comao extraviar un personaje, todo el programa no se ejecutará y le devolverá un error de sintaxis,que es algo de lo que hablaremos luego. Piense en esto como si olvidara una coma enuna oración y todo el contexto de lo estás tratando de decir que te malinterpreten.Por ejemplo, en la oración "comamos, abuela". Si olvidaras esa coma,Si bien puede parecer un pequeño error, cambia todo el contexto de la oración,haciendo que parezca que estás a punto de comer tu abuela. Se siguen las mismas reglas para la programación,si olvida un punto y coma, todo el contexto de su programa podría estar dañado y malinterpretado. Ahora, otra cosa que hace que los IDE sean tan útileses que te harán saber si y cuándo Hay errores de sintaxis en su código. Sintaxiserrores, por supuesto, son partes de su código que no siguen las reglas de las que hablamospreviamente. El IDE te dirá dónde su código es el error, y tampoco permitiráejecuta su programa hasta que el error haya sido fijo. Debido a la importancia de la sintaxispara escribir código y aprender un nuevo idioma, se recomienda que aprendas las reglasy sintaxis de un idioma antes de comenzar escribir programas complejos en ese idioma.La mayoría de las reglas son tediosas de aprender pero fácil de dominar y tan pronto como puedas hacer eso,podrás identificar fácilmente la sintaxis errores y cuídalos fácilmente. Eso cubre la esencia básica de sintaxis y programaciónreglas, así que ahora que sabemos CÓMO escribir código, y DONDE escribir el código, a continuación debemos cubrir¿Qué sucede después de haber escrito nuestro programa? y ejecuta nuestro código. Porque escribir una piezade código para un juego o una base de datos es genial y todo, pero después de que la computadora interpretael programa, ¿cómo sabremos lo que está pasando? y si funciona o no? Bueno programadoreshaga esto mirando la consola. La consola es una interfaz de texto dentro de la computadora quenosotros los programadores podemos usar para una variedad de diferentes propósitos Si recuerdas, hace poco tiempomostramos una imagen de un IDE básico, y uno de las partes principales de esa imagen fue elconsola. El uso principal de la consola es generar textodel programa Esto generalmente se hace usando Una declaración impresa. Una declaración impresa es uncomando que hace exactamente lo que suena: Imprime texto en la consola. Esta impresióndeclaración es la primera pieza del CÓDIGO REAL hemos hablado en esta serie, y estan simple como parece. La declaración impresa, a pesar de su simplicidad, es uno de los másfunciones importantes en la programación y existe de alguna forma en casi todas las programacionesidioma. Lo más básico que puedes pedir es la impresión.declaración que hacer es simplemente hacer que diga alguna cosa. Esto se hace instruyendo alconsola para imprimir, y luego incluir lo que sea desea ser impreso dentro de los paréntesis.Por ejemplo, en python, el segmento de código print ("Hello World") causará un mensajeleyendo "hola mundo" para aparecer en el consola. Con buena pinta. La declaración impresa también es vital para vere interpretar la salida de la computadora de un programa. Por ejemplo, si le dices a una computadorapara ejecutar un cálculo simple, por ejemplo para determinar qué es 4 + 3, ejecutará elprogramar internamente y calcular una respuesta. Sin embargo, ¿cuál es el propósito de tener ella computadora ejecuta este programa si no ser capaz de decir cuál es el resultado? En lugarde simplemente decirle a la computadora que realice este cálculo, indica a la computadora queimprimir la salida del programa a la consola, y al finalizar el programa, 7 seránaparecer en la consola. Como puede ver, el la consola nos permite imprimir fácilmente informaciónal desarrollador para una variedad de usos. Es importante tener en cuenta que la declaración impresavaría según el lenguaje de programación siendo utilizado. Por ejemplo, en Java haymúltiples versiones de la declaración impresa dependiendo sobre si desea un salto de línea despuésel texto impreso y las declaraciones impresas especializadas que hacen que su código sea más eficiente. También,la sintaxis general de usar una declaración de impresión y ciertos matices de su función pueden cambiarentre idiomas Sin embargo, generalmente puedes confíe en que lleve a cabo la misma función general,ya que es una declaración fundamental para la programación en general. Así que imprime declaraciones, imprimeninformación a la consola para el desarrollador para usar, agradable. Toda su funcionalidad hace que la declaración impresa,junto con la consola, un desarrollador muy útil herramienta. Sin embargo, es importante recordareso es todo: una herramienta de desarrollo. La consola realmente no está destinada a ser vistapor el usuario final de su programa. Tiende estar escondido detrás de escena y otrosmétodos para mostrar información como Se utiliza la visualización de texto, gráficos o imágenes.para transmitir información al usuario en su lugar. Piénsalo así, cuando estás usandotu teléfono, ves la consola en ninguno de los programas que usas Entonces, si bien puedes usarla consola para darte información sobre cómo está funcionando su programa, no intenteimplementarlo en el producto final porque fundamentalmente no está destinado a eso.En general, recuerde usar la consola para su máxima extensión al escribir y solucionar problemasen sus programas, ya que es una gran herramienta para use para decir cómo se está desempeñando su programaentre bastidores. Así que ahora que conocemos mucha informaciónsobre lenguajes de programación y cómo y dónde para escribirlos, junto con la declaración impresadebajo de nuestros cinturones, repasemos algo intuitivo cosas que la computadora puede hacer sola,sin que tengas que decirle cómo hacerlo. Más específicamente, cubriremos número básicoMatemáticas y matemática de cuerdas Comenzando con las matemáticas básicas, la computadoraYa sabe cómo hacer aritmética simple. Esto incluye suma, resta, multiplicación,y división, todos los cuales están representados por los símbolos que se muestran en la pantalla ahora. Encualquier IDE que pueda instalar, será capaz de imprimir la respuesta a las matemáticas simplesproblemas al usar la declaración de impresión, que puede parecer contrario a la intuición porque ¿por quéusas la computadora para hacer matemáticas cuando tienes una calculadora perfectamente buena en tu teléfono,pero hay que recordar que las computadoras son tonto, y todo lo que queremos que haga una computadoraTenemos que construir desde cero. Aritmética básica, Si bien es simple, ayuda en casi cualquier programapuedes escribir Por ejemplo, si quisiéramos construir una aplicación de calculadora básica, necesitaríamosutilizar esta funcionalidad para mostrar correctamente la respuesta a una aritméticaproblema cuando nuestro usuario intenta sumar, restar, multiplicar o dividir dos números. Ahora, además de las 4 ecuaciones matemáticas básicas,la mayoría de los lenguajes de programación incluyen un adicional operador conocido como módulo. Si este es tuprimera vez que escuchas esta palabra, no te preocupes, ya que generalmente no se enseña en clases de matemáticas.El módulo nos permite obtener el resto de Una operación divisional. Por ejemplo, cuandotomamos 10 módulo 3, esencialmente estamos diciendo la computadora para tomar 10, dividirlo por 3, ignorarla respuesta real y solo danos el resto de esa operación en este caso 1, ya que cuandodividimos 10 por 3, la respuesta es 3 resto 1. El 1 en este caso es lo que se imprimefuera a la consola. Si no hay resto, digamos en el caso de que tomemos 50 módulo 2,como el resto es 0, la función sería devuelve 0 si lo imprimiéramos. Esto puede ser extremadamente útil en muchos casos,el ser más obvio si queremos determinar si cierto número entero es par o noimpar. Si tomamos un cierto número de módulo 2 y devuelve 0, entonces sabemos que es incluso desdecualquier número par dividido por 2 siempre resultará en una respuesta completa sin resto, perosi el sistema devuelve 1, entonces sabemos que el entero es impar. Te encontrarasusando los operadores matemáticos básicos mucho más de lo que piensas, así que es bueno mantenerlosen mente al escribir sus programas. Ahora nuestra computadora puede trabajar con números, comobien como cuerdas. Las cuerdas por cierto son otra manera de decir simplemente texto. Por ejemplo, "holamundo "es una cadena, la letra" a "es una cadena, cualquier cosa entre comillasse denota como una cadena en lenguaje de programación. Cubriremos más sobre Strings en un momentocuando hablamos de variables, pero por ahora continuemos. Ya hablamos deimprimiendo cadenas en la consola, pero vamos decimos que estamos haciendo un juego y queríamosimprime la declaración " "Juego terminado, 4 fue tu puntaje final".Ahora bien, podríamos hacer una cuerda que dice esa frase exacta e imprímela enla consola, en algunos casos sería más útil para imprimir el valor entero real,especialmente en el caso de un juego donde el la puntuación puede cambiar cada vez que juegas, porquepuntaje definitivamente no siempre va a ser 4. Bueno, también podemos imprimir múltiplescadenas de texto e incluso enteros "agregando" juntos en la declaración impresa. Estase llama concatenación. Continuando con nuestro ejemplo de puntaje. Si quisiéramospara imprimir la declaración "Juego terminado, 4 fue tu puntaje final ", usando 4 como enteroen lugar de una cadena, podríamos hacer esto desglosando la declaración en dos cadenasy un entero así. Imprimir ("Game over," + 4 + "fue tupuntuación final) Por supuesto, comenzamos con una declaración impresa,que nuevamente será diferente en todos los idiomas. Dentro de la declaración impresa comenzamos porimprimiendo la cadena "Juego terminado". Ahora aquí viene la parte importante, a partir de ahí,usamos un signo más y agregamos 4 a la impresión declaración, al igual que si estuviera agregando dosnúmeros. Entonces, podemos repetir este proceso con otro signo + para la cadena final "fuesu puntaje final "y podemos imprimir La totalidad de nuestra declaración es fácil.Al hacer esto, podemos imprimir fácilmente múltiples diferentes cadenas y enteros juntos enUna declaración impresa. También podríamos combinar las dos lecciones que hemosaprendido hasta ahora y hacer algo como "Juego encima, "+ (4 + 4) +" fue su puntaje final ",en el caso digamos donde tenemos un juego que te da un puntaje base, luego 4 puntospara una determinada tarea que completó. Esta demostracion También muestra otra parte importante de la programación,que a menudo es para obtener su programa para ser el más eficiente, tienes que combinaraspectos del código. Ahora es importante tener en cuenta que la computadoratomará lo que pones entre paréntesis e imprimirlo personaje por personaje,así que a menudo los programadores olvidarán agregar un espacio al final de sus cuerdas. Estapuede provocar un pequeño error en el que se imprimirá la cadena del ejemplo anteriorfuera como si dijera "Juego terminado, 4 fue tu puntaje final" queno es tan agradable cuando se muestra en la pantalla para el usuario, por lo que es una buena práctica siemprepon un espacio después y antes de tus cuerdas para asegurarse de que esto no suceda, y sula cadena no termina así. Otra cosa importante a tener en cuenta es la diferencia.entre "4" entre comillas y 4 sin comillas. Ahora "4" entre comillaslas marcas se tratan como una cadena en lugar de una 4 sin comillas tratadascomo un número Esto puede no parecer un gran trato, pero de nuevo las computadoras son tontas, y siintentas hacer cálculos matemáticos con un número entre comillas marca que devolverá un error, porque ella computadora no entiende que eres tratando de preformar la operación en un número,y cree que estás intentando agregar un número entero a una cadena, que es un gran no-no en la programación.Entonces, cuando esté programando, asegúrese de hacer una nota mental de si quieres o nohacer algo un número entero o una cadena, porque ese tipo de cosas hace una gran diferencia.Muy bien, eso concluye nuestro segmento en el potencia base de las computadoras. Ahora a continuación vamos a cubrir unode los componentes más importantes de la computadora ciencia, así que ASEGÚRESE de prestar atención porquea continuación vamos a cubrir variables, qué son y cómo los usamos. En primer lugar, ¿qué es exactamente una variable?Una variable es simplemente algo que puede almacenar información y puede ser referenciada y manipulada.Piensa en variables como una caja de cartón. Cartulina las cajas sirven como un medio para almacenar artículos en ellasque se puede cambiar, reemplazar y modificar. Las variables son como cajas de cartón que almacenaninformación para que el programador haga referencia, manipular y referirse. Cada variable simplementetiene un tipo, un nombre y una información almacenado en su interior. El tipo y pieza dela información será cubierta a continuación y el nombre es simplemente un nombre para la variable, piense encomo escribir una etiqueta en el cartón caja en sharpie. Ahora, hay muchos tipos diferentes de variables.que un programador puede usar, pero en este momento nosotros solo cubrirá lo que se llama "primitivovariables ", que incluyen enteros, booleanos, flotadores y dobles, cuerdas y caracteres. Comenzaremos hablando de un número entero.Un entero, o int para abreviar, es tan simple como suena: una variable que puede almacenar unvalor entero. Esto incluye todos los números enteros. de -2,147,483,648 a 2,147,483,648. Ahoraobserve cómo dije números enteros, variables enteras NO PUEDE y NO tendrá ningún valor decimal,así que tenlo en cuenta cuando uses variables. En segundo lugar es un booleano. Un booleano es un muyvariable primitiva que puede almacenar un valor de verdadero o falso. Variables booleanasSOLO puede contener estos dos valores, y son extremadamente útil para declaraciones condicionales, que nosotrosCubriré pronto. Los siguientes dos tipos de variables son flotantesy dobles. Ambos tipos de variables. son tipos de datos de coma flotante, que esencialmentesignifica que estas variables pueden almacenar números con decimales. Mientras que los valores enterosno puede contener valores decimales, flotantes y dobles lata. La principal diferencia entre los dos esque una variable flotante puede almacenar números de una precisión de hasta 32 bits, mientras que la lata doblealmacenar números con precisión de hasta 64 bits. Esencialmente, un doble puede almacenar más decimaleslugares que un flotador, por lo que todo se reduce a qué precisión desea que sea la variable. A continuación tenemos variables de cadena, que soncomo las cuerdas de las que hemos hablado de antemano, excepto almacenado en algún lugar de un valor.Las variables de cadena pueden almacenar cadenas de letras, que son solo palabras y oraciones. Instrumentos de cuerdason útiles para mostrar texto y almacenar información de entrada. Las cadenas también se pueden concatenarjuntos para formar combinaciones de variables de cadena y cadenas preescritas. Esto es muy utilpara enviar información en un formato legible para el usuario Por ejemplo, imagina que nosotrostener una cadena llamada "nombre". El código pide entrada y almacena esa cadena deTexto en el nombre. Para enviar esta información a el usuario, en lugar de simplemente mostrar sunombre, puedes agregar la frase "Tu nombre es: "y convertirlo en una oración concatenando"Tu nombre es:" + nombre + "." Esta facilita la lectura de su código, mientras que tambiénagregando variabilidad a su código, que siempre hace las cosas más interesantes para el finalusuario. Finalmente, tenemos variables char. Char se encuentrapor carácter, y tal como su nombre lo indica, cada uno puede contener un personaje. Esto esútil cuando un programador quiere leer uno presione el botón o un carácter en una cadenasin usar una variable de cadena. Especifico ejemplo es hacer un juego controladopor el teclado El programa necesita reconocer el personaje que se presiona y traduceeso en llevar a cabo alguna función. Ahora Las cadenas también pueden contener un carácter, pero las de charno puede contener más de un personaje, así que sigue eso en mente al definir variables. Ahora, ¿por qué son tan útiles las variables? Bueno siendocapaz de almacenar información en un formato que puede ser referenciado fácilmente más tarde es esencialpara cualquier buen programa A menudo en el código eres va a querer hacer un seguimiento de cosas comocomo nombre o puntaje de un usuario, y así creando una variable llamada "nombre" o "puntaje"puedes almacenar esta información en esa variable y luego referenciarlo, agregarlo o modificarloeso. Además, muchas veces, el programa tendrá para recibir información del usuario, que no puedeser preprogramado en el código, y así Se requiere una variable para almacenar la información.Un programa también puede depender de factores que cambiar a medida que avanza el programa, en el quecaso una variable se requiere una vez más. También, tomando estas variables y manipulándolases bastante necesario para llevar a cabo muchos de las tareas que desea que realice un programa,por ejemplo, multiplicando las variables int o concatenando variables de cadena. Variables generalesson la columna vertebral de cualquier buen programa y podrás te encuentras usándolos a menudo si quierescódigo limpio y eficiente, así que es mejor que aprende qué tipos de variables necesitapara usar y cuándo. Así que ahora que sabemos todo sobre los diferentestipos variables y hemos hablado de ellos un poco, ahora vamos a profundizar másen lo que sucede cuando realmente definimos, o crear, una variable, cómo los referenciamos,y cómo podemos manipularlos para nuestros programas. Para comenzar, repasemos lo que sucede cuandoDefinimos una variable. Ahora cuando escribimos un línea de código que inicializa una variable,y ese código se ejecuta, la computadora esencialmente crea un pequeño espacio en la memoria que almacenasu nombre de variable y su contenido para que Se puede hacer referencia más adelante. Volviendo aNuestro ejemplo de caja de cartón. Piensa en esto como si tienes una instalación de almacenamiento y hacesuna nueva caja de cartón con la etiqueta "Nombre" y dentro de él pones un pedazo de papel conla palabra "NullPointerException" en él. Ahora, cuando quieras saber el contenidode su cuadro de nombre, simplemente puede mirar dentro y ver que tiene el contenido "NullPointerException".Esto es lo que hace la computadora, excepto el la instalación de almacenamiento es memoria, la caja es una variable,y el contenido de la caja son cualesquiera que sean variable se establece para ser igual a. Cada vez quequerer saber el contenido de la variable de nombre, simplemente puedes llamarlo y la computadoraextraer la información que está almacenada en ese variable y usarlo como el usuario veajuste. Otra cosa a tener en cuenta muy rápido es quepuedes hacer una variable sin poner información dentro de ella. Esto sería comosi construiste una nueva caja de cartón, le diste es una etiqueta con un sharpie, pero simplemente noponer información dentro de ella. Eres simplemente guardando ese espacio en su almacén para más tarde.Esto puede ser porque desea almacenar información más tarde en el camino, o si estásva a usarlo para almacenar información dada a usted por el usuario, en cuyo caso NO PUEDEdale información ya que no sabes lo que ingresará el usuario. Solo tenga en cuenta que siintenta referenciar o señalar una variable que no contiene ninguna información,obtendrá lo que se conoce como NullPointerException, que a pesar de ser un nombre increíble para unCanal de YouTube, es algo que generalmente desea evitar al programar. Ahora, los lenguajes de programación nos permiten haceralgunas cosas geniales con estas "cajas" que hemos creado Por ejemplo, vamosdigamos que creamos una segunda variable "channelName" y en lugar de establecerlo igual a "NullPointerException",en su lugar lo establecemos igual a nuestro ya creado Variable "Nombre". Esto no creaun espacio en memoria para esta nueva variable; sin embargo, simplemente apunta a la misma ubicación de memoriaya hemos creado para el "Nombre" variable. Volviendo a nuestras instalaciones de almacenamiento.ejemplo, esto quisiera si en lugar de crear un cuadro completamente nuevo llamado "channelName"y almacenar una hoja de papel con la palabra "NullPointerException" en él, en su lugarsimplemente agregó otra etiqueta debajo del "Nombre" cuadro, titulado "channelName". Ahora tenemosdos variables pero ambas apuntan hacia la misma contenido, que es la cadena "NullPointerException".Usualmente hacemos esto para ahorrar espacio en nuestro código por cosas que sabemos que van a tenerEl mismo valor. Las variables también se pueden actualizar a lo largo de sucódigo. Por ejemplo, supongamos que tenía una "Edad" variable, y dentro estaba el número entero 17.Entonces celebraste un cumpleaños y quisiste para actualizar tu edad. Todo lo que tienes que hacer eshacer referencia a la variable y establecerla igual a cualquier nuevo entero que desee la variablemantener, en este caso 18. Este sería el lo mismo que tener una caja etiquetada edad, con una hojade papel leyendo 17 dentro de él, y luego sacando ese pedazo de papel, borrando 17,reemplazándolo por 18 y luego colocándolo de vuelta a la caja. Al hacer esto, podemospara actualizar fácilmente el contenido de nuestras variables en todo el código como cosas dinámicamentecambio. Como otro ejemplo, si estuvieras haciendo un juego de rol, es probable que tu personaje tenga estadísticascomo ataque, defensa, maná, etc. Como el el juego progresó, puedes actualizar continuamentelas variables para que el jugador pueda obtener más poderoso cuanto más lejos quepasó por el juego, y no lo harías Hay que crear nuevas variables. Tu solosimplemente necesita seguir agarrando esa caja de su instalación de almacenamiento, borrando y reemplazandolos números en la hoja de papel, y luego continúa junto con tu código. Solo mantente adentrocuenta que estas variables no son nada más que lugares en la memoria en los que cierto valorse almacena, por lo que podemos actualizar fácilmente los números, y su lugar permanecerá constante. Despuésun código ha seguido su curso, el lugar en la memoria se elimina hasta que vuelva a ejecutar el código yel programa dedica espacio para la variable de nuevo. Cada vez que ejecutas el código, ereshaciendo nuevas cajas en su instalación de almacenamiento, y al final de tu código, los destruyestodo para hacer espacio para nuevas cajas la próxima vez. Otra cosa genial que puedes hacer con variableses sumarlos, restarlos, multiplicarlos, dividirlos, e incluso modularlos. Ahora estoen su mayoría solo funciona para variables enteras como multiplicar y dividir cadenas notiene demasiado sentido Pero si estuvieras haciendo una aplicación de calculadora y almacenaste la primeranúmero que el usuario ingresó como num1, y el segundo como num2. Entonces podría multiplicar num1 ynum2 juntos, e imprímalos o almacénelos ellos en una nueva variable titulada resultado. Entonces,cada vez que ejecuta el programa, el usuario podría ingrese nuevos números en las variables num1 y num2,y simplemente se establecerían en esos nuevos enteros y devolver el resultado que correspondea esos números específicos. Esto permite para mantener un registro fácil de qué números soncuál y qué está pasando en su programa lo cual es extremadamente útil Además, mientras túno puede restar, multiplicar, dividir o tomar el módulo de cadenas, puede agregarellos. Digamos que tienes una cadena Str1 con los contenidos "Hola" y un Str2 conlos contenidos "allí". Puedes agregar Str1 y Str2 para crear una cadena que tenía el contenido"Hola", ya sea almacenándolo en un tercera variable o imprimirlo en la consola. El último tema que trataremos sobretema de variables son las convenciones de nomenclatura de una variable, que aunque parezca extraña,pero es extremadamente importante cuando se trata de lea su código para que lo cubramos ahora.Ahora, las variables tienen que ser una cadena continua, y si quisieras hacer una variable quealmacenado el puntaje del jugador, tendrías que encontrar alguna forma de combinar las palabras jugador y puntaje,ya que no puedes tener la frase "jugador puntuación "será el nombre de una variable. Todos los programadorestener su propia preferencia personal cuando viene a nombrar variables, pero la quese utilizará en esta conferencia se llama CamelCase, cual es el proceso de no capitalizar elprimera palabra, pero capitalizando cada palabra que lo sigue Volviendo a la puntuación del jugadorejemplo, usando el método camelCase, la variable se llamaría playerScore. Esto nos permiteidentificar fácilmente cada palabra y se convierte realmente útil para nombres de variables largos como thePlayersScoreBeforeFinalBoss ",mientras que si lo escribimos sin mayúsculas, Sería realmente confuso. Esto ayudaráuna tonelada cuando empiezas a encontrar errores en tu código y necesita escanear rápidamente su programapara averiguar qué está mal, y se suma a la legibilidad general del programa. Otrolos programadores pueden usar diferentes convenciones de nomenclatura como usar guiones bajos para separar las palabrasen una frase, pero por ahora nos quedaremos con camelCase. A continuación, pasaremos a condicionaldeclaraciones, que en esencia, son declaraciones que cambian la ruta de nuestro código dependiendobajo ciertas condiciones. Por el bien de mantener cosas simples, para esta sección, líneas rojasconnotará que nuestro código NO seguirá ese camino específico, y las líneas verdes significaránque nuestro código ES siguiendo ese camino. El tipo principal de declaración condicional quelos programadores usan es la declaración if, y esto aparecerá innumerables cantidades de veces encualquier programa que escribas Es tan simple como suena: si alguna condición es verdadera, ygeneralmente la condición estará encerrada por llaves, luego siga las instrucciones ubicadasdentro de los corchetes de la declaración if. Más, Haz otra cosa.Ahora, los corchetes se usan en la mayoría de la programación. idiomas para indicar un segmento de código quecorrerá. Funciona así, si la condición entre paréntesis es verdadero, entonces todo el códigocontenido dentro de los corchetes se ejecutará, y si la condición entre paréntesis NO escierto, entonces se saltará todas las declaraciones dentro de los corchetes Una nota rápida es quemientras este es el caso con la mayoría de la programación idiomas, algunos; como Python, use dos puntos yespacio en blanco para determinar dónde un pedazo de el código comienza y termina, pero por el bien deEn esta serie, usaremos llaves. Ahora, la condición dentro del paréntesispuede tomar miles de formas diferentes como como si el valor de la variable de cadena Nombre esigual a "Steven" o si el puntaje del jugador, almacenado en una variable int, es mayor que5, la lista sigue y sigue. Cada uno de estos las declaraciones se evalúan como un valor booleano, querecordarás de cuando hablamos Las variables son verdaderas o falsas. Si elboolean es cierto, ejecutamos el código dentro del llaves, si no es así, pretendemos tododentro de las llaves nunca existieron y sigue con nuestro código. La declaración if viene con dos más adicionalesdeclaraciones que pueden acompañarlo: de lo contrario, si y más. De lo contrario, si se usa una declaración condicionaldirectamente después de una declaración if, y lleva principalmente la misma función que una declaración if.Sin embargo, la otra declaración if solo será evaluado si el anterior si (o si no)la declaración se omite debido a su condición siendo falso Entonces lo atravesaríamos comoentonces, si algo es cierto, correríamos el código dentro de las llaves de esa declaración.De lo contrario, si ese algo no es cierto, PERO otro declaración dentro de paréntesis es cierto, nosotrosluego ejecutaría ESE segmento de código. Y si ninguno de ellos son ciertos, nos saltearíamos ambos segmentosde código y seguir adelante en nuestro programa. Este es un concepto difícil de entenderso let's do an example. Si tuviéramos un programa that evaluated the if statement if (age = 10),we could then have a statement under that que declaró si (edad = 12). Ahora, si elage variable was 10, which we can see from the example it is, then the code immediatelyfollowing that conditional statement in the los corchetes correrían. The else if statementwe made would not even be tested since we know it is going to be false, and thus theprint statement inside of THAT conditional statement's brackets will be ignored, andthe code will move on to the rest of the program. Now, for example, let's say we changed theage variable to be 12 instead of 10. Now, instead of the first conditional statementbeing, true, it actually evaluates as false, since age no longer equals 10. So what wedo now, is first skip over the print statement which prints out that the age is 10, sinceit's not. Y ahora evaluamos el otro si declaración. We check if age is equal to 12,which again it does, and so now we run all the code inside of that conditional statementbefore finally moving on to the rest of the program. So as a review, we check the initial if statement,if it's good we run all code within that if statement's curly brackets and move onwith our program, if the initial if statement is NOT true, we then move on to any else ifstatement's and evaluate if THOSE conditional Las declaraciones son ciertas. We can have as many elseif statements as we want, although this could lead to clutter amongst your code so we'lltalk about some alternatives later on to help esto afuera. Now that takes care of the if-elsestatement, so now we'll move on to the else declaración. The else statement once again comes afteran if or an else if statement, and will carry out its instructions no matter what, as longas the preceding statement/statements are evaluado como falso If we went back to ourprevious program, we could add an else statement which would only have the code in its bracketsrun if the age variable wasn't “10” o "12". This would catch all cases ofthe program that didn't fit our parameters. It's good practice to ALWAYS have an elsestatement at the end of your conditional statements to catch any weird cases that may come upin your program. Now remember back to the fact that we canhave thousands of else if statements, after a while that can get pretty cluttered, andso another very useful conditional statement which helps circumnavigate this problem isthe switch statement. Una declaración de cambio es functionally similar to many if and else ifstatements together. Escribes una declaración de cambio in the form of switch (variable), and thenbelow that you write how many cases that the variable podría ser. For instance, if we wroteswitch(var), then under it we could write out 5 cases that the variable var could be,and then the instructions listed under that case to be carried out if the var variableis equal to that case. Now switch statements are different sinceinstead of using brackets, they use a colon to signify the start of a set of instructions,and a break statement to end it. Esto es muy useful because you are able to essentiallyuse many if and else if statements without tener que escribir casi tanto. In switchstatements, you just always have to remember to include a default case at the bottom ofthe expression to denote any and all cases que no cumplan los requisitos anteriores.Esto simplemente captura todas las entradas que no encajan dentro de los casos principales del programa.It's very similar to an else case at the final de una cadena if-else. Ahora, ¿por qué son tan útiles estas declaraciones? Bien,many times, programmers want their programs to function differently depending on differentcondiciones For instance, a program could function differently depending on the informationthat the user inputs, such as allowing a user to use a program or not use a program if theyare above or below 18 years old respectively. Or in say a video game, if a user's experiencelevel is above a certain threshold we might quiero darles oponentes más duros para la batalla.Otro ejemplo podría ser un programa que cambia the color scheme depending on the time ofday. O incluso más simplemente, si un usuario presiona a button that is meant to move on to anotherscreen in an app, the programmer would only want the app to change screens if the userclicks that button. Un programa sin condicional statements would do the same thing every time,and would be very primitive compared to one eso puede cambiar dependiendo de sus condiciones. So now that we know how to make and use variables,how to compare them, and what we can do with those comparisons, let's move on to anotherfoundational concept of computer science: matrices Now we've already talked about variables,and how great they are for storing singular bits information for making our code moresimplistic, but one of the biggest drawbacks that come with variables is their inabilityto hold more than one piece of differing information. For example, let's say you're making anapp which allows users to create a grocery lista. Well there's no real easy way to createlists using variables, because it's not like you can have one variable store the namesof 7 or 8 different food items. Recuerda, we can only put one piece of paper in ourcardboard box; no más. Y además, incluso if you were to add multiple items to one stringvariable, you still would have a lot of trouble doing simple tasks you might want from a listlike searching through it or splitting it or even deleting items from the list whenyou're done with them. Este es el problema que usar arreglos nos resuelve. An array is, as you may have guessed by now,a list. Puedes tener una variedad de enteros, an array of strings, and even an array ofother arrays which is something we'll cover en un minuto. Programmers use arrays when theywant to store a lot of variables containing information that is all related to each other,such as a grocery list or a high score list en un juego Think of arrays as a column inexcel or google sheets. Tienes el titulo at the top and then below it are a bunch ofbits of information which all relate to the título. Arrays are super useful when programmerswant to store a lot of information that can be easily searched through because programmershave developed methods of breaking down and using arrays to find specific informationin arrays full of thousands of different variables. As an example to show just how useful arraysare, let's say you're a startup company que posee una aplicación que tiene 100,000 usuarios. Cadatime a user wants to create a new account, they input the username they want and thenyour program will have to check to make sure el nombre de la cuenta aún no se ha tomado.Hacer esto requiere que busques a través de the information of all 100,000 of your usersto see if that username has an account with tu servicio. An array would be able to containall of this information and make it easy to search through and find out if the accountname has been taken with little to no delay. Now the single most important thing to noteabout arrays is how you reference each element of the array within them. Let's create abasic array called numbers, and inside of puso los dígitos 1-10. Now when we want torefer to each cell in this array, we call sobre su "índice". An index is just a fancyway of saying that numbers are placed within la matriz Now you would think that the firstinteger in this array would be the first index, the second would be the second index and soon, but that's not the case. En computadora science, programming languages refer to thefirst cell as the 0th element in the array. This means that if we were talking about ourarray of numbers we just made, the number 4 would actually be in the 3rd index, 5 wouldbe in the 4th and so on, so instead of starting our count from 1, we start from 0. It'sextremely weird and confusing but it's one of those programming quirks you are goingto have to memorize and commit to memory. If you were to not follow this nomenclatureand you refer to the last element in this array as the 10th, you get what is referredto as an “out of bounds” error, since you are trying to reference the 10th element,but there is no 10th element. Que eres en realidad tratando de hacer es referenciar el noveno. Another extremely important thing to noteabout arrays has to do with their size. Cuando you initialize an array, you can do it eitherone of two ways. Puedes llenarlo with the elements that you want containedin the array right then and there, creating and filling the array at the same time, oryou can define how many elements you want in the array-essentially the arrays size-and then populate it with elements later. This is because when we initialize an array,it creates a space in memory that has a size de exactamente lo que le das, ni más ni menos.Esto es genial para cuando queremos acceder a elementos in the array because we can do so instantaneously,but the one downside is that we can't increase the size of the array later on, all arraysizes are final. Piensa en ello como en un escenario arriba una estantería con libros. By populating abookshelf with a certain number of books and then moving on and filling the next shelfwith different books. No tenemos camino por recorrer BACK and add books to that first shelf withoutshifting everything. Una vez que decidamos cuánto space to dedicate space for an array in thiscase, there's no way to ADD more space. Once again because this is extremely importantto remember, this means that once an array has been defined, there is NO WAY to changethe size of it. Si tienes una matriz titulada “Names” with a size of 8, and you tryto add another name to the array you will receive an error, so be careful when messingaround with array sizes. Por supuesto que puede always go back at the start of the code whenyou initially MAKE the array and allocate more space to it if you find out you needmore space to hold items, but once it's definido, NO PUEDE cambiar su tamaño. Another small thing I want to touch upon reallyquickly is that when you initialize an array, you must determine which type of array itis right then and there. Por ejemplo tienes to specifically say it will be an array ofstrings or integers when defining it, and also you're not allowed to mix and match,meaning you can't have an array full of integers with a few strings and some doublesthrown into the mix. Tienen que ser todos los el mismo tipo. Now the last thing we're going to coveron arrays is a little funky, and that is the práctica de colocar matrices dentro de matrices.Si crea una matriz de matrices, se refiere como una matriz 2D o bidimensional. Pensarof these as matrices if any of you have taken clases de álgebra Now If you haven't, thinkback to our google sheets example but instead de solo columnas, también agregaríamos filas.Entonces, cada elemento de nuestra matriz no simply be just a String variable or an Integervariable, but an entirely new array with its Conjunto propio de valores y elementos. The way we index these is mostly the same,except we would have 2 numbers to index instead de 1. Comenzamos con la fila y luego la columna.Entonces un número en la posición (0,2) sería in the first row three columns down, in thiscase the name Clint. Un número en el puesto (1,1) would be two rows down and 2 columnsacross, in this case the name Chris. You get la idea. Now you can also make 3-dimensionalarrays by putting an array inside an array inside an array, but that's a little abovewhat we're going to be covering so I'm lo cortaré allí. Next up we're going to be talking aboutloops, so what exactly are loops? Next up we're going to be talking aboutloops, so what exactly are loops? Next up we're going to be talking aboutloops, so what exactly are loops? Next up we're going to be talking aboutloops, so what exactly are loops? Next up we're going to be talking aboutloops, so what exactly are loops? Well as you could probably tell by that statementright there, a programming loop is a statement that is used to run certain instructions repeatedly,just like how the opening statement of this El tema se repitió 5 veces. Loops are veryuseful for a variety of reasons. Por ejemplo, imagina que quieres imprimir algo 15 veces.Claro, puedes copiar y pegar la impresión declaración 15 veces. Pero esto es realmente molestoto have to do, and becomes even more unrealistic cuando ese número sube a, digamos, 100 más o menos.¿Y si en lugar de reescribir lo mismo instructions over and over again, you couldsimply place the print statement inside of a loop, and it will occur as many times asyou would like, that's the power of loops bebé. With loops we're able to repeat partsof code multiple times. Ahora hay tres different types of loops that we will be discussinghoy. Y arriba está el bucle for. A for loop is very useful for situations describedabove, where you would like to carry out a cierto conjunto de instrucciones en numerosas ocasiones.La sintaxis de un bucle for varía según on the language, however it usually consistsof three parts. Un valor entero, una condición which the integer value must meet in orderto exit the loop, and an operation to modify the integer value after the instructions insideof the loop are completed. Cada vez que para loop runs, the operation you set will be performedon the integer, and as long as that integer still meets the condition you set, usuallybeing greater than or less than a constant valor, el bucle for continuará ejecutándose. Eventually, when the integer has been modifiedby either increasing or decreasing it to the point where it no longer meets the condition,the for loop will terminate and the code will seguir corriendo Por ejemplo, digamosour integer value was i and we set it equal to 0, then we set the conditional statementas i being less than 3, so basically we're saying that as long as i - the variable wejust created - is less than 3, continue running Las instrucciones contenidas dentro del bucle.Finalmente, hacemos la operación i + +, que significa each time the loop runs we will increase itby one, and inside the loop let's just put Una simple declaración impresa. Ahora recorramos el ciclo. We startwith i = 0, 0 is less then 3 so we enter the bucle e imprimir Hello World. Now that theinstructions are done we add 1 to i making it 1. Moving on, 1 in less than 3 again, sowe once again enter the loop and print out Hola Mundo. Again, we add 1 to i, makingit 2 now. 2 todavía es menor que 3, así que ingresamos el bucle de nuevo e imprima hola mundo.Finalmente, agregamos 1 a i una vez más y se convierte en Tres. 3 is not less than 3 though, it isequal to 3, and so we don't enter the loop and it terminates, moving on to the next segmentde código Este es un ejemplo simple, pero tú can extrapolate it across programming to fittus necesidades. Now when using a for loop you have to makesure to set up a condition that, given the initial integer value and the operation, willat some point not be met, to avoid creating un bucle infinito y bloqueando su programa.Se produce un bucle infinito cuando das un for loop a condition which will always be metgiven the parameters of the program, and so el software falla. For example, a for loopbeginning at 10 and checking if i is ever less than 0, and then adding 1 to i at theend of the loop will never terminate, since Solo aumentaré infinitamente. After the for loop is the very similar foreach loop. A para cada bucle (o para for-in-list loop, in python) is used for iterating througharrays or lists. Esencialmente, el bucle será go through each element in the array and carryout some set of instructions for each value. If you would like to read all of the elementsin an array and compare them to some value, or perform some operation on them, a for eachloop is extremely useful. Así por ejemplo, we could have a for each loop which iteratedacross an array and simply printed out the valor de cada ubicación de matriz. A continuación, tenemos el bucle while. A while loopwill continually carry out its instructions while a conditional statement given to ites verdad. Esto puede ser tan largo como cierto variable is true, as long as a number is lessthan another number, or while a value is still igual a otro valor. While loops are differentthan for loops in that the loop is not contained within one statement, but stretched out andwill continue to run so long as its condition es verdad. Like a for loop, you can make the conditionsuch that it will eventually return false and exit the loop, however while loops willnot crash your computer should you create Un bucle infinito. In fact, it is very commonfor while loops to run infinitely, as, for certain programs, you would like the programto continually be iterated through instead of running once, all the way through untilyou exit out of the program. When programming a game, for instance, a whileloop would be used to iterate through your code, continually refreshing the screen asthe game runs. Desde allí puedes realizar operations on the screen to make the gameplayable. Crear un ciclo while infinito would simply be done using the syntax while(true),as the condition true will always be evaluated como cierto Finally, I'd quickly like to cover an extensionof the while loop, the do-while loop. Do-while loops are very similar to while loops, exceptthey will carry out their instructions at least once, even if the condition is false,and then will carry on like a basic while lazo. Essentially, the conditions inside theloop will run AT LEAST once, and then if the condition is still met they will run againand function as a normal while loop. As you can see, loops and their many varietieshave some extremely useful functions. Utilizando them, you are able to perform an operationmany times in a row, you can iterate through arrays and lists, and overall decrease theclutter of your code. Next up, we're going to take a break fromlearning about common programming statements, and dive into what happens when the code wewrite doesn't work. Más específicamente, vamos a be covering the different types of errorsthat can occur when you're programming, y lo que los causa. Now when you're writing code, you have tounderstand that things aren't always going to go the way you expected them, and sometimesthe program doesn't always work as you had Lo pretendía. We programmers call theseerrors and while annoying, they are always going to come up in computer science and soit's best to learn what they are and how to tratar con ellos. Often referred to as “bugs”,errors in scripting languages can be narrowed down to one of three “types”: syntax,runtime, and logic, all three of which we estará cubriendo en el video de hoy. To kick things off, let's talk about syntaxerrores These are usually the easiest of the 3 to solve since they are oftentimes somethingthat can be fixed within seconds. Si tu recuerdas back to earlier in the video when we talkedabout syntax and programming rules, we said that if you were to break the programmingrules, or syntax, that it would result in un error. Well that's what syntax errorsare, parts in your program where you fail to meet the programming rules and so the computerdoesn't know how to interpret your code. This can be anything, from forgetting a semicolonat the end of a statement in java, accidentally defining a variable with two words insteadof one, or even just misspelling the word String when you're trying to define a stringvariable. Por suerte para ustedes, estos errores are extremely easy to fix since you just needto figure out where the error occurred and cuál era la regla de sintaxis que rompiste. Now thinkingback to IDE's, we mentioned that IDE's are so useful because they do precisely that,they underline syntax errors and usually provide consejos útiles sobre cómo solucionarlos. Pensarof syntax errors as small misspellings or grammatical errors in an essay you're writing,annoying; sí, pero no el más irritante cosas. Another useful thing about IDE'swhen it comes to syntax errors is that the program will actually restrict you from runningthe code unless all syntax errors are cleared, haciéndolos aún más fáciles de identificar y arreglar. The second type of error we will be coveringis the runtime error. Estos errores no show until you actually “run” the code,hence the name “runtime” error. Tiempo de ejecución errors are caused by a statement in your codethat SEEMS seems logically sound, but the computer physically has no way of computingit in a reasonable amount of time. Lo mas common of these errors is one which we'vealready talked about; El bucle infinito. Como a refresher/example, think of an infiniteloop like this. Digamos que sentó a su amigo in front of the TV, put on the Office on repeat,and told him he could leave as soon as Michael hizo una broma de "Eso es lo que ella dijo".Parece bastante simple ¿verdad? Incorrecto, porque instead of putting in the Office, you putin FRIENDS on blu ray. No michael, no inapropiado joke, meaning your friend would be sittingthere for the rest of his life probably confused as to why Dunder Mifflin looks so much likea coffee shop. Esto es esencialmente lo que sucede. with the computer, you give it some conditionthat it has to complete before the program puede terminar; however, you give it no feasibleway to finish that task. Esto pone la computadora in error mode and most likely will crash yourprogram, as the computer desperately tries to complete the condition you gave it. Comoa computer example, if we try to have a program terminate when an integer i is no longer greaterthan 99, but i is initially 100 and only increases, the loop will never terminate and the programwill crash. Para evitar esto, generalmente want to think through the flow of your codebefore running it -especially with loops- to make sure that all of your statements canbe completed by the computer. Planificación cuidadosa out your code before you begin writing itis an extremely useful practice, and something we'll be covering towards the later partde este video The final type of error that we will be coveringis a logic error. Este error también es bonito. Autoexplicativo. A logic error occurs whenthe code runs smoothly without any runtime or syntax errors, but the result that youget isn't what you wanted. Por ejemplo, let's say you had a calculator app, andyou wanted to instruct the program to add two numbers, except it multiplied them insteadbecause you used the multiplication symbol en accidente. This leads the sum to be 36 insteadof 13. Nothing went wrong with the code syntax or runtime wise, the code runs just fine,it just doesn't work as you intended it to. These are often the hardest types of errorsto debug since most of the time, you'll have no idea why the code isn't working,and certainly not any idea of how to fix it. This is why it's a good idea to test yourcode incrementally, don't wait until you've been programming for an hour before testingyour application, or else you'll run into Muchos errores lógicos. Logic errors can beextremely frustrating and could cost you a lot of time, making them a huge pain, butif you know how to effectively debug your código, estarás bien. Speaking of debugging your code, that bringsus straight into our next topic, which is Cómo depurar tu programa. Ahora, digamos que has escrito un programa.You think it's ready, and you're ready to Pruébalo. You've been working hard on this,and you're excited to see it in action. You run the program, and wait for it to runsmoothly and efficiently. Solo que no trabajo. You have encountered one of the threeerrors we just mentioned. De verdad quieres este código funciona, pero ¿cómo? This is wheredebugging comes into play. If the code is giving you an error, then thefirst thing you should do is read the error. Oftentimes, for syntax and runtime errorsthe IDE will print an error message out to la consola. See what line or lines it pointsto- since those will be the lines in which the error occurred- and see if you can understandand fix what it says the problem is. Si el error isn't clear, or you've never heardof it, then try googling it, there are many websites out there such as stackoverflow whichserve as forums to ask and answer problems con código Chances are, if you've had aproblem, someone else has had the same issue y es probable que haya una solución probada. Generalmente,when a syntax or runtime error pops up, you should be able to find a fix for it fairlyeasily; sin embargo, como dije antes, el problema may arise from some loophole or oversightin the code you hadn't planned for beforehand. Maybe you did something as simple as multiplytwo variables instead of adding them. Estas son los errores lógicos de los que hablamos anteriormente.Estos problemas generalmente no tendrán texto rojo aparece para explicarte lo que salió mal.Tendrás que resolverlo tú mismo. Now there are a few different strategies youcan use in order to track down and fix a logic error. First, you can use print statementsand the console in order to determine where the code is going wrong. Imagine you have a conditional statement thatwill run one segment of code if an integer x, is greater than 5, and will run anothersegment of code if not. If, in your program, x is supposed to be greaterthan 5 when the program reaches this conditional but for some reason the program is still printingout “X is small” you could use a print declaración para ayudar. For this problem specifically you could placesaid print statement before the branch of the conditional that would print the valueof x. Ahora cuando ejecutas el programa sabes exactamente lo que la computadora está pensando. Printingout the value of x just before the if/else statement will let you know if the variablehas the value you want it to have, and if it doesn't you know that somewhere abovethat conditional something went wrong and x was set to a value you didn't want ita. En este caso, x es igual a 2, que es por qué x es pequeño se está imprimiendo. Now we know what the problem is we can trackdown where and when in the code we modify x para resolver el problema. Use print statementsto determine where your program goes wrong, and then try to track down the cause of theseissues and solve them. Si usas esta estrategia, make sure you end up deleting the print statementsafterwards to avoid clutter in the console. The situation described above could also besolved using a breakpoint. Un punto de interrupción se detiene your program when the line you placed thebreakpoint at is reached in your program. If, say, you would like the program to runthrough a certain conditional and set a variable based on that conditional, but you are unsureif this actually happens correctly in your code, you can place a breakpoint inside theconditional path you want to run. Upon the breakpoint being reached, the programwill pause, and wait for you to continue it a través de un botón presione. This signals thatthe spot in the code where the breakpoint was placed, in this case the correct conditionalpath, has been reached by the program. usted can then continue the program knowing thatwas or wasn't where an error in your code ocurrió. Breakpoints can be used in conjunctionwith print statements in order to both pause the program, and perhaps view the values ofyour variables at the moment in time to give usted mismo toda la información que pueda desear.También puede tener múltiples puntos de interrupción para help slowly work through your program anddetermine where the error has occurred. UNA combination of these two strategies will helpyou easily determine where in your code you Han incurrido en un error lógico. Next, let's go over what to do if you thinkyou have tracked down the section of code Eso causa el problema. You may think youshould delete it, but it's likely you put it there for a reason, and you don't wantto lose that work if you don't have to. En primer lugar, intenta comentarlo. Comments areused to markup code and explain their surrounding secciones, pero también se pueden usar para depurar.Todo lo que se designe como comentario será not be read by the program as code, and willbe skipped over. Esencialmente, se convierte en algo. that is only there for YOU the programmerleer. The syntax varies from language to language, but it usually involves placingsome symbols before or around the code you would like to be commented. Examples of howto comment in different languages can be seen en la pantalla ahora. Also, when you commentsomething, the IDE will grayscale the line of code, making it extremely easy to determinewhat's commented and what is not. Comentando code 'deletes' it in the computer'seyes without actually deleting it. Si un problema is present before you comment a section ofcode but it is gone afterward, then that section de código es el culpable. If you comment partof a code out and there are still issues, then move onto another section until you findthe culprit. Una vez que lo hagas, puedes modificarlo until it works as intended or delete it entirelyand you will have a fully functioning program Una vez más. ¡Hurra! Now that we've talked about what to do IFyou've encountered an error and a strategy on how to find and fix it, I'd like to talkabout some strategies you can use to AVOID errores en primer lugar. Firstly, backupyour code frequently. En caso de que code completely bugging out and you beingunable to fix it, you will want the ability to revert to a previous version where thecode was still working. Si ahorras con frecuencia enough, then you will probably not lose toomuch work. Administradores de versiones como Github o Subversion can help with this, as they backupcode to an online cloud service in which you can easily pull previous versions of the programen cualquier punto. Also, on top of saving, run your program frequentlyto ensure that the current version works as destinado a. This accomplishes two things. primeroof all, it prevents you from saving a backup Eso no funciona. Secondly, if you encountera problem, it will be easier to find if you have only made a small number of changes sincethe last time you ran it and it worked, and thus you will only have to look through thenew code for problems. Si has gastado 5 hours coding and hadn't run it during thattime period, it's going to be extremely likely that at some point during that 5 hourcode sesh you messed up, and it's going to be even harder to figure out where youwent wrong. Errores, aunque molestos y extremadamente frustrating, are a fundamental part of makingyou a better programmer. Alright, now that we've covered errors fora bit, let's hop on back to programming statements and talk about one of the mostimportant concepts in computer science, the función. Now, you may not know it, but we've actuallybeen talking about a few functions this entire serie. Print statements, for loops, and evenbasic math operations are all examples of functions, which of course begs the questionof what actually defines a function. Bien, a function is a segment of code that can beeasily run “calling” the function name and depending on the type of function, willdo something in return. Functions can be called numerosas veces y en numerosos lugares. Esencialmentethey are like wrapping up a segment of code en un bonito regalo y darle un nombre que;cuando se le llame, desenvolverá el presente e irá a través del código que envuelto. For example, the print statements we havebeen using this series allow us to print something a la consola cada vez que queramos son funciones.Usted ve, simplemente "llamamos" a la función de impresión and enter in what we want to be printed tothe console, and the computer does it for nosotros. Behind the scenes, there is actually evenmore complex code that is in charge of taking your text and translating it to the consolepara ser impreso Los desarrolladores de casi todos programming languages realize that you don'twant to program something that manually has to print something to the console throughthe use of complex programming, and so they implemented the print statement to reducethe stress and complexity of code on the user, abstrayéndolo a una simple línea de código.Todo ese código que se usa para imprimir algo to the console is wrapped up like a presentand given to us in the form of one line, “print()”. This is actually the main theme of all functionsand the backbone of any good program. A menudo in your program there are going to be sectionsof code which are repeated and serve the same purpose, or equations which you want to allowdiffering inputs of. Y entonces puedes usar funciones in order to condense these down into singularlines of code to save both time and reduce desorden en su código. As you will see soon,functions are EXTREMELY powerful and will definitely be something you utilize all thetime in your computer science journey. The print statement is just one example offunctions in everyday code. Hay miles of functions that are available to you throughIDE's. Sin embargo; porque no siempre use all of the thousands of functions thatare open to you in a single program you have to import these functions from packages foundin the IDE, which is something we will cover mas tarde. Now, there are four main types of functionsin most programming languages, and they are separated by two defining features: whetheror not they take in arguments, and whether o no devuelven valores. Empecemos porseparating them by whether or not they take arguments, but first we have to cover whatarguments are. Arguments are essentially variables that wepass into the function in order to be manipulated and then either returned back to us, printedto the console, or used in another operation. Think of functions with arguments like orderingfood at a restaurant. Si caminaste hasta your local five guys and told them you wantedto get food without supplying a type of food, they would probably look at you confused.Necesitas decirles exactamente lo que quieres ordenar para que te lo puedan dar.En este caso, conseguir comida es la función and what you order is being passed in as theargument. Basado en lo que les dices, o El argumento es que harán algo diferente.También debe tener en cuenta que el argumento puede be many different things, it could be fries,burgers, soda, anything really on the menu, y tal es el caso con los argumentos en la programación. This is essentially what happens with thecomputer, for example, the max function which takes two integers as arguments and returnsthe maximum number between the two. Ahora para this function if you don't input two numbersor variables for it to compare, it's going to throw you an error just like the five guysemployee, he doesn't know what you want to eat since you didn't provide him anyarguments, and the computer doesn't know what two numbers you want it to compare andreturn since you didn't provide it with Dos enteros. Arguments are a way for programmersto have one function that can do many different things depending on whichever variables canbe passed through. Los argumentos agregan variabilidad to programming and can help diversify yourcódigo. Pensando en el ejemplo de nuestros cinco chicos, a restaurant that only allows one type offood to be made regardless of what you order isn't going to be very useful or diversified,but if we're able to pass in arguments and tell them what food we want, our experiencecan be heightened and more options become available, which is exactly what happens whenyou accept arguments in your functions. Now that we've talked about functions thattake in arguments, let's move on to functions which do not take in arguments, because functionscan also be created and used without taking en argumentos y aun así ser increíblemente útil.Por ejemplo, digamos que estabas haciendo un text based RPG game and one of the optionsyou give your player is the ability to view their stats at various points throughout thejuego. Ahora cada vez que te encuentras con una opción and they choose the “View Stats” button,you don't want to have to type out 6 different print statements for every statistic theymay have, your code would get cluttered and desordenado muy rápido. Instead, what you coulddo is package the 6 different print statements en una función simple llamada printStats ().No necesita pasar ningún argumento a the functions since the function will do thesame thing no matter what the statistics on the player are. Now, everytime the user wantsto view their stats, you simply call the printStats() function and voila, the user's stats areprinted for them to view. Esto te permite to save a lot of time writing out code, butalso a lot of space which is extremely important when your programs begin getting into hundredsand thousands of lines and you want to easily busca a través de él. Okay, now that we've separated functionsinto those that take arguments and those that do not, let's again split these up intothose that return values and those that don't. Now the thing you have to understand is thatwhen you're making your own functions, which is something we will be covering soon, youhave to choose what your function will return, en todo caso Functions are able toreturn values back to the user whether they be String variables, integer variables, oreven arrays. Ahora lo que hay que tener en cuenta sobre el regreso values is that calling the function alonewon't do anything. Tienes que devolver el valor en algo. As an example, the Maxfunction we talked about previously would return an integer, but in order to do somethingwith it we would have to either set a new integer variable equal to the result of thatMax function, or we can print out the result of a function, which in this case would justprint out the maximum value between the two enteros Using functions which return valuesdon't do much on their own, you have to pair it with something in order to gain usefuera de el. Let's do another example, let's say youhad created a function which took in two string variables as arguments, combined them usingthat fancy String math we talked about earlier, y luego los devolvió como una sola cadena.Esta función combineString podría entonces ser used to create new String variables sincewhat it is returning is technically a string. The variable would simply be set to whateveris returned from the combineString. The last type of function is one that doesnot return anything, and these are known as Funciones "nulas". Oftentimes these arelike the printStats function we created earlier, simply used to condense large amounts of printstatements that appear often in your code. These cannot be set to variables since theydon't return anything and just get the code dentro de ellos atraviesan. Ahí lo tienes, los 4 tipos de funciones.Los que toman argumentos y devuelven cosas, ones that take in arguments and don't returnsomething, ones that don't take in arguments but still return values, and the ones thattake in arguments and don't return anything. Each of these 4 types of functions are usefuland unique in their own way and you will probably find yourself using them all throughout yourprogramming journey, so get used to the different types of functions and know how to make themost of them, as they are all extremely powerful. Finally, I'd like to talk about one of themajor benefits of functions, which is that it makes it super useful to make large changesto your code without having to go through todo el programa Each function call isjust a copy of that function's original code, and so it's very easy to make changes tothe function and have it translate to across tu codigo. Let's go back to our printStats()function and say that you wanted to go back and add in a new stat that the player canlevel up through experience in the game. Sin functions, you would have to go back intoyour code, find every instance that you had printed out the users stats, and create anotherprint statement to display the new statistic. However, if you had created a printStats()function like we did a little while ago, all you would need to do is find where you definedthat function and add in a print statement which displays the new statistic and you'redone, bam. Ahora, cada lugar que había llamado the printStats function previously will nowalso print the new statistic as well. usted can see how powerful functions can be if usedproperly, and we haven't even scratched La superficie todavía. Now, up next we're going to cover how wecan import other people's functions that los escribieron y los usaron en nuestro código. Now before we get technical, close your eyesand imagine you are trying to build a house. Sure, you could grow your own trees, chopdown your own wood, make your own tools and clavos, y construirlo desde cero. Pero por quédo that, when you can simply go to your local Home Depot and buy these materials that othershave already made ready for you. Eso es the main idea behind importing functions intotu codigo. Importar funciones te permite to gain access to libraries of functions thatother people have already made for you. Esta es tan útil como parece. Existenso many functions that are super useful for any given program that it would take you foreverto write them all yourself. Por suerte, otro people have already done most of this fortú. In each programming language, you are ableto use an import statement to import libraries of functions into your program that you canuse as you write it. A library is simply a collection of functionsthat all have the same theme. Puede ser un math library, a data analysis library, a librarywhich translates text, or anything that you se me ocurre realmente. There is such a varietyof libraries for any given language that most functions you require that are not hyper-specificto your program can likely be found in some biblioteca. In fact, a good portion of any programmer'sjob is looking online for packages which can make his or her job easier instead of handwritingfunciones Ahora, puedo oírte decir: "Guau, eso está enfermo, ¿cómo lo hago? Bueno esquite simple: an import statement. In most languages, an import statement consistsof 3 parts. The library you would like to import from, the package you would like toimport from that library, and then which class de ese paquete que le gustaría usar. porexample, we could load up the Java library, and from there import the util package, shortfor utilities, and then from that utilities package import the scanner class, a classwhich allows us to read information from the user. A package is simply a smaller sect offunctions and methods to help differentiate between the thousands of methods containedin a library, and class is even more specialized que eso. Now if you don't know what specific classesyou're going to want to pull methods from, you can use a star * to import all classeswithin the package you'd like. Sin embargo, it can be beneficial to be more specific,and only import the classes you would like, as it helps with efficiency of the programa la larga. Por ejemplo, en python, the syntax to import a library is import followedby the library name. Sin embargo, importando un entire library is more computationally taxingthan importing specific functions from a library. Imagine you would only be using the factorialfunction from the python math library. It would be a waste of computing power toimport the entire library, and would increase El tiempo de carga de su programa. For smallerprograms, this isn't a big deal, but it really starts to add up when dealing withlarger projects. Por lo tanto, en su lugar use “from math import factorial” or thejava equivalent “import java.math.factorial”, and now have access to that one math commandsolamente. This limits the functions that you can uso, sin embargo, ahorra tiempo de ejecución de programación.Si decides que quieres usar otra función that you hadn't planned for, you can alwaysgo back and import that too. Muchas veces si you try to use a function from a common packageand you have not yet imported it yet, the IDE le pedirá que lo haga. If you're trying to figure out which librariesyou want to import, think of the functions vas a necesitar en tu programa. Performa simple google search, and you will probably run into a package or library that alreadyexists in your IDE that you can use. Y si you can't, there are ways to download andimport additional projects to fit your needs. But if after all of that you still can'tfind a library that contains the function ¿Estás buscando? Well that's a perfectsegway into what we're going to talk about next, which is the basic structure for writingyour own functions. So at this point we've talked about bothwhat functions are and how we can get some very useful functions by importing functionsthrough packages. But there are definitely going to be moments in your programming journeywhere you're going to want to make your own functions because you want to make onespecific to your program and code. Por suerte, making your own functions is extremely simple,there are just some basic rules I want to cubrir. Now while we've previously used makingfunctions as an example for other topics such as the playerStats function from a littlebit ago, they were extremely abstract and didn't go in depth into what is needed foran actual function to operate. Así que ahora we're going to be covering a skeletal systemof everything that needs to be included in una función para que funcione. Now think back to the 4 different types offunctions that we talked about previously. Functions that do and don't return valuesand functions that both do and don't take en argumentos For creating your own functions,we're just going to go down the list and talk about how to approach creating them,starting with the most basic of the bunch, one which takes no arguments and returns novalues, but before we start that, there are a few small things I want to note about functionnaming conventions. Las convenciones de nomenclatura variable we talked about previously also translateover to function names. Entonces no puedes tener two word functions and you can't use specialcharacters like periods or commas. Generalmente you're going to want to follow the samecamelCase style which we talked about in the Variables de video. Alright, so in general for making functions,each language differentiates how you tell la computadora que es una función. In javayou have to define the functions scope, which is something you don't really need to knowunless you're going to become more invested in java, but basically it tells the computerwhich parts of code can use the function and qué tipo no puede. For this series all ofour functions are going to be public. Desde there you then determine which type of functionit is, so in this case since it won't be returning any variables we'll just put voidto signify this type of function will not Estaré devolviendo cualquier cosa. Finally, you put thefunction name after those two identifiers along with a set of parentheses after it likeentonces. Los paréntesis son donde tus argumentos would go if you were making a function thattook in arguments, but since for our first type of function we're not incorporatingarguments into this function, let's just leave que en blanco Todo eso es solo para Java;Python por otro lado todo lo que haces es poner def, short for define, and then the functionname with a set of parenthesis. Así como tú can see, each language is going to be different,but the main thing we want to remember is para agregar siempre paréntesis. From there, wejust type what we want our void function to do within the confines of the function andthen close off the loop and we're done, pan comido. In Java, the confines of the loopwould be whatever is contained within the curly brackets, and in python it would beuntil you are no longer indented. En su centro, this is the most primitive type of functionwe've just made. Algo que toma no arguments and returns no values, quitesimilar to the printStats function from earlier en. Moving on to the next type of function, creatinga void function that takes in arguments. Ahora this process is going to seem very similarto the previous except for one small adjustment. Remember the parenthesis that I mentionedlike 30 seconds ago, well we put any variables we want the user to pass into the functioninto these parenthesis, and then when we “call” that specific function, it will be requiredto have those variables passed into it. por example, in Java, let's make a functionthat takes in 2 numbers and prints out the producto de esos números. Comenzamos con elpublic void plus name of function setup since de nuevo, no devolveremos ningún valor.Y ahora viene la nueva parte. Dentro del paréntesis, you define which type of variables you wantto pass in as arguments, in this case an integer, y luego un nombre para esa variable. Este nombreis what you will use to refer to the integer the user passed in. For this example let'sjust call it num1. Entonces si queremos agregar another argument, we simply add a comma inbetween the two and we can make another integer variable num2 para contener el segundo número. Nosotroscould do this for however many variables we want to pass into the function, but for nowlet's close off the parenthesis and just imprime el producto de num1 y num2. Como tucan see, we refer to the two numbers the user ingresará a la función como num1 y num2. Now, whenever we want to call the multiplyNumbersfunction, we just have to make sure that we are putting 2 numbers in as arguments. Enthis case the number 5 becomes num1, and the el número 8 se convierte en num2. From there we simplyrun the code and the number 40 is printed a la consola Es importante tener en cuenta queyou can also mix and match variables when haciendo argumentos So you can have someFunctionwhich takes in a char, an integer, and two cadenas de todo dentro de una función. Pretty neaten mi opinión. Lo último que quiero mencionar about arguments is that when you call a functionyou have to follow the variables you defined Al hacer la función. So for our multiplyNumbersfunction you couldn't put in a string and entonces un int. It HAS to be two integers becausethat's what the computer is expecting to ser pasado a la función. So now that we've gone over how to makefunctions that don't return variables, we have to cover those that do, and we'll startwith ones that don't take in arguments. Now the main difference between defining functionsthat return variables and defining ones that do not is that in some cases you have to specifythat you want this function to return an integer variable, this is most commonly used in Java,where you would replace “void” with “int” to tell the computer that you want this functionto give something back to you in the form of an integer. This works the same as if youwanted to return a string, char, or even an formación. You simply replace the word after publicwith whatever variable you want to be returned por la función The most important thing to remember aboutmaking functions that return variables is that no matter what path your code takes,it MUST return a variable NO MATTER WHAT. ¿Qué significa esto? Well let's say youhad some String function in a game and inside of it there was an if statement where if theplayer score was above a 10, you returned Un mensaje de felicitación. This works fineif you print the result of this function and the player's score is above 10. But, ifthe playerScore was less than 10 then you don't enter the if statement and then youdon't have something prepared to be returned to the user and so the function is going tothrow you an error. Tienes que tener todos tus paths covered which may seem simple, but ifyou're making a function with a switch statement in it containing high amounts of cases, thiscan get out of hand quickly. Algo que me gusta to do just to make sure this doesn't happenis put a return statement at the bottom of the function with a string or an integer sounique that I'm able to tell that the code no funciona correctamente y puede solucionarlo. losmain point I'm trying to get across however, is always cover your exits and always havea return statement prepared for any case the El usuario puede tirarle. Another small thing to note is that you can'treturn one type of variable if you have already definió la función para devolver otro tipo.Por ejemplo, no puede devolver una cadena en una función entera o viceversa. El regresostatement must always match the type of function no importa qué. The final type of function is one that returnsvariables and also takes in arguments, and for these all you need to do is combine whatwe've learned from the previous cases. Primero, you assign your arguments in between the parenthesis,making sure you have also defined what variable you want to return, and then ensure that nomatter what path the code takes that you are siempre devolviendo ese tipo de variable. Eseconcludes our discussion on functions. Como you can probably tell, functions are an extremelyvast subject area and require a little bit of practice to fully understand, which iswhy later on we'll recommend some websites you can use to practice these more difficulttemas Now I'd like to switch gears a little bitand continue our discussion from earlier on matrices Arrays, while useful, aren't theonly way to store and manipulate information. In fact, there are a multitude of differentways to store data in computer science including LinkedLists, Stacks, Queue's, Maps, Trees,and many others too. Ahora mismo; though, I'd like to talk about2 cool, wacky and zany ways to store data that we haven't previously covered: ArrayListsand dictionaries. Pero antes de entrar en eso, let's get a little review/reinforcementof array's. As you may remember, arrays are basicallylists of values that are stored together. When you initialize an array, you give ita size, and this size is fixed. No lo harás be able to increase the size of the array,so when you make an array, it's length is final. To access the values in an array, youreference them using an index which starts at 0. What this means is that the first itemof an array is not at position 1, it is at position 0, and it's position is commonlyreferred to as it's index location. Entonces, to find the nth item in an array, you wouldrefer to it as index location [n-1]. Sin embargo, as the size of an array is fixed, you haveto be careful to not reference a position that is beyond the total size of the array,or append too many items to it, as this will devolver un error We also have what are knownas two-dimensional arrays, which is an array containing an array at eachof its indexes. O podrías tener una matriz containing arrays containing arrays containingarrays containing arrays, depending one what estás tratando de hacer Multidimensional arrayscan be useful in more advanced programs for organizando un amplio volumen de valores relacionados.Si eso es confuso, pase de nuevo a earlier for our full discussion on Array's,the time-stamp will be in the description. Now that we've reviewed array's, let'sgo over array lists. Listas de matrices (o simplemente lists, in Python) can be thought of as a growingformación. Earlier, we mentioned how you have to be carefulto set an appropriate size of your array and make sure to only reference and append valuessuch that you remain within the size of the formación. However, with array lists, this isn'tun problema. Después de inicializar un arrayList, it instinctively has a size of 10, but ifyou append a values such that the size of the arrayList goes beyond 10 elements, anarrayList will “grow” itself, meaning that the computer will allocate more memoryto the array to increase its total size so que los nuevos valores se pueden agregar. Estais quite useful when you don't know the exact number of values that the array willneed to store, or want the ability to store values to your heart's content, such asmaking a database with an unknown amount of usuario que se registrará. There is a lot more to uncover when regardingarrayLists, but for this surface-level series, that is all you pretty much need to know,so let's move on to dictionaries. Now when we talk about dictionaries, we'renot referencing that thick book you probably have lying around your house which has thousandsof definitions. En informática, diccionarios are like arrays, in that they store multiplevalues, however their values are stored very diferentemente. Rather than being referencedby their position within the dictionary linearly, each value is tied to another value that isused to reference it, or its “key”. Porque of this, we need to throw away all conceptionsof dictionaries as a linear way of looking at data, since in actuality it is much morefluid and interchanging. Básicamente decimos that each position in a dictionary holds akey/value pair. Al hacer referencia a un valor en a dictionary, you will use it's unique key,and the dictionary will tell you the value eso está atado a eso. Think of it like this,each time you add an item to your dictionary, your computer creates a handcrafted box tostore the data, and also custom-makes a jeweled key, one of a kind, no other like it in themundo. De esta manera, solo hay una clave que goes to the box that stores a certain bitde información. Debido a que cada clave debe ser única, reusing a key in a dictionary will resultin an error being thrown because having two keys that are exactly the same would confusethe computer as to what box, or bit of information, esa clave lleva a. However, you can storethe same value in multiple key/value pairs, ya que las llaves serían todas diferentes. Now like I said, dictionaries are more fluid,making them easier to organize than arrays, as everything is set up in a more logicalconducta. Es decir, es más fácil de encontrar. the value you are looking for when you areusing keys rather than simply referencing sus posiciones Déjame explicarte lo que quiero decir.Imagine que tiene un diccionario de precios en a store where the key is the name of the productand the value is the price of the item. Tal vez apples cost 1 dollars, milk costs 2 dollars,and bread costs 3 dollars. Puedes ver eso in the dictionary, each key is the name ofa product, and each key corresponds to the precio de cada producto. So to find the priceof bread, all you need to do is simply call the dictionary using the key “bread”,and the dictionary would return the value 1. This makes it extremely easy to track valuesthrough your code since you're working with tangible values rather than numbers whichdon't mean anything to you. You can also manipulate dictionaries in manythe same ways you can manipulate arrays and listas de matrices. You can iterate through a dictionaryand perform many operations and comparisons en los valores. If you want to find the productwith the highest price, for example, you can iterate through the dictionary to find thevalue that is the highest amongst the grocery almacenar artículos Arrays, arraylists, and dictionaries are usefulin their own right, as are the mass amounts of other ways to store data, and each boastcertain advantages over one another. Nosotros ya covered the basics of 3, but since there areso many, we don't have time to go in-depth into each and every one of them, and so inorder to help you grasp the basics of storing information, we're now going to talk aboutone of the most important functions needed to understand arrays, which are searchingalgoritmos Now, just as there are many ways to storeinformation in computer science, there are incluso más formas de buscar en las listas.Los algoritmos de búsqueda en su núcleo son formas in which we can look through a list of valuesstored in an array, say a patient name list or a high score list, and find a particularpieza de datos. El objetivo de un algoritmo de búsqueda. is to simply give the algorithm a string orobject you want it to find and return the index of the array that contains that stringor object as fast as possible. Ahora esto puede seem simple, but lots of software runs onthe backbone of being able to search through lists extremely quickly, making searchingalgorithms, and in particular efficient searching algoritmos, un tema importante a cubrir. Adicionalmente,this is the main functionality that arrays are used for and is the backbone of many ofthe methods used with arrayLists as well as many other storage methods, so knowing themwill take you a very long way. Typically searching algorithms are used toreturn the index of a particular data point so that it can be used, modified, updatedor checked on. Por ejemplo, si estás a punto to check into a hospital run on an array systemfor patients, the staff must search for your name in the database and by returning theindex of where your name is, they now have a quantifiable number that they can use toeasily check you in, rent out prescriptions, schedule you for checkups, update your personalinformation, etc. without having to search a través de la lista para su nombre cada vez. You may think that there is little differencebetween searching algorithms, since computers nowadays can perform millions of calculationsper second, but when you're a huge multi-billion dollar corporation trying to find a certaindata point in a list containing thousands or even millions of data points, small differencesin efficiency are going to make or break the experiencia de usuario. Even a 1% improvement inefficiency can mean big differences in the amount of time a user is waiting for a simpletarea. Now before we jump into different types ofsearching algorithms, we must discern between the two states that arrays or lists can bein, either sorted or unsorted. Una lista ordenada of information is characterized by some sortof rankable value, whether that be a patient ID, credit card number, or even by alphabeticalvalues like username's or legal names. Un unsorted list is just some random assortmentof related information, not sorted by any orden particular o razón. Some searchingalgorithms only work for sorted lists, usually the more efficient ones, and some work forboth sorted and unsorted lists, although these son generalmente menos eficientes. If you end uppursuing computer science further, you will have to deal with both sorted and unsortedlists, so it's good to know common searching prácticas para ambos Another thing to note is that we determinethe efficiency of a searching algorithm based on both the worst case scenario and the averagenumber of items it must search. A esto le llamamos Big O notation, in which each searching algorithmhas an equation which takes in the size of the array as an integer n, and will outputan worst-case scenario efficiency value that we can use to compare with other searchingalgoritmos También podemos ver cuánto tiempo; on average, it takes to find an element ina list. El uso de estos dos métodos nos permite to easily compare how efficient two algorithmsson. Bien, ahora que tenemos algunos antecedentes en la búsqueda, vamos directamente a ello. The first type of search we'll be talkingabout is called a linear search and you've honestly probably used this multiple timesthroughout your life. Cada vez que tienes to search for your name on a list of peopleyou probably follow the same pattern. usted start at the top, check to see if the firstname on the list is yours, if it is. Excelente. If not, you move on to the next name on thelist until either you find your name, or you no, en cuyo caso te vas. A linearsearch works the same way, you start with the first element in the list, compare itto the value that you're trying to find, and if they're the same you've found yourmatch and return the index of that element, and if not you move on to the next elementin the list until you either find the thing you're searching for or you run out of listverificar. Parece bastante simple ¿verdad? Esta is because linear searches are pretty badwhen it comes to efficiency, especially in El peor de los casos. If the item you'researching for in the list is the last element, you're going to have to check the entirelist of items before you find the one you're buscando. De media; however, you'regoing to get it about halfway through the lista. This makes the linear search O(n) worst-casescenario, since in the worst possible case it will take the entire length of the array,or n, to find the correct value. El lineal search on average will return the correctindex in O(n/2) or halfway through the list. The linear search is great; however, sinceit can work with both sorted and unsorted lists, because of the fact that it will eventuallycover every element in the list. El otro search we'll cover requires the list tobe sorted which may seem like a drawback, but having a sorted list allows you to usealgorithms that are far more efficient than La búsqueda lineal. So overall, the linearsearch is a good basic searching algorithm for if you have an unsorted list, but if yourlist is sorted, there are way more efficient options out there for you, such as the binarysearch which we'll be talking about now. The binary search uses a recursive processto break the data in your list down into more and more manageable bytes, taking advantageof the fact that it's sorted, in order to encuentra el artículo que estás buscando más rápido.Este es mucho más difícil de entender alrededor, así que comencemos con un ejemplo. Vamossay you have a list of 10 names sorted alphabetically, like shown on the screen now, and you wantedto find your name within that list. En binario search you would first look for the middle-mostname, in this case the one at the 4th index. Just a quick aside, since there is no “true”middle, the computer automatically uses the el siguiente hacia abajo como el valor "medio". Ahora,once you find your middle value, you first check to see if the name you're searchingfor at the index you've chosen, if it is you simply return that index, but 99.9% ofthe time it's not including right now, so Avancemos. If the value at the middleindex is NOT equal to the one you're searching for, you check to see if the value you'researching comes before or after the middle índice. Por ejemplo, si estabas buscandothe name Brendan and the value at the middle el índice era Carl; Brendan obviously comes beforematthew alphabetically and since we know the list is sorted, what we can do now is ignorethe entire bottom half of the list and just focus on the top, since we know that if Brendanis even in the list, it's going to be in esa mitad superior Now, we simply treat the tophalf of the list as an entirely new entity y repita el proceso nuevamente. De nuevo,we would find the middle-most element of this new list of names and again compare it tothe name you're trying to find. Si es the name we're trying to find, we returnthat index, but if not we compare to see if Viene antes o después del índice medio.Volviendo a nuestro ejemplo, digamos el El índice medio de esta nueva lista es AJ. Ahora,we know that Brendan comes AFTER AJ alphabetically so we can now ignore the top half of the listsince we know that Brendan is going to be en la parte superior de nuestra lista. Now we repeat thisprocess again and again until we find the nombre que estamos buscando So for our example,the middle index this time is Brendan, and that's what we're searching for so wefinally would return index 2. In binary search, eventually the index we compare to our searchterm will be the same and once it is, we can devolver el índice y seguir adelante. Now if we don'tfind it, which happens after we have eliminated the entirety of the list without finding oursearch term, the algorithm will simply return a null value to let you know that the itemyou're searching for cannot be found in la lista. The binary search is way fasterand more efficient than the linear search since we are drastically cutting down theamount of elements we have to look at, making El programa corre más rápido. In almost 99.9% ofcases in which your list is sorted, the binary search is going to return a result fasterthan the linear search, so if you have a sorted lista, su mejor opción es ir binario. Comofor efficiency, the binary search is O(log n) for the worst case scenario which can beconfusing if you don't fully understand logarithms, but all you need to know is thatit is way more efficient than the linear search. It's average scenario is actually also O(logn) as well, which again is infinitely times Más eficiente que lineal. Now, while there are other types of searchingalgorithms you can use, these two are the most common for both unsorted and sorted lists,so we will stop there for now. A continuación, estamos going to be covering one of the most confusingand important topics in computer science, recursividad Let's start with the most important question:what exactly does recursion mean? En programación, recursion refers to functions that repeatedlycall themselves. Es decir, que en las instrucciones that occur within a function, one of the instructionswill be a call to that same function you're already in.In the extremely primitive exampleon your screen now, you can see we have some function which, in the confines of itself,calls itself. Una función recursiva generalmente take into account some integer as an argument,and will use this to carry out some instructions, modifying the integer that was entered, beforecalling itself again with that new integer como argumento To better understand these functions, let'sdiscuss the basics of how we go about programming one of these recursive functions and createone ourselves. Un muy buen ejemplo fácil of a recursive function is one which sumsall numbers from 1 to n, so let's make a función recursiva que hace justamente eso. losfirst thing we need is the actual function, and we're going to make it an integer functionwhich takes in an integer n as an argument. The reason we do this will be explained laterbut for now let's move on to the base case. A base case is simply a definite value whichall recursive statements, the ones that are being repeatedly called as we go through thefunction, try to get towards. Al principio of the function, we test the value that waspassed in by the argument against the base caso para ver si está satisfecho. Usually, thesebase cases are some requirements, like if n, as I described before, reaches a certainvalue or is equal to a certain value. It is extremely important that the base caseis set to some requirement that n will eventually meet for the same reason that it is importantto avoid infinite loop: we do not want a stack error de desbordamiento a ocurrir. For example, if ourbase case was to stop calling the recursive function when n was greater than 100, andif it is not, we call the function again but with n-1, and we started with n as 99, wewould never reach the base case and the recursive function will repeatedly call itself overand over and over again, subtracting 1 from n and hoping that somehow it will eventuallybe greater than 100 until your computer crashes, no es divertido. So anyways back to our recursivesum example, let's make our base case when n is less than or equal to 1. This way, wecan start at some positive integer n and subtract from it until it hits at or equal1, in which case we can exit the recursive declaración. Frio. Now, if n is not less thanor equal to 1, what we want to do is return the SUM of both n and then the returning valueof our recursiveSum method minus 1. Why do agregamos n + la llamada a la función? Bueno vamosactually go through the function as if we fueron la computadora y ver por qué. We start witha call of recursiveSum with n = 3. We know that 3 is not less than or equal to 1 so nowwe try to return a recursive sum of n (which is 3) and the returning value of recursiveSumwith an n of 2. We don't KNOW what the returning value ofrecursiveSum with an n of 2 is so we have to go through the function again, only thistime n is 2.Again n is not less than or equal to 1, and so this function will go into theelse statement and return…2 plus ANOTHER recursive statement, in this case the returningvalue of recursiveSum with an n of 1. So once again we have to go through the recursiveSumfunction to get the value that will be added to 2 and then returned and added to 3 andthen returned. Aguanta, estamos cerca. Now in this function, n IS less than or equalto 1 and so we return n, which is 1. Now we take that n, which is 1, and that iswhat gets added to 2 in the previous function call and then returned, so this would return3. Now this 3 is what gets added to the first function call, which is three, and so it becomesthree plus three which is 6. And FINALLY after all that time, we get 6 returned from thefunción. Que, si has estado siguiendo along at home, 3 + 2 + 1 is indeed 6. Nowthis may seem like a waste of time since 1 + 2 +3 no es una operación difícil. But to thoseof you saying that I ask you to please give me la suma de todos los números del 1 al 3,567.Buena suerte. Ahora la recursión es MUY difícil concept to wrap your head around, so if you'renot 100% comfortable with it at the moment, please rewatch this section of the lectureto better familiarize yourself with it. Alright cool, now that we have a little backgroundon recursion, let's talk about why it works muy bien. Now to understand why and how recursionworks, we must first understand what a stack es. A stack is a data structure that containsall of the tasks you instruct your program completar. Based on a certain method, yourprogram will then carry out the tasks you darle. It's called a stack because if we call startanother process before the previous one completes, the process is “stacked” on top of theother one such as the animation on your screen se muestra ahora.Los programas que escribimos seguirán la estructura LIFO. For those unfamiliar with accounting, LIFOmeans last in first out, or the last item put on the stack will be the first one removedde eso. Esencialmente, cada vez que le preguntas a tu computer to complete a task, that task isadded to the stack, and will be the first Uno para ser resuelto. Think of it like a stackof stones, you can keep adding stones on top of your pile, but in order to get to one nearthe bottom, you first have to remove all the rocas encima de ella. Now when your functioncontinually calls itself without end; sin a base case, like in our infinite loop examplethen the stack will never be resolved, as items will be continually added to the stackwithout any of them ever being completed. In this case, the memory allocated to thestack is exceeded, and a stack overflow error se produce, lo que provoca el bloqueo de su programa.Piensa en esto como si estuvieras haciendo tareas domésticas and before you complete one chore, you getcalled to do another chore, and then before you can complete that one you get called todo another one. Since you keep stacking tasks or chores ontop of each other, the stack of tasks will never be completed and you will probably diebefore ever finishing any of your chores. This is the same logic that makes infiniteloops crash your program. Obras de recursión en estos mismos principios. The initial callmakes a second call which is added to the stack, and now that one must be taken careof first, but in that one another function is called which gets added to the stack, andso on, until you reach the base case in which lentamente comienzas a bajar por la pila. In conclusion, recursion in general is extremelyuseful because by calling the same functions repeatedly it breaks down the problem intosmaller sections, and results in the program siendo más eficiente Small parts of problemsare easier to solve and less taxing to compute than the entire problem at once, and the computercan combine these small solutions into the Solución principal al final. Now as we wind down our introduction to programmingseries, we want to take some time and go over some of the soft skills needed to be a successfulcomputer scientist since it's not all about código escrito In fact, many professional computerscientists will tell you that the majority of their job is spent thinking about coderather than actually writing it. Esto es porque much of programming boils down to problemresolviendo ¿Cómo optimizamos este sistema, cómo ¿podemos hacer esta función para nuestra aplicación? Quétype of movement do we want for our game and ¿Cómo podemos programarlo? The harsh truth is that no good program hasever been written simply from the programmer getting the prompt or idea, sitting down,hopping on an IDE, and starting to write code. There are many tasks we should go throughbeforehand in order to plan out our code so we ensure that when the time comes to program,it's a clean and easy process, and not riddled with mistakes and bugs. This is where pseudocodeentra en juego. Think of pseudocode like this, if you wantedto take a family trip to the grand canyon, would you simply hop in your car and driveoff and figure things out later? No porque eso sería ridículo. Instead, you wouldspend some time planning out the trip, what sitios o lugares que quieres visitar? Quéhotel reservations are you going to have to ¿hacer? What kind of things are you going todo when you get there? Qué rutas o autopistas vas a tomar y por qué? Todos estosthings must be determined out before you can incluso piensa en saltar en tu Ford Explorer.Entonces, ¿cómo se traduce esto a pseudocódigo? Well, think of our family trip to the GrandCanyon as a program. Los programadores usan pseudocódigo, pseudo meaning not real, and code meaning,well, code, as a means to plan out their programs before they write them, just like how we plannedour trip before going. Tiran sintaxis and naming conventions for variables and justfocus on what they want the program to accomplish, y cómo planean hacer eso. Pseudocodeis very similar to constructing an outline para un papel que estás escribiendo. You write downthe main topics of the essay and plan out your major talking points, but you don'tworry about the nitty gritty details of it all such as word choice, grammar conventions,and proper formatting. Al hacer esto, permitimos ourselves to think freely and not worry aboutstressing the small stuff. Al menos no todavía. Alright, so now that we know WHAT pseudocodeis, let's talk about HOW we write pseudocode. You see, the best part about pseudocode isthat it can take the form of many different cosas para muchas personas diferentes. Each computerscientist probably has their own methodology for planning out their code, and since thereare probably hundreds of different methods of writing pseudocode that are out there,today I'd like to focus on 3 popular ones that I think you might find to be extremelyútil. The first of these are known as flowcharts,and mainly they can be used to think through El proceso de una función particular. A flowchartis fundamentally a graphical representation de una función y cómo podría fluir. Muchosprogrammers do this, and lay out the conditional statements and loops they want as differentblocks in the flow chart, connected by arrows y trazando cada camino de su función.A partir de ahí, es extremadamente fácil crear test cases and follow them throughout theflow of the function through the different Bloques y flechas. For example, we could havea flowchart that goes something like this. A user enters a number, and if this numberis 8, I want the program to return True; sin embargo, if the number is not 8 then I want to returnfalso. Es una excelente manera de visualizar qué the function's overall purpose is and alsolook for any errors that you may have missed when thinking about the function, such asa missing path. También abstrae la programación. statements up to simple blocks, making iteasier to modify or change completely. los best part is, that when you have finishedtesting cases you can simply convert the blocks into statements and you have a well-writtenfunction without any debugging. Another popular pseudocode technique thatis used often is to simply write out what quieres que tu código lo haga cronológicamente.No pienses necesariamente en qué programación statements and functions you want to use,just jot down, from start to finish, what it is the program you are writing is goingto do step by step. Por ejemplo, digamos you're making an app that takes in two numbersand divides them. El pseudocódigo para eso se vería un poco como esto. primeroI want to prompt the user to enter a number, then I want to wait for the user to inputthe first number. Después de obtener el primer número, I want to again prompt the user to input asecond number. Una vez que lo hacen, completo el operation by dividing the two numbers enteredand return the result back to the user. Esta all seems like it would be common sense, butremember that oftentimes we're not going to be working with simple multiplication functions,we may be working with full-scale games, algorithms, o interfaces de usuario con muchas opciones diferentes.Este método le permite al programador no get bogged down with the syntax and conventionsyou have to follow, you're simply making a note of what the program's ultimate goalshould be, as if you were explaining it to un amigo tuyo. This method really letsyou plan out everything that needs to happen en su programa para que funcione sin problemas.También asegura que no te olvides de un piece of an algorithm, or a certain functionthat you need to write in afterwards. And the final pseudocode strategy that I'dlike to talk about today is writing out the main features you want the user to have whenusing your program, and what functions or smaller programs you're going to need tocomplete those features. Hagamos otro example, say you're making a banking interfaceand on start-up, you want the user to initially Tiene 2 opciones diferentes. They can set upa new account or log into an existing account. From there, if they log into their accountyou then want them to have the functionality to withdraw money, deposit money, take outa loan, or pay back a loan. Si ellos deciden to set up a new account, you want them tobe able to create an account, store their information in a database, and then accessall of the features that a returning member tendría. This may look very similar tothe flowchart, the only difference being this is abstracted one level higher, over an entireprogram rather than just a single function. If you really wanted to, you could also createa flowchart that would go through the functionality de los 4 métodos descritos anteriormente. Settingup the hierarchy like seen on your screen now makes it clear to see every function andinterface you're going to have to make. This prevents you from having to try and shoehorna function or feature into an almost finished program at the last second is not a very funexperience in the slightest. So there you have it, 3 pseudocode strategiesyou can use to plan out your code before you incluso comenzar a escribir cualquiera. The flowchart method,which is good for thinking through the flow de una determinada función. The write-up method,which is good for getting the general idea down for a program, or the functionality planningmethod, good for listing out the functions of a certain program. You can use none ofthem, all of them, a mix of them, or even ignore estos y encuentre o cree el suyo propio.El objetivo principal aquí es minimizar drásticamente the amount of errors that occur during yourprogramming and relieve a lot of stress on tu cabeza. The importance of pseudocode cannotbe stressed enough, and if you don't believe me, I urge you to try and complete a largeproject without it. Ok, so if you've watched the series up untilthis point, you have gotten a pretty good understanding of many aspects of programming,and also how to plan out your programs. Ahora it's time to go out into the real world, andwrite some actual code. ¿Pero qué tipo de programa? I can hear you askingyo. Y la respuesta es realmente lo que quieras, De Verdad. As I'm sure you know by now, youcan program just about anything that you have on your mind, anything from simple games tocomplex software. Te hemos equipado con the basics that are going to be used in prettymuch any program you do decide to write. Pero that doesn't mean every programming languageis perfect for every application. Cada idioma has its own strengths and weaknesses, andchoosing the right one is very important for making it easier, or sometimes even just possible,for you to program what you want. Así que eso es what we are going to talk about now: choosingthe best language for what you want to accomplish. Now, we talked earlier about low level versushigh level programming languages. En caso te olvidaste, hagamos un repaso rápido.Los lenguajes de programación de nivel superior tienen un high level of abstraction from machine language,that series of 0's and 1's from way back when, while lower level programming languageshave a low level of abstraction from machine idioma. For example, block programming whereyou drag and drop programming statements together like 2d legos would be a high level language,as it does not take a high level of understanding of the inner workings of a computer to programeso. El nivel teórico más alto de una programación. language would be if I could just write downwhat I wanted the computer to do in simple Inglés y simplemente funcionaría. But, sadly,that doesn't exist yet. Por otro lado of the spectrum, the lowest level programminglanguage would be just feeding 0's and 1's into the computer at supersonic speed, whichwould be almost impossible and extremely absurd. So, how do you choose what type of languageis best for your needs? Bueno, depende de qué you are trying to do, as sometimes you needvery specialized languages to get done what usted quiere. The world of computer science isvast and contains many fields, so trying to cover everything in one language would beimposible. Esto ha llevado a la creación de thousands of different programming languageseach designed for a specific task. Ahora mismo though, we'll cover some of the most popularlanguages and their uses. Now, if you are trying to design a website,and delve into that career path, using HTML y CSS es probablemente tu mejor apuesta. HTML isa markup language that is designed for writing the content of a website, while CSS is greatfor designing the style of the website. usted interact with HTML code every day and youcan even see it right now if you right click and hit inspect element, this will truly showyou how complex HTML and CSS can be. Maybe it would be best for you to use a scriptingidioma. Un lenguaje de script es un lenguaje that has many commands for you to use andthat can also be run without needing to be compilado Scripts can be faster to write thanactual programs, and tend to be easier to port between operating systems allowing forcross-platform support. Los guiones también pueden ser used with websites, oftentimes adding to theoverall user experience of the site. Si tu want to go into web design, this might alsobe a path for you to go down. Examples of scripting languages are Perl, PHP, Ajax, andJavascript. If you just want to make a general purposeprogram, you should probably use a general lenguaje de propósito General purpose languages,as they sound, have a wide range of applications. Por lo general, estos deberían ser sus idiomas preferidos.Ejemplos de lenguajes de uso general son Java, C ++ y Python. They each have theirown different benefits over one another. Java is best at developing games and interactiveweb pages, Python can act as a scripting language for web programming as well as writing applicationsand data analysis. Y C ++ es mejor para escribir aplicaciones y programas del sistema. They allhave a variety of packages that you can import and use to achieve the functionality you needde ellos. Mientras selecciona el general correcto purpose language for your big projects isvery important, for most of your programs cualquiera de ellos funcionará. It really comesdown to preference. Conozca cada idioma and decide which one's syntax rules youlike best and find most comfortable. Si tu get to know one general purpose language reallywell and enjoy programming with it, you can apply it to just about any of the programsyou plan on writing. Personalmente, tiendo a uso Python para la mayoría de mis proyectos. Esto esmostly not due to any functional difference between Python and any other general purposelanguage, though there are a decent amount, but it is mainly because I find its syntaxrules most convenient and easiest to write programas con. Overall, either you can considerthe project you plan on doing, and research and see which language boasts the most advantagesfor your purposes, or you can simply become comfortable with a language and use it formost of the projects you decide to write. We'll now be looking at our final topicof this introduction to programming mini-series. You now have the knowledge of basic programmingwhich will take you far in any language you decide to learn, you know some good pre-programmingpseudocode strategies to help you design your code from the ground up, and you might alreadyhave a good idea as to the type of programming language you might want to start with, sowhat's the next step? ¿Cómo puedo aprender eso? language and what applications can it be used¿para? Bueno, eso es lo que vamos a ser. cubriendo ahora, así que saltemos directamente a eso. Starting with the biggest question which iswhat's the next step. Bueno, ahora que tu might know which type of language you mightbe interested in, research that language and find out whether or not you truly want topursue that programming language. La mayoría de los idiomas like python or C++ will have either an officialwebsite where you can read up on, or a wikipedia page which will provide you with useful informationin deciding whether or not you want to pursue ese camino From there, the next step is toactually learn the language, which can be hecho aquí mismo en YouTube. While we havetaught you the basics of any programming language, each specific language is going to expandupon the basic concepts and so watching tutorial videos on a certain language is going to bevery beneficial. Muchos sitios web intentarán get you to purchase paid courses or take classeswhich cost money, but you can find extremely good courses here on YouTube for absolutely0 cost to yourself. Yo comenzaría con un introduction series like the one you'recurrently watching, but for the language you have chosen and work your way through thatseries, picking up on the syntax and rules of that language until you become comfortablecon eso. Una vez que haces eso, llegas a una encrucijada.Sabes programar en un idioma determinado, but you may be completely clueless as to whatto make in that language. Programmer's block can leave you uninspired and not want to continueprogramming so I'd like to give you a few sitios para ayudar. First is codingbat, a completely free websitewhich has hundreds of coding challenges in Java and Python to help you refine your programmingskills and even learn some programming short-cuts y consejos This is great if you want to getbetter at improving your efficiency and need algo para perfeccionar tus habilidades como desarrollador.El siguiente es CoderByte, que ofrece más de 200+ challenges that you can complete in over 10different languages, something that is sure para ayudarte a mejorar. The final website I'dlike to talk about is hackerRank, which not only provides programming challenges to keepyou on your toes, but also provides support for using you programming skills to find jobsor internships, something you've probably definitely thought about if you are takingprogramming up as a skill. Estos y muchos more websites exist solely to keep you interestedin code and work on refining your skills to become better, you just have to find thembecause they're certainly out there. Now if you're a teenager watching this series,I also encourage you to take the programming clases en tu escuela secundaria. AP Computer SciencePrinciples and AP Computer Science A are both amazing courses which will help you greatlyin the future, and are also incredibly informative e importante para las universidades. Your school mightalso offer other classes in the field of computer science, including ones on data structures,game design, and data science. Todos y cada uno classes you can take to help expand your knowledgeof programming and help you find your niche va a ayudar tremendamente As you can see, the world of code has nowbeen opened up to you. Estos son sólo unos pocos examples of where you can go from here butthere are many more we didn't talk about. You can get into GitHub and start contributingto projects, you can work on your own projects and collaborate with others, the possibilitiesson infinitas El siguiente paso depende de usted. This concludes our introduction to programmingmine-series, we hope you enjoyed watching tanto como disfrutamos haciéndolo. Si tuenjoyed the series as a whole, consider subscribing to our channel NullPointerException, whichwill be linked in the description, for more contenido próximamente Gracias por ver.

Noticias relacionadas