mirror of
https://github.com/Asabeneh/30-Days-Of-Python.git
synced 2026-06-03 21:02:42 +08:00
commit
bf54af9c6d
22
Spanish/01_Day_Introduction/helloworld.py
Normal file
22
Spanish/01_Day_Introduction/helloworld.py
Normal file
@ -0,0 +1,22 @@
|
||||
# Introducción
|
||||
# Día 1 - Desafío 30DaysOfPython
|
||||
|
||||
print(2 + 3) # suma(+)
|
||||
print(3 - 1) # resta(-)
|
||||
print(2 * 3) # multiplicación(*)
|
||||
print(3 / 2) # división(/)
|
||||
print(3 ** 2) # exponencial(**)
|
||||
print(3 % 2) # módulo(%)
|
||||
print(3 // 2) # División de piso(//)
|
||||
|
||||
# Comprobando los tipos de datos
|
||||
|
||||
print(type(10)) # Int
|
||||
print(type(3.14)) # Float
|
||||
print(type(1 + 3j)) # Complejo
|
||||
print(type('Asabeneh')) # Cadena
|
||||
print(type([1, 2, 3])) # Lista
|
||||
print(type({'name':'Asabeneh'})) # Diccionario
|
||||
print(type({9.8, 3.14, 2.7})) # Conjunto
|
||||
print(type((9.8, 3.14, 2.7))) # Tupla
|
||||
|
||||
@ -0,0 +1,300 @@
|
||||
<div align="center">
|
||||
<h1> 30 Dias de Python: Dia 2 - Variables, Funciones integradas</h1>
|
||||
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
|
||||
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
|
||||
</a>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Author:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Second Edition: July, 2021</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Dia 1](../readme.md) | [Dia 3 >>](../03_Day_Operators/03_operators.md)
|
||||
|
||||

|
||||
|
||||
- [📘 Día 2](#-día-2)
|
||||
- [Funciones integradas](#funciones-integradas)
|
||||
- [Variables](#variables)
|
||||
- [Declaración de múltiples variables en una línea](#declaración-de-múltiples-variables-en-una-línea)
|
||||
- [Tipos de datos](#tipos-de-datos)
|
||||
- [Comprobación de tipos de datos y conversión](#comprobación-de-tipos-de-datos-y-conversión)
|
||||
- [Números](#números)
|
||||
- [💻 Ejercicios - Día 2](#💻-ejercicios---día-2)
|
||||
- [Ejercicios: Nivel 1](#ejercicios-nivel-1)
|
||||
- [Ejercicios: Nivel 2](#ejercicios-nivel-2)
|
||||
|
||||
# 📘 Dia 2
|
||||
|
||||
## Funciones integradas
|
||||
|
||||
En Python tenemos muchas funciones integradas. Las funciones integradas están disponibles globalmente para su uso, lo que significa que puede hacer uso de las funciones integradas sin importarlas ni configurarlas. Algunas de las funciones integradas de Python más utilizadas son las siguientes: _print()_, _len()_, _type()_, _int()_, _float()_, _str()_, _input()_, _list()_, _dict()_, _min()_, _max()_, _sum()_, _sorted()_, _open()_, _file()_, _help()_ y _dir()_ . En la siguiente tabla, verá una lista exhaustiva de las funciones integradas de Python sacadas de la [documentación de Python](https://docs.python.org/3.9/library/functions.html).
|
||||
|
||||

|
||||
|
||||
Abramos el shell de Python y comencemos a usar algunas de las funciones integradas más comunes.
|
||||
|
||||

|
||||
|
||||
Practiquemos más usando diferentes funciones integradas
|
||||
|
||||

|
||||
|
||||
Como puede ver en la terminal de arriba, Python tiene palabras reservadas. No usamos palabras reservadas para declarar variables o funciones. En la siguiente sección cubriremos las variables.
|
||||
|
||||
Creo que a estas alturas ya está familiarizado con las funciones integradas. Hagamos una práctica más de funciones integradas y pasaremos a la siguiente sección.
|
||||
|
||||

|
||||
|
||||
## Variables
|
||||
|
||||
Las variables almacenan datos en la memoria de una computadora. Se recomienda el uso de variables mnemotécnicas en muchos lenguajes de programación. Una variable mnemotécnica es un nombre de variable que se puede recordar y asociar fácilmente. Una variable se refiere a una dirección de memoria en la que se almacenan los datos.
|
||||
Número al principio, carácter especial o guión no están permitidos al nombrar una variable. Una variable puede tener un nombre corto (como x, y, z), pero se recomienda enfáticamente un nombre más descriptivo (nombre, apellido, edad, país).
|
||||
|
||||
Reglas de nombres de variables de Python
|
||||
|
||||
- Un nombre de variable debe comenzar con una letra o el carácter de subrayado
|
||||
- Un nombre de variable no puede comenzar con un número
|
||||
- Un nombre de variable solo puede contener caracteres alfanuméricos y guiones bajos (A-z, 0-9 y \_)
|
||||
- Los nombres de las variables distinguen entre mayúsculas y minúsculas (firstname, Firstname, FirstName y FIRSTNAME) son variables diferentes)
|
||||
|
||||
Estos son algunos ejemplos de nombres de variables válidos:
|
||||
|
||||
```shell
|
||||
firstname
|
||||
lastname
|
||||
age
|
||||
country
|
||||
city
|
||||
first_name
|
||||
last_name
|
||||
capital_city
|
||||
_if # si queremos usar palabra reservada como variable
|
||||
year_2021
|
||||
year2021
|
||||
current_year_2021
|
||||
birth_year
|
||||
num1
|
||||
num2
|
||||
```
|
||||
|
||||
Nombres de variables no válidos
|
||||
|
||||
```shell
|
||||
first-name
|
||||
first@name
|
||||
first$name
|
||||
num-1
|
||||
1num
|
||||
```
|
||||
|
||||
Usaremos el estilo estándar de nomenclatura de variables de Python que ha sido adoptado por muchos desarrolladores de Python. Los desarrolladores de Python usan la convención de nomenclatura de variables de caja de serpiente (snake_case). Usamos un carácter de subrayado después de cada palabra para una variable que contiene más de una palabra (p. ej., nombre, apellido, velocidad de rotación del motor). El siguiente ejemplo es un ejemplo de nomenclatura estándar de variables, se requiere guión bajo cuando el nombre de la variable es más de una palabra.
|
||||
|
||||
Cuando asignamos un determinado tipo de datos a una variable, se llama declaración de variable. Por ejemplo, en el siguiente ejemplo, mi nombre se asigna a una variable first_name. El signo igual es un operador de asignación. Asignar significa almacenar datos en la variable. El signo igual en Python no es la igualdad como en Matemáticas.
|
||||
|
||||
_Ejemplo:_
|
||||
|
||||
```py
|
||||
# Variables en Python
|
||||
first_name = 'Asabeneh'
|
||||
last_name = 'Yetayeh'
|
||||
country = 'Finland'
|
||||
city = 'Helsinki'
|
||||
age = 250
|
||||
is_married = True
|
||||
skills = ['HTML', 'CSS', 'JS', 'React', 'Python']
|
||||
person_info = {
|
||||
'firstname':'Asabeneh',
|
||||
'lastname':'Yetayeh',
|
||||
'country':'Finland',
|
||||
'city':'Helsinki'
|
||||
}
|
||||
```
|
||||
|
||||
Usemos las funciones integradas _print()_ y _len()_. La función de impresión toma un número ilimitado de argumentos. Un argumento es un valor que se puede pasar o poner dentro del paréntesis de la función, vea el ejemplo a continuación.
|
||||
|
||||
**Ejemplo:**
|
||||
|
||||
```py
|
||||
print('Hello, World!') # El texto Hola, Mundo! es un argumento
|
||||
print('Hello',',', 'World','!') # Puede tomar varios argumentos, se han pasado cuatro argumentos
|
||||
print(len('Hello, World!')) # solo se necesita un argumento
|
||||
```
|
||||
|
||||
Imprimamos y también encontremos la longitud de las variables declaradas en la parte superior:
|
||||
|
||||
**Ejemplo:**
|
||||
|
||||
```py
|
||||
# Imprimiendo los valores almacenados en las variables
|
||||
|
||||
print('First name:', first_name)
|
||||
print('First name length:', len(first_name))
|
||||
print('Last name: ', last_name)
|
||||
print('Last name length: ', len(last_name))
|
||||
print('Country: ', country)
|
||||
print('City: ', city)
|
||||
print('Age: ', age)
|
||||
print('Married: ', is_married)
|
||||
print('Skills: ', skills)
|
||||
print('Person information: ', person_info)
|
||||
```
|
||||
|
||||
### Declaración de múltiples variables en una línea
|
||||
|
||||
También se pueden declarar múltiples variables en una línea:
|
||||
|
||||
**Ejemplo:**
|
||||
|
||||
```py
|
||||
first_name, last_name, country, age, is_married = 'Asabeneh', 'Yetayeh', 'Helsink', 250, True
|
||||
|
||||
print(first_name, last_name, country, age, is_married)
|
||||
print('First name:', first_name)
|
||||
print('Last name: ', last_name)
|
||||
print('Country: ', country)
|
||||
print('Age: ', age)
|
||||
print('Married: ', is_married)
|
||||
```
|
||||
|
||||
Obtener la entrada del usuario usando la función integrada _input()_. Asignemos los datos que obtenemos de un usuario a las variables first_name y age.
|
||||
**Ejemplo:**
|
||||
|
||||
```py
|
||||
first_name = input('What is your name: ')
|
||||
age = input('How old are you? ')
|
||||
|
||||
print(first_name)
|
||||
print(age)
|
||||
```
|
||||
|
||||
## Tipos de datos
|
||||
|
||||
Hay varios tipos de datos en Python. Para identificar el tipo de datos usamos la función incorporada _type_. Me gustaría pedirle que se concentre en comprender muy bien los diferentes tipos de datos. Cuando se trata de programar, todo se trata de tipos de datos. Introduje los tipos de datos desde el principio y viene de nuevo, porque todos los temas están relacionados con los tipos de datos. Cubriremos los tipos de datos con más detalle en sus respectivas secciones.
|
||||
|
||||
## Comprobación de tipos de datos y conversión
|
||||
|
||||
- Verificar tipos de datos: para verificar el tipo de datos de ciertos datos/variables usamos el _type_
|
||||
**Ejemplo:**
|
||||
|
||||
```py
|
||||
# Diferentes tipos de datos en python
|
||||
# Declaremos variables con varios tipos de datos
|
||||
|
||||
first_name = 'Asabeneh' # str
|
||||
last_name = 'Yetayeh' # str
|
||||
country = 'Finland' # str
|
||||
city= 'Helsinki' # str
|
||||
age = 250 # int, no es mi edad real, no te preocupes
|
||||
|
||||
# Imprimir tipos
|
||||
print(type('Asabeneh')) # str
|
||||
print(type(first_name)) # str
|
||||
print(type(10)) # int
|
||||
print(type(3.14)) # float
|
||||
print(type(1 + 1j)) # complex
|
||||
print(type(True)) # bool
|
||||
print(type([1, 2, 3, 4])) # list
|
||||
print(type({'name':'Asabeneh','age':250, 'is_married':250})) # dict
|
||||
print(type((1,2))) # tuple
|
||||
print(type(zip([1,2],[3,4]))) # set
|
||||
```
|
||||
|
||||
- Casting: Conversión de un tipo de dato a otro tipo de dato. Usamos _int()_, _float()_, _str()_, _list_, _set_
|
||||
Cuando hacemos operaciones aritméticas, los números de cadena deben convertirse primero a int o float; de lo contrario, devolverá un error. Si concatenamos un número con una cadena, el número debe convertirse primero en una cadena. Hablaremos sobre la concatenación en la sección String.
|
||||
|
||||
**Ejemplo:**
|
||||
|
||||
```py
|
||||
# int a float
|
||||
num_int = 10
|
||||
print('num_int',num_int) # 10
|
||||
num_float = float(num_int)
|
||||
print('num_float:', num_float) # 10.0
|
||||
|
||||
# float a int
|
||||
gravity = 9.81
|
||||
print(int(gravity)) # 9
|
||||
|
||||
# int a str
|
||||
num_int = 10
|
||||
print(num_int) # 10
|
||||
num_str = str(num_int)
|
||||
print(num_str) # '10'
|
||||
|
||||
# str a int o float
|
||||
num_str = '10.6'
|
||||
print('num_int', int(num_str)) # 10
|
||||
print('num_float', float(num_str)) # 10.6
|
||||
|
||||
# str a list
|
||||
first_name = 'Asabeneh'
|
||||
print(first_name) # 'Asabeneh'
|
||||
first_name_to_list = list(first_name)
|
||||
print(first_name_to_list) # ['A', 's', 'a', 'b', 'e', 'n', 'e', 'h']
|
||||
```
|
||||
|
||||
## Números
|
||||
|
||||
Tipos de datos numéricos en Python:
|
||||
|
||||
1. Integers: números enteros (negativos, cero y positivos)
|
||||
Ejemplo:
|
||||
... -3, -2, -1, 0, 1, 2, 3...
|
||||
|
||||
2. Floating: números de coma (números decimales)
|
||||
Ejemplo:
|
||||
... -3,5, -2,25, -1,0, 0,0, 1,1, 2,2, 3,5...
|
||||
|
||||
3. Complex: números complejos
|
||||
Ejemplo:
|
||||
1 + j, 2 + 4j, 1 - 1j
|
||||
|
||||
🌕 Eres increíble. Acaba de completar los desafíos del día 2 y está dos pasos por delante en su camino hacia la grandeza. Ahora haz algunos ejercicios para tu cerebro y tus músculos.
|
||||
|
||||
## 💻 Ejercicios - Día 2
|
||||
|
||||
### Ejercicios: Nivel 1
|
||||
|
||||
1. Dentro de 30DaysOfPython crea una carpeta llamada day_2. Dentro de esta carpeta crea un archivo llamado variables.py
|
||||
2. Escriba un comentario de python que diga 'Día 2: 30 días de programación en python'
|
||||
3. Declarar una variable de nombre y asignarle un valor
|
||||
4. Declarar una variable de apellido y asignarle un valor
|
||||
5. Declare una variable de nombre completo y asígnele un valor
|
||||
6. Declarar una variable de país y asignarle un valor
|
||||
7. Declarar una variable de ciudad y asignarle un valor
|
||||
8. Declarar una variable de edad y asignarle un valor
|
||||
9. Declarar una variable de año y asignarle un valor
|
||||
10. Declarar una variable is_married y asignarle un valor
|
||||
11. Declarar una variable is_true y asignarle un valor
|
||||
12. Declare una variable is_light_on y asígnele un valor
|
||||
13. Declarar múltiples variables en una línea
|
||||
|
||||
### Ejercicios: Nivel 2
|
||||
|
||||
1. Verifique el tipo de datos de todas sus variables usando la función incorporada type()
|
||||
1. Usando la función incorporada _len()_, encuentre la longitud de su nombre
|
||||
1. Compara la longitud de tu nombre y tu apellido
|
||||
1. Declarar 5 como num_one y 4 como num_two
|
||||
1. Sume num_one y num_two y asigne el valor a un total variable
|
||||
2. Reste num_two de num_one y asigne el valor a una variable diff
|
||||
3. Multiplique num_two y num_one y asigne el valor a un producto variable
|
||||
4. Divide num_one por num_two y asigna el valor a una división variable
|
||||
5. Use la división de módulo para encontrar num_two dividido por num_one y asigne el valor a un residuo variable
|
||||
6. Calcula num_one a la potencia de num_two y asigna el valor a una variable exp
|
||||
7. Encuentra la división de piso de num_one por num_two y asigna el valor a una variable floor_division
|
||||
1. El radio de un círculo es de 30 metros.
|
||||
1. Calcule el área de un círculo y asigne el valor a una variable con el nombre de _area_of_circle_
|
||||
2. Calcule la circunferencia de un círculo y asigne el valor a una variable con el nombre de _circum_of_circle_
|
||||
3. Tome el radio como entrada del usuario y calcule el área.
|
||||
1. Use la función de entrada integrada para obtener el nombre, el apellido, el país y la edad de un usuario y almacene el valor en sus nombres de variables correspondientes
|
||||
1. Ejecute la ayuda ('palabras clave') en el shell de Python o en su archivo para verificar las palabras o palabras clave reservadas de Python
|
||||
|
||||
🎉 ¡FELICITACIONES! 🎉
|
||||
|
||||
[<< Day 1](../readme.md) | [Day 3 >>](../03_Day_Operators/03_operators.md)
|
||||
40
Spanish/02_Day_Variables_builtin_functions/variables.py
Normal file
40
Spanish/02_Day_Variables_builtin_functions/variables.py
Normal file
@ -0,0 +1,40 @@
|
||||
|
||||
# Variables en Python
|
||||
|
||||
first_name = 'Asabeneh'
|
||||
last_name = 'Yetayeh'
|
||||
country = 'Finland'
|
||||
city = 'Helsinki'
|
||||
age = 250
|
||||
is_married = True
|
||||
skills = ['HTML', 'CSS', 'JS', 'React', 'Python']
|
||||
person_info = {
|
||||
'firstname':'Asabeneh',
|
||||
'lastname':'Yetayeh',
|
||||
'country':'Finland',
|
||||
'city':'Helsinki'
|
||||
}
|
||||
|
||||
# Imprimir los valores almacenados en las variables
|
||||
|
||||
print('First name:', first_name)
|
||||
print('First name length:', len(first_name))
|
||||
print('Last name: ', last_name)
|
||||
print('Last name length: ', len(last_name))
|
||||
print('Country: ', country)
|
||||
print('City: ', city)
|
||||
print('Age: ', age)
|
||||
print('Married: ', is_married)
|
||||
print('Skills: ', skills)
|
||||
print('Person information: ', person_info)
|
||||
|
||||
# Declarar múltiples variables en una línea
|
||||
|
||||
first_name, last_name, country, age, is_married = 'Asabeneh', 'Yetayeh', 'Helsink', 250, True
|
||||
|
||||
print(first_name, last_name, country, age, is_married)
|
||||
print('First name:', first_name)
|
||||
print('Last name: ', last_name)
|
||||
print('Country: ', country)
|
||||
print('Age: ', age)
|
||||
print('Married: ', is_married)
|
||||
316
Spanish/03_Day_Operators/03_operators.md
Normal file
316
Spanish/03_Day_Operators/03_operators.md
Normal file
@ -0,0 +1,316 @@
|
||||
<div align="center">
|
||||
<h1> 30 días de Python: Día 3 - Operadores</h1>
|
||||
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
|
||||
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
|
||||
</a>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Author:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Second Edition: July, 2021</small>
|
||||
</sub>
|
||||
</div>
|
||||
|
||||
[<< Dia 2](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) | [Dia 4 >>](../04_Day_Strings/04_strings.md)
|
||||
|
||||

|
||||
|
||||
- [📘 Día 3](#📘-día-3)
|
||||
- [Booleano](#booleano)
|
||||
- [Operadores](#operadores)
|
||||
- [Operadores de asignación](#operadores-de-asignación)
|
||||
- [Operadores aritméticos:](#operadores-aritméticos)
|
||||
- [Operadores de comparación](#operadores-de-comparación)
|
||||
- [Operadores lógicos](#operadores-lógicos)
|
||||
- [💻 Ejercicios - Día 3](#💻-ejercicios---día-3)
|
||||
|
||||
# 📘 Día 3
|
||||
|
||||
## Booleano
|
||||
|
||||
Un tipo de datos booleano representa uno de los dos valores: _Verdadero_ o _Falso_. El uso de estos tipos de datos quedará claro una vez que comencemos a usar el operador de comparación. La primera letra **T** para Verdadero y **F** para Falso debe ser en mayúscula a diferencia de JavaScript.
|
||||
**Ejemplo: valores booleanos**
|
||||
|
||||
```py
|
||||
print(True)
|
||||
print(False)
|
||||
```
|
||||
|
||||
## Operadores
|
||||
|
||||
Python language supports several types of operators. In this section, we will focus on few of them.
|
||||
|
||||
### Operadores de asignación
|
||||
|
||||
Los operadores de asignación se utilizan para asignar valores a las variables. Tomemos = como ejemplo. El signo igual en matemáticas muestra que dos valores son iguales, sin embargo, en Python significa que estamos almacenando un valor en una determinada variable y lo llamamos asignación o asignación de valor a una variable. La siguiente tabla muestra los diferentes tipos de operadores de asignación de Python, tomados de [w3school](https://www.w3schools.com/python/python_operators.asp).
|
||||
|
||||

|
||||
|
||||
### Operadores aritméticos:
|
||||
|
||||
- Suma (+): a + b
|
||||
- Resta(-): a - b
|
||||
- Multiplicación(*): a * b
|
||||
- División(/): a/b
|
||||
- Módulo(%): a % b
|
||||
- División de piso(//): a // b
|
||||
- Exponenciación(**): a ** b
|
||||
|
||||

|
||||
|
||||
**Ejemplo: Enteros**
|
||||
|
||||
```py
|
||||
# Operaciones aritméticas en Python
|
||||
# enteros
|
||||
|
||||
print('Addition: ', 1 + 2) # 3
|
||||
print('Subtraction: ', 2 - 1) # 1
|
||||
print('Multiplication: ', 2 * 3) # 6
|
||||
print ('Division: ', 4 / 2) # 2.0 La división en Python da un número flotante
|
||||
print('Division: ', 6 / 2) # 3.0
|
||||
print('Division: ', 7 / 2) # 3.5
|
||||
print('Division without the remainder: ', 7 // 2) # 3, da sin el número flotante o sin el resto
|
||||
print ('Division without the remainder: ',7 // 3) # 2
|
||||
print('Modulus: ', 3 % 2) # 1, da el resto
|
||||
print('Exponentiation: ', 2 ** 3) # 9 significa 2 * 2 * 2
|
||||
```
|
||||
|
||||
**Ejemplo: Floats**
|
||||
|
||||
```py
|
||||
# Números flotantes
|
||||
print('Floating Point Number, PI', 3.14)
|
||||
print('Floating Point Number, gravity', 9.81)
|
||||
```
|
||||
|
||||
**Ejemplo: Números complex**
|
||||
|
||||
```py
|
||||
# Números complejos
|
||||
print('Complex number: ', 1 + 1j)
|
||||
print('Multiplying complex numbers: ',(1 + 1j) * (1 - 1j))
|
||||
```
|
||||
|
||||
Declaremos una variable y asignemos un tipo de dato numérico. Voy a usar una variable de un solo carácter, pero recuerde que no desarrolle el hábito de declarar este tipo de variables. Los nombres de las variables deben ser siempre mnemotécnicos.
|
||||
|
||||
**Ejemplo:**
|
||||
|
||||
```python
|
||||
# Declarar la variable en la parte superior primero
|
||||
|
||||
a = 3 # a es un nombre de variable y 3 es un tipo de dato entero
|
||||
b = 2 # b es un nombre de variable y 3 es un tipo de dato entero
|
||||
|
||||
# Operaciones aritméticas y asignación del resultado a una variable
|
||||
total = a + b
|
||||
diff = a - b
|
||||
product = a * b
|
||||
division = a / b
|
||||
remainder = a % b
|
||||
floor_division = a // b
|
||||
exponential = a ** b
|
||||
|
||||
# Debería haber usado sum en lugar de total, pero sum es una función integrada; trate de evitar anular las funciones integradas
|
||||
print(total) # si no etiqueta su impresión con alguna cadena, nunca sabrá de dónde viene el resultado
|
||||
print('a + b = ', total)
|
||||
print('a - b = ', diff)
|
||||
print('a * b = ', product)
|
||||
print('a / b = ', division)
|
||||
print('a % b = ', remainder)
|
||||
print('a // b = ', floor_division)
|
||||
print('a ** b = ', exponentiation)
|
||||
```
|
||||
|
||||
**Ejemplo:**
|
||||
|
||||
```py
|
||||
print('== Addition, Subtraction, Multiplication, Division, Modulus ==')
|
||||
|
||||
# Declarar valores y organizarlos juntos
|
||||
num_one = 3
|
||||
num_two = 4
|
||||
|
||||
# Operaciones aritmeticas
|
||||
total = num_one + num_two
|
||||
diff = num_two - num_one
|
||||
product = num_one * num_two
|
||||
div = num_two / num_one
|
||||
remainder = num_two % num_one
|
||||
|
||||
# Imprimiendo valores con etiqueta
|
||||
print('total: ', total)
|
||||
print('difference: ', diff)
|
||||
print('product: ', product)
|
||||
print('division: ', div)
|
||||
print('remainder: ', remainder)
|
||||
```
|
||||
|
||||
Empecemos a conectar los puntos y empecemos a hacer uso de lo que ya sabemos para calcular (área, volumen, densidad, peso, perímetro, distancia, fuerza).
|
||||
|
||||
**Ejemplo:**
|
||||
```py
|
||||
# Cálculo del área de un círculo
|
||||
radius = 10 # radio de un circulo
|
||||
area_of_circle = 3.14 * radius ** 2 # dos signo * significa exponente o potencia
|
||||
print('Area of a circle:', area_of_circle)
|
||||
|
||||
# Calcular el área de un rectángulo
|
||||
length = 10
|
||||
width = 20
|
||||
area_of_rectangle = length * width
|
||||
print('Area of rectangle:', area_of_rectangle)
|
||||
|
||||
# Calcular el peso de un objeto
|
||||
mass = 75
|
||||
gravity = 9.81
|
||||
weight = mass * gravity
|
||||
print(weight, 'N') # Agregando unidad al peso
|
||||
|
||||
# Calcular la densidad de un líquido
|
||||
mass = 75 # en kg
|
||||
volume = 0.075 # en metros cúbicos
|
||||
density = mass / volume # 1000 Kg/m^3
|
||||
|
||||
```
|
||||
|
||||
### Operadores de comparación
|
||||
|
||||
En programación comparamos valores, usamos operadores de comparación para comparar dos valores. Comprobamos si un valor es mayor o menor o igual a otro valor. La siguiente tabla muestra los operadores de comparación de Python que se tomaron de [w3shool](https://www.w3schools.com/python/python_operators.asp).
|
||||
|
||||

|
||||
**Ejemplo: Operadores de comparación**
|
||||
|
||||
```py
|
||||
print(3 > 2) # True, porque 3 es mayor que 2
|
||||
print(3 >= 2) # True, porque 3 es mayor que 2
|
||||
print(3 < 2) # False, porque 3 es mayor que 2
|
||||
print(2 < 3) # True, porque 2 es menor que 3
|
||||
print(2 <= 3) # True, porque 2 es menor que 3
|
||||
print(3 == 2) # False, porque 3 no es igual a 2
|
||||
print(3 != 2) # True, porque 3 no es igual a 2
|
||||
print(len('mango') == len('avocado')) # False
|
||||
print(len('mango') != len('avocado')) # True
|
||||
print(len('mango') < len('avocado')) # True
|
||||
print(len('milk') != len('meat')) # False
|
||||
print(len('milk') == len('meat')) # True
|
||||
print(len('tomato') == len('potato')) # True
|
||||
print(len('python') > len('dragon')) # False
|
||||
|
||||
|
||||
# Comparar algo da un True o False
|
||||
|
||||
print('True == True: ', True == True)
|
||||
print('True == False: ', True == False)
|
||||
print('False == False:', False == False)
|
||||
```
|
||||
|
||||
Además del operador de comparación anterior, Python usa:
|
||||
|
||||
- _is_: Devuelve True si ambas variables son el mismo objeto (x es y)
|
||||
- _is not_: Devuelve True si ambas variables no son el mismo objeto (x no es y)
|
||||
- _in_: Devuelve True si la lista consultada contiene un elemento determinado (x en y)
|
||||
- _not in_: Devuelve True si la lista consultada no tiene un elemento determinado (x en y)
|
||||
|
||||
```py
|
||||
print('1 is 1', 1 is 1) # True - porque los valores de los datos son los mismos
|
||||
print('1 is not 2', 1 is not 2) # True - porque 1 no es 2
|
||||
print('A in Asabeneh', 'A' in 'Asabeneh') # True - A encontrado en la cadena
|
||||
print('B in Asabeneh', 'B' in 'Asabeneh') # False - no hay b mayúscula
|
||||
print('coding' in 'coding for all') # True - porque 'coding for all' tiene la palabra 'coding'
|
||||
print('a in an:', 'a' in 'an') # True
|
||||
print('4 is 2 ** 2:', 4 is 2 ** 2) # True
|
||||
```
|
||||
|
||||
### Operadores lógicos
|
||||
|
||||
A diferencia de otros lenguajes de programación, Python utiliza las palabras clave _and_, _or_ y _not_ para los operadores lógicos. Los operadores lógicos se utilizan para combinar sentencias condicionales:
|
||||
|
||||

|
||||
|
||||
```py
|
||||
print(3 > 2 and 4 > 3) # True - porque ambas afirmaciones son verdaderas
|
||||
print(3 > 2 and 4 < 3) # False - porque la segunda afirmación es falsa
|
||||
print(3 < 2 and 4 < 3) # False - porque ambas afirmaciones son falsas
|
||||
print('True and True: ', True and True)
|
||||
print(3 > 2 or 4 > 3) # True - porque ambas afirmaciones son verdaderas
|
||||
print(3 > 2 or 4 < 3) # True - porque una de las afirmaciones es verdadera
|
||||
print(3 < 2 or 4 < 3) # False - porque ambas afirmaciones son falsas
|
||||
print('True or False:', True or False)
|
||||
print(not 3 > 2) # False - porque 3 > 2 es verdadero, entonces no verdadero da falso
|
||||
print(not True) # False - Negación, el operador not devuelve verdadero a falso
|
||||
print(not False) # True
|
||||
print(not not True) # True
|
||||
print(not not False) # False
|
||||
|
||||
```
|
||||
|
||||
🌕 Tienes una energía ilimitada. Acaba de completar los desafíos del día 3 y está tres pasos por delante en su camino hacia la grandeza. Ahora haz algunos ejercicios para tu cerebro y tus músculos.
|
||||
|
||||
## 💻 Ejercicios - Día 3
|
||||
|
||||
1. Declara tu edad como variable entera
|
||||
2. Declara tu altura como una variable flotante
|
||||
3. Declarar una variable que almacene un número complejo
|
||||
4. Escriba un script que solicite al usuario que ingrese la base y la altura del triángulo y calcule el área de este triángulo (área = 0,5 x b x h).
|
||||
|
||||
```py
|
||||
Enter base: 20
|
||||
Enter height: 10
|
||||
The area of the triangle is 100
|
||||
```
|
||||
|
||||
5. Escriba un script que solicite al usuario que ingrese el lado a, el lado b y el lado c del triángulo. Calcula el perímetro del triángulo (perímetro = a + b + c).
|
||||
|
||||
```py
|
||||
Enter side a: 5
|
||||
Enter side b: 4
|
||||
Enter side c: 3
|
||||
The perimeter of the triangle is 12
|
||||
```
|
||||
|
||||
6. Obtenga la longitud y el ancho de un rectángulo usando el indicador. Calcula su área (área = largo x ancho) y perímetro (perímetro = 2 x (largo + ancho))
|
||||
7. Obtenga el radio de un círculo usando el aviso. Calcula el área (área = pi x r x r) y la circunferencia (c = 2 x pi x r) donde pi = 3,14.
|
||||
8. Calcular la pendiente, la intersección x y la intersección y de y = 2x -2
|
||||
9. La pendiente es (m = y2-y1/x2-x1). Encuentre la pendiente y la [distancia euclidiana](https://en.wikipedia.org/wiki/Euclidean_distance#:~:text=In%20mathematics%2C%20the%20Euclidean%20distance,being%20called%20the%20Pythagorean%20distance.) entre el punto (2, 2) y el punto (6,10)
|
||||
10. Compara las pendientes en las tareas 8 y 9.
|
||||
11. Calcula el valor de y (y = x^2 + 6x + 9). Trate de usar diferentes valores de x y descubra en qué valor de x y será 0.
|
||||
12. Encuentra la longitud de 'python' y 'dragon' y haz una declaración de comparación falsa.
|
||||
13. Use el operador _and_ para verificar si 'on' se encuentra tanto en 'python' como en 'dragon'
|
||||
14. _Espero que este curso no esté lleno de jerga_. Use el operador _in_ para verificar si _jerga_ está en la oración.
|
||||
15. No hay 'on' ni en dragón ni en pitón
|
||||
16. Encuentre la longitud del texto _python_ y convierta el valor en flotante y conviértalo en cadena
|
||||
17. Los números pares son divisibles por 2 y el resto es cero. ¿Cómo verifica si un número es par o no usando python?
|
||||
18. Verifique si la división de piso de 7 por 3 es igual al valor int convertido de 2.7.
|
||||
19. Comprueba si el tipo de '10' es igual al tipo de 10
|
||||
20. Comprueba si int('9.8') es igual a 10
|
||||
21. Escriba un script que solicite al usuario que ingrese las horas y la tarifa por hora. ¿Calcular el salario de la persona?
|
||||
|
||||
```py
|
||||
Enter hours: 40
|
||||
Enter rate per hour: 28
|
||||
Your weekly earning is 1120
|
||||
```
|
||||
|
||||
22. Escriba un script que le solicite al usuario que ingrese el número de años. Calcula el número de segundos que una persona puede vivir. Suponga que una persona puede vivir cien años.
|
||||
|
||||
```py
|
||||
Enter number of years you have lived: 100
|
||||
You have lived for 3153600000 seconds.
|
||||
```
|
||||
|
||||
23. Escriba un script de Python que muestre la siguiente tabla
|
||||
|
||||
```py
|
||||
1 1 1 1 1
|
||||
2 1 2 4 8
|
||||
3 1 3 9 27
|
||||
4 1 4 16 64
|
||||
5 1 5 25 125
|
||||
```
|
||||
|
||||
🎉 ¡FELICITACIONES! 🎉
|
||||
|
||||
[<< Day 2](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) | [Day 4 >>](../04_Day_Strings/04_strings.md)
|
||||
124
Spanish/03_Day_Operators/day-3.py
Normal file
124
Spanish/03_Day_Operators/day-3.py
Normal file
@ -0,0 +1,124 @@
|
||||
# Operaciones aritméticas en Python
|
||||
# Integers
|
||||
|
||||
print('Addition: ', 1 + 2)
|
||||
print('Subtraction: ', 2 - 1)
|
||||
print('Multiplication: ', 2 * 3)
|
||||
print ('Division: ', 4 / 2) # La división en python da un número flotante
|
||||
print('Division: ', 6 / 2)
|
||||
print('Division: ', 7 / 2)
|
||||
print('Division without the remainder: ', 7 // 2) # da sin el número flotante o sin el resto
|
||||
print('Modulus: ', 3 % 2) # Da el resto
|
||||
print ('Division without the remainder: ', 7 // 3)
|
||||
print('Exponential: ', 3 ** 2) # significa 3 * 3
|
||||
|
||||
# Números Floating
|
||||
print('Floating Number,PI', 3.14)
|
||||
print('Floating Number, gravity', 9.81)
|
||||
|
||||
# Números Complex
|
||||
print('Complex number: ', 1 + 1j)
|
||||
print('Multiplying complex number: ',(1 + 1j) * (1-1j))
|
||||
|
||||
# Declarar la variable en la parte superior primero
|
||||
|
||||
a = 3 # a es un nombre de variable y 3 es un tipo de dato entero
|
||||
b = 2 # b es un nombre de variable y 3 es un tipo de dato entero
|
||||
|
||||
# Operaciones aritméticas y asignación del resultado a una variable
|
||||
total = a + b
|
||||
diff = a - b
|
||||
product = a * b
|
||||
division = a / b
|
||||
remainder = a % b
|
||||
floor_division = a // b
|
||||
exponential = a ** b
|
||||
|
||||
# Debería haber usado sum en lugar de total, pero sum es una función integrada. Trate de evitar anular las funciones integradas.
|
||||
print(total) # si no etiqueta su impresión con alguna cadena, nunca sabrá de dónde viene el resultado
|
||||
print('a + b = ', total)
|
||||
print('a - b = ', diff)
|
||||
print('a * b = ', product)
|
||||
print('a / b = ', division)
|
||||
print('a % b = ', remainder)
|
||||
print('a // b = ', floor_division)
|
||||
print('a ** b = ', exponential)
|
||||
|
||||
# Declarar valores y organizarlos juntos
|
||||
num_one = 3
|
||||
num_two = 4
|
||||
|
||||
# Operaciones aritmeticas
|
||||
total = num_one + num_two
|
||||
diff = num_two - num_one
|
||||
product = num_one * num_two
|
||||
div = num_two / num_two
|
||||
remainder = num_two % num_one
|
||||
|
||||
# Imprimiendo valores con etiqueta
|
||||
print('total: ', total)
|
||||
print('difference: ', diff)
|
||||
print('product: ', product)
|
||||
print('division: ', div)
|
||||
print('remainder: ', remainder)
|
||||
|
||||
|
||||
# Cálculo del área de un círculo
|
||||
radius = 10 # radio de un circulo
|
||||
area_of_circle = 3.14 * radius ** 2 # dos * signo significa exponente o potencia
|
||||
print('Area of a circle:', area_of_circle)
|
||||
|
||||
# Calcular el área de un rectángulo
|
||||
length = 10
|
||||
width = 20
|
||||
area_of_rectangle = length * width
|
||||
print('Area of rectangle:', area_of_rectangle)
|
||||
|
||||
# Calcular el peso de un objeto
|
||||
mass = 75
|
||||
gravity = 9.81
|
||||
weight = mass * gravity
|
||||
print(weight, 'N')
|
||||
|
||||
print(3 > 2) # True, porque 3 es mayor que 2
|
||||
print(3 >= 2) # True, porque 3 es mayor que 2
|
||||
print(3 < 2) # False, porque 3 es mayor que 2
|
||||
print(2 < 3) # True, porque 2 es menor que 3
|
||||
print(2 <= 3) # True, porque 2 es menor que 3
|
||||
print(3 == 2) # False, porque 3 no es igual a 2
|
||||
print(3 != 2) # True, porque 3 no es igual a 2
|
||||
print(len('mango') == len('avocado')) # False
|
||||
print(len('mango') != len('avocado')) # True
|
||||
print(len('mango') < len('avocado')) # True
|
||||
print(len('milk') != len('meat')) # False
|
||||
print(len('milk') == len('meat')) # True
|
||||
print(len('tomato') == len('potato')) # True
|
||||
print(len('python') > len('dragon')) # False
|
||||
|
||||
# Comparación booleana
|
||||
print('True == True: ', True == True)
|
||||
print('True == False: ', True == False)
|
||||
print('False == False:', False == False)
|
||||
print('True and True: ', True and True)
|
||||
print('True or False:', True or False)
|
||||
|
||||
# Comparación de otra forma
|
||||
print('1 is 1', 1 is 1) # True - porque los valores de los datos son los mismos
|
||||
print('1 is not 2', 1 is not 2) # True - porque 1 no es 2
|
||||
print('A in Asabeneh', 'A' in 'Asabeneh') # True - A encontrado en la cadena
|
||||
print('B in Asabeneh', 'B' in 'Asabeneh') # False - no hay b mayúscula
|
||||
print('coding' in 'coding for all') # True - porque codificar para todos tiene la palabra codificar
|
||||
print('a in an:', 'a' in 'an') # True
|
||||
print('4 is 2 ** 2:', 4 is 2 ** 2) # True
|
||||
|
||||
print(3 > 2 and 4 > 3) # True - porque ambas afirmaciones son verdaderas
|
||||
print(3 > 2 and 4 < 3) # False - porque la segunda afirmación es falsa
|
||||
print(3 < 2 and 4 < 3) # False - porque ambas afirmaciones son falsas
|
||||
print(3 > 2 or 4 > 3) # True - porque ambas afirmaciones son verdaderas
|
||||
print(3 > 2 or 4 < 3) # True - porque uno de los enunciados es verdadero
|
||||
print(3 < 2 or 4 < 3) # False - porque ambas afirmaciones son falsas
|
||||
print(not 3 > 2) # False - porque 3 > 2 es verdadero, entonces not verdadero da falso
|
||||
print(not True) # False - Negación, el operador not devuelve verdadero a falso
|
||||
print(not False) # True
|
||||
print(not not True) # True
|
||||
print(not not False) # False
|
||||
457
Spanish/readme.md
Normal file
457
Spanish/readme.md
Normal file
@ -0,0 +1,457 @@
|
||||
# 🐍 30 Days Of Python
|
||||
|
||||
|# Day | Topics |
|
||||
|------|:---------------------------------------------------------:|
|
||||
| 01 | [Introducción](./readme.md)|
|
||||
| 02 | [Variables, funciones integradas](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md)|
|
||||
| 03 | [Operadores](./03_Day_Operators/03_operators.md)|
|
||||
| 04 | [Strings](./04_Day_Strings/04_strings.md)|
|
||||
| 05 | [Lists](./05_Day_Lists/05_lists.md)|
|
||||
| 06 | [Tuplas](./06_Day_Tuples/06_tuples.md)|
|
||||
| 07 | [Sets](./07_Day_Sets/07_sets.md)|
|
||||
| 08 | [Diccionarios](./08_Day_Dictionaries/08_dictionaries.md)|
|
||||
| 09 | [Condicionales](./09_Day_Conditionals/09_conditionals.md)|
|
||||
| 10 | [Bucles](./10_Day_Loops/10_loops.md)|
|
||||
| 11 | [Funciones](./11_Day_Functions/11_functions.md)|
|
||||
| 12 | [Módulos](./12_Day_Modules/12_modules.md)|
|
||||
| 13 | [Lista de comprensión](./13_Day_List_comprehension/13_list_comprehension.md)|
|
||||
| 14 | [Funciones de orden superior](./14_Day_Higher_order_functions/14_higher_order_functions.md)|
|
||||
| 15 | [Errores de tipo Python](./15_Day_Python_type_errors/15_python_type_errors.md)|
|
||||
| 16 | [Fecha y hora de Python](./16_Day_Python_date_time/16_python_datetime.md) |
|
||||
| 17 | [Manejo de excepciones](./17_Day_Exception_handling/17_exception_handling.md)|
|
||||
| 18 | [Expresiones regulares](./18_Day_Regular_expressions/18_regular_expressions.md)|
|
||||
| 19 | [Manejo de archivos](./19_Day_File_handling/19_file_handling.md)|
|
||||
| 20 | [Administrador de paquetes de Python](./20_Day_Python_package_manager/20_python_package_manager.md)|
|
||||
| 21 | [Clases y Objetos](./21_Day_Classes_and_objects/21_classes_and_objects.md)|
|
||||
| 22 | [Raspado web](./22_Day_Web_scraping/22_web_scraping.md)|
|
||||
| 23 | [Ambiente virtual](./23_Day_Virtual_environment/23_virtual_environment.md)|
|
||||
| 24 | [Estadísticas](./24_Day_Statistics/24_statistics.md)|
|
||||
| 25 | [Pandas](./25_Day_Pandas/25_pandas.md)|
|
||||
| 26 | [Python web](./26_Day_Python_web/26_python_web.md)|
|
||||
| 27 | [Python con MongoDB](./27_Day_Python_with_mongodb/27_python_with_mongodb.md)|
|
||||
| 28 | [API](./28_Day_API/28_API.md)|
|
||||
| 29 | [Building API](./29_Day_Building_API/29_building_API.md)|
|
||||
| 30 | [Conclusiones](./30_Day_Conclusions/30_conclusions.md)|
|
||||
|
||||
🧡🧡🧡 FELIZ CODIGO 🧡🧡🧡
|
||||
|
||||
<div>
|
||||
<small>Support the <strong>author</strong> to create more educational materials</small> <br />
|
||||
<a href = "https://www.paypal.me/asabeneh"><img src='./../images/paypal_lg.png' alt='Paypal Logo' style="width:10%"/></a>
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
<h1> 30 días de Python: Día 1 - Introducción</h1>
|
||||
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
|
||||
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
|
||||
</a>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Author:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Second Edition: July, 2021</small>
|
||||
</sub>
|
||||
</div>
|
||||
|
||||
[Dia 2 >>](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md)
|
||||
|
||||

|
||||
|
||||
- [🐍 30 Days Of Python](#-30-days-of-python)
|
||||
- [📘 Day 1](#-day-1)
|
||||
- [Welcome](#welcome)
|
||||
- [Introduction](#introduction)
|
||||
- [Why Python ?](#why-python-)
|
||||
- [Environment Setup](#environment-setup)
|
||||
- [Installing Python](#installing-python)
|
||||
- [Python Shell](#python-shell)
|
||||
- [Installing Visual Studio Code](#installing-visual-studio-code)
|
||||
- [How to use visual studio code](#how-to-use-visual-studio-code)
|
||||
- [Basic Python](#basic-python)
|
||||
- [Python Syntax](#python-syntax)
|
||||
- [Python Indentation](#python-indentation)
|
||||
- [Comments](#comments)
|
||||
- [Data types](#data-types)
|
||||
- [Number](#number)
|
||||
- [String](#string)
|
||||
- [Booleans](#booleans)
|
||||
- [List](#list)
|
||||
- [Dictionary](#dictionary)
|
||||
- [Tuple](#tuple)
|
||||
- [Set](#set)
|
||||
- [Checking Data types](#checking-data-types)
|
||||
- [Python File](#python-file)
|
||||
- [💻 Exercises - Day 1](#-exercises---day-1)
|
||||
- [Exercise: Level 1](#exercise-level-1)
|
||||
- [Exercise: Level 2](#exercise-level-2)
|
||||
- [Exercise: Level 3](#exercise-level-3)
|
||||
|
||||
# 📘 Day 1
|
||||
|
||||
## Welcome
|
||||
|
||||
**Congratulations** for deciding to participate in a _30 days of Python_ programming challenge . In this challenge you will learn everything you need to be a python programmer and the whole concept of programming. In the end of the challenge you will get a _30DaysOfPython_ programming challenge certificate.
|
||||
|
||||
If you would like to actively engage in the challenge, you may join the [30DaysOfPython challenge](https://t.me/ThirtyDaysOfPython) telegram group.
|
||||
|
||||
## Introduction
|
||||
|
||||
Python is a high-level programming language for general-purpose programming. It is an open source, interpreted, objected-oriented programming language. Python was created by a Dutch programmer, Guido van Rossum. The name of Python programming language was derived from a British sketch comedy series, _Monty Python's Flying Circus_. The first version was released on February 20, 1991. This 30 days of Python challenge will help you learn the latest version of Python, Python 3 step by step. The topics are broken down into 30 days, where each day contains several topics with easy-to-understand explanations, real-world examples, many hands on exercises and projects.
|
||||
|
||||
This challenge is designed for beginners and professionals who want to learn python programming language. It may take 30 to 100 days to complete the challenge, people who actively participate on the telegram group have a high probability of completing the challenge.
|
||||
|
||||
This challenge is easy to read, written in conversational English, engaging, motivating and at the same time, it is very demanding. You need to allocate much time to finish this challenge. If you are a visual learner, you may get the video lesson on <a href="https://www.youtube.com/channel/UC7PNRuno1rzYPb1xLa4yktw"> Washera</a> YouTube channel. You may start from [Python for Absolute Beginners video](https://youtu.be/OCCWZheOesI). Subscribe the channel, comment and ask questions on YouTube vidoes and be proactive, the author will eventually notice you.
|
||||
|
||||
The author likes to hear your opinion about the challenge, share the author by expressing your thoughts about the 30DaysOfPython challenge. You can leave your testimonial on this [link](https://testimonial-vdzd.onrender.com/)
|
||||
|
||||
## Why Python ?
|
||||
|
||||
It is a programming language which is very close to human language and because of that it is easy to learn and use.
|
||||
Python is used by various industries and companies (including Google). It has been used to develop web applications, desktop applications, system adminstration, and machine learning libraries. Python is highly embraced language in the data science and machine learning community. I hope this is enough to convince you to start learning Python. Python is eating the world and you are killing it before it eats you.
|
||||
|
||||
## Environment Setup
|
||||
|
||||
### Installing Python
|
||||
|
||||
To run a python script you need to install python. Let's [download](https://www.python.org/) python.
|
||||
If your are a windows user. Click the button encircled in red.
|
||||
|
||||
[](https://www.python.org/)
|
||||
|
||||
If you are a macOS user. Click the button encircled in red.
|
||||
|
||||
[](https://www.python.org/)
|
||||
|
||||
To check if python is installed write the following command on your device terminal.
|
||||
|
||||
```shell
|
||||
python --version
|
||||
```
|
||||
|
||||

|
||||
|
||||
As you can see from the terminal, I am using _Python 3.7.5_ version at the moment. Your version of Python might be different from mine by but it should be 3.6 or above. If you mange to see the python version, well done. Python has been installed on your machine. Continue to the next section.
|
||||
|
||||
### Python Shell
|
||||
|
||||
Python is an interpreted scripting language, so it does not need to be compiled. It means it executes the code line by line. Python comes with a _Python Shell (Python Interactive Shell)_. It is used to execute a single python command and get the result.
|
||||
|
||||
Python Shell waits for the Python code from the user. When you enter the code, it interprets the code and shows the result in the next line.
|
||||
Open your terminal or command prompt(cmd) and write:
|
||||
|
||||
```shell
|
||||
python
|
||||
```
|
||||
|
||||

|
||||
|
||||
The Python interactive shell is opened and it is waiting for you to write Python code(Python script). You will write your Python script next to this symbol >>> and then click Enter.
|
||||
Let us write our very first script on the Python scripting shell.
|
||||
|
||||

|
||||
|
||||
Well done, you wrote your first Python script on Python interactive shell. How do we close the Python interactive shell ?
|
||||
To close the shell, next to this symbol >> write **exit()** command and press Enter.
|
||||
|
||||

|
||||
|
||||
Now, you know how to open the Python interactive shell and how to exit from it.
|
||||
|
||||
Python will give you results if you write scripts that Python understands, if not it returns errors. Let's make a deliberate mistake and see what Python will return.
|
||||
|
||||

|
||||
|
||||
As you can see from the returned error, Python is so clever that it knows the mistake we made and which was _Syntax Error: invalid syntax_. Using x as multiplication in Python is a syntax error because (x) is not a valid syntax in Python. Instead of (**x**) we use asterisk (*) for multiplication. The returned error clearly shows what to fix.
|
||||
|
||||
The process of identifying and removing errors from a program is called _debugging_. Let us debug it by putting * in place of **x**.
|
||||
|
||||

|
||||
|
||||
Our bug was fixed, the code ran and we got a result we were expecting. As a programmer you will see such kind of errors on daily basis. It is good to know how to debug. To be good at debugging you should understand what kind of errors you are facing. Some of the Python errors you may encounter are _SyntaxError_, _IndexError_, _NameError_, _ModuleNotFoundError_, _KeyError_, _ImportError_, _AttributeError_, _TypeError_, _ValueError_, _ZeroDivisionError_ etc. We will see more about different Python **_error types_** in later sections.
|
||||
|
||||
Let us practice more how to use Python interactive shell. Go to your terminal or command prompt and write the word **python**.
|
||||
|
||||

|
||||
|
||||
The Python interactive shell is opened. Let us do some basic mathematical operations (addition, subtraction, multiplication, division, modulus, exponential).
|
||||
|
||||
Let us do some maths first before we write any Python code:
|
||||
|
||||
- 2 + 3 is 5
|
||||
- 3 - 2 is 1
|
||||
- 3 \* 2 is 6
|
||||
- 3 / 2 is 1.5
|
||||
- 3 ** 2 is the same as 3 * 3
|
||||
|
||||
In python we have the following additional operations:
|
||||
|
||||
- 3 % 2 = 1 => which means finding the remainder
|
||||
- 3 // 2 = 1 => which means removing the remainder
|
||||
|
||||
Let us change the above mathematical expressions to Python code. The Python shell has been opened and let us write a comment at the very beginning of the shell.
|
||||
|
||||
A _comment_ is a part of the code which is not executed by python. So we can leave some text in our code to make our code more readable. Python does not run the comment part. A comment in python starts with hash(#) symbol.
|
||||
This is how you write a comment in python
|
||||
|
||||
```shell
|
||||
# comment starts with hash
|
||||
# this is a python comment, because it starts with a (#) symbol
|
||||
```
|
||||
|
||||

|
||||
|
||||
Before we move on to the next section, let us practice more on the Python interactive shell. Close the opened shell by writing _exit()_ on the shell and open it again and let us practice how to write text on the Python shell.
|
||||
|
||||

|
||||
|
||||
### Installing Visual Studio Code
|
||||
|
||||
The Python interactive shell is good to try and test small script codes but it will not be for a big project. In real work environment, developers use different code editors to write codes. In this 30 days of Python programming challenge we will use visual studio code. Visual studio code is a very popular open source text editor. I am a fan of vscode and I would recommend to [download](https://code.visualstudio.com/) visual studio code, but if you are in favor of other editors, feel free to follow with what you have.
|
||||
|
||||
[](https://code.visualstudio.com/)
|
||||
|
||||
If you installed visual studio code, let us see how to use it.
|
||||
If you prefer a video, you can follow this Visual Studio Code for Python [Video tutorial](https://www.youtube.com/watch?v=bn7Cx4z-vSo)
|
||||
|
||||
#### How to use visual studio code
|
||||
|
||||
Open the visual studio code by double clicking the visual studio icon. When you open it you will get this kind of interface. Try to interact with the labeled icons.
|
||||
|
||||

|
||||
|
||||
Create a folder named 30DaysOfPython on your desktop. Then open it using visual studio code.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
After opening it you will see shortcuts for creating files and folders inside of 30DaysOfPython project's directory. As you can see below, I have created the very first file, helloworld.py. You can do the same.
|
||||
|
||||

|
||||
|
||||
After a long day of coding, you want to close your code editor, right? This is how you will close the opened project.
|
||||
|
||||

|
||||
|
||||
Congratulations, you have finished setting up the development environment. Let us start coding.
|
||||
|
||||
## Basic Python
|
||||
|
||||
### Python Syntax
|
||||
|
||||
A Python script can be written in Python interactive shell or in the code editor. A Python file has an extension .py.
|
||||
|
||||
### Python Indentation
|
||||
|
||||
An indentation is a white space in a text. Indentation in many languages is used to increase code readability, however Python uses indentation to create block of codes. In other programming languages curly brackets are used to create blocks of codes instead of indentation. One of the common bugs when writing python code is wrong indentation.
|
||||
|
||||

|
||||
|
||||
### Comments
|
||||
|
||||
Comments are very important to make the code more readable and to leave remarks in our code. Python does not run comment parts of our code.
|
||||
Any text starting with hash(#) in Python is a comment.
|
||||
|
||||
**Example: Single Line Comment**
|
||||
|
||||
```shell
|
||||
# This is the first comment
|
||||
# This is the second comment
|
||||
# Python is eating the world
|
||||
```
|
||||
|
||||
**Example: Multiline Comment**
|
||||
|
||||
Triple quote can be used for multiline comment if it is not assigned to a variable
|
||||
|
||||
```shell
|
||||
"""This is multiline comment
|
||||
multiline comment takes multiple lines.
|
||||
python is eating the world
|
||||
"""
|
||||
```
|
||||
|
||||
### Data types
|
||||
|
||||
In Python there are several types of data types. Let us get started with the most common ones. Different data types will be covered in detail in other sections. For the time being, let us just go through the different data types and get familiar with them. You do not have to have a clear understanding now.
|
||||
|
||||
#### Number
|
||||
|
||||
- Integer: Integer(negative, zero and positive) numbers
|
||||
Example:
|
||||
... -3, -2, -1, 0, 1, 2, 3 ...
|
||||
- Float: Decimal number
|
||||
Example
|
||||
... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ...
|
||||
- Complex
|
||||
Example
|
||||
1 + j, 2 + 4j
|
||||
|
||||
#### String
|
||||
|
||||
A collection of one or more characters under a single or double quote. If a string is more than one sentence then we use a triple quote.
|
||||
|
||||
**Example:**
|
||||
|
||||
```py
|
||||
'Asabeneh'
|
||||
'Finland'
|
||||
'Python'
|
||||
'I love teaching'
|
||||
'I hope you are enjoying the first day of 30DaysOfPython Challenge'
|
||||
```
|
||||
|
||||
#### Booleans
|
||||
|
||||
A boolean data type is either a True or False value. T and F should be always uppercase.
|
||||
|
||||
**Example:**
|
||||
|
||||
```python
|
||||
True # Is the light on? If it is on, then the value is True
|
||||
False # Is the light on? If it is off, then the value is False
|
||||
```
|
||||
|
||||
#### List
|
||||
|
||||
Python list is an ordered collection which allows to store different data type items. A list is similar to an array in JavaScript.
|
||||
|
||||
**Example:**
|
||||
|
||||
```py
|
||||
[0, 1, 2, 3, 4, 5] # all are the same data types - a list of numbers
|
||||
['Banana', 'Orange', 'Mango', 'Avocado'] # all the same data types - a list of strings (fruits)
|
||||
['Finland','Estonia', 'Sweden','Norway'] # all the same data types - a list of strings (countries)
|
||||
['Banana', 10, False, 9.81] # different data types in the list - string, integer, boolean and float
|
||||
```
|
||||
|
||||
#### Dictionary
|
||||
|
||||
A Python dictionary object is an unordered collection of data in a key value pair format.
|
||||
|
||||
**Example:**
|
||||
|
||||
```py
|
||||
{
|
||||
'first_name':'Asabeneh',
|
||||
'last_name':'Yetayeh',
|
||||
'country':'Finland',
|
||||
'age':250,
|
||||
'is_married':True,
|
||||
'skills':['JS', 'React', 'Node', 'Python']
|
||||
}
|
||||
```
|
||||
|
||||
#### Tuple
|
||||
|
||||
A tuple is an ordered collection of different data types like list but tuples can not be modified once they are created. They are immutable.
|
||||
|
||||
**Example:**
|
||||
|
||||
```py
|
||||
('Asabeneh', 'Pawel', 'Brook', 'Abraham', 'Lidiya') # Names
|
||||
```
|
||||
|
||||
```py
|
||||
('Earth', 'Jupiter', 'Neptune', 'Mars', 'Venus', 'Saturn', 'Uranus', 'Mercury') # planets
|
||||
```
|
||||
|
||||
#### Set
|
||||
|
||||
A set is a collection of data types similar to list and tuple. Unlike list and tuple, set is not an ordered collection of items. Like in Mathematics, set in Python stores only unique items.
|
||||
|
||||
In later sections, we will go in detail about each and every Python data type.
|
||||
|
||||
**Example:**
|
||||
|
||||
```py
|
||||
{2, 4, 3, 5}
|
||||
{3.14, 9.81, 2.7} # order is not important in set
|
||||
```
|
||||
|
||||
### Checking Data types
|
||||
|
||||
To check the data type of certain data/variable we use the **type** function. In the following terminal you will see different python data types:
|
||||
|
||||

|
||||
|
||||
### Python File
|
||||
|
||||
First open your project folder, 30DaysOfPython. If you don't have this folder, create a folder name called 30DaysOfPython. Inside this folder, create a file called helloworld.py. Now, let's do what we did on python interactive shell using visual studio code.
|
||||
|
||||
The Python interactive shell was printing without using **print** but on visual studio code to see our result we should use a built in function _print(). The _print()_ built-in function takes one or more arguments as follows _print('arument1', 'argument2', 'argument3')_. See the examples below.
|
||||
|
||||
**Example:**
|
||||
|
||||
The file name is helloworld.py
|
||||
|
||||
```py
|
||||
# Day 1 - 30DaysOfPython Challenge
|
||||
|
||||
print(2 + 3) # addition(+)
|
||||
print(3 - 1) # subtraction(-)
|
||||
print(2 * 3) # multiplication(*)
|
||||
print(3 / 2) # division(/)
|
||||
print(3 ** 2) # exponential(**)
|
||||
print(3 % 2) # modulus(%)
|
||||
print(3 // 2) # Floor division operator(//)
|
||||
|
||||
# Checking data types
|
||||
print(type(10)) # Int
|
||||
print(type(3.14)) # Float
|
||||
print(type(1 + 3j)) # Complex number
|
||||
print(type('Asabeneh')) # String
|
||||
print(type([1, 2, 3])) # List
|
||||
print(type({'name':'Asabeneh'})) # Dictionary
|
||||
print(type({9.8, 3.14, 2.7})) # Set
|
||||
print(type((9.8, 3.14, 2.7))) # Tuple
|
||||
```
|
||||
|
||||
To run the python file check the image below. You can run the python file either by running the green button on Visual Studio Code or by typing _python helloworld.py_ in the terminal .
|
||||
|
||||

|
||||
|
||||
🌕 You are amazing. You have just completed day 1 challenge and you are on your way to greatness. Now do some exercises for your brain and muscles.
|
||||
|
||||
## 💻 Exercises - Day 1
|
||||
|
||||
### Exercise: Level 1
|
||||
|
||||
1. Check the python version you are using
|
||||
2. Open the python interactive shell and do the following operations. The operands are 3 and 4.
|
||||
- addition(+)
|
||||
- subtraction(-)
|
||||
- multiplication(\*)
|
||||
- modulus(%)
|
||||
- division(/)
|
||||
- exponential(\*\*)
|
||||
- floor division operator(//)
|
||||
3. Write strings on the python interactive shell. The strings are the following:
|
||||
- Your name
|
||||
- Your family name
|
||||
- Your country
|
||||
- I am enjoying 30 days of python
|
||||
4. Check the data types of the following data:
|
||||
- 10
|
||||
- 9.8
|
||||
- 3.14
|
||||
- 4 - 4j
|
||||
- ['Asabeneh', 'Python', 'Finland']
|
||||
- Your name
|
||||
- Your family name
|
||||
- Your country
|
||||
|
||||
### Exercise: Level 2
|
||||
|
||||
1. Create a folder named day_1 inside 30DaysOfPython folder. Inside day_1 folder, create a python file helloworld.py and repeat questions 1, 2, 3 and 4. Remember to use _print()_ when you are working on a python file. Navigate to the directory where you have saved your file, and run it.
|
||||
|
||||
### Exercise: Level 3
|
||||
|
||||
1. Write an example for different Python data types such as Number(Integer, Float, Complex), String, Boolean, List, Tuple, Set and Dictionary.
|
||||
2. Find an [Euclidian distance](https://en.wikipedia.org/wiki/Euclidean_distance#:~:text=In%20mathematics%2C%20the%20Euclidean%20distance,being%20called%20the%20Pythagorean%20distance.) between (2, 3) and (10, 8)
|
||||
|
||||
🎉 CONGRATULATIONS ! 🎉
|
||||
|
||||
[Day 2 >>](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md)
|
||||
Loading…
Reference in New Issue
Block a user