Python

Download as xlsx, pdf, or txt
Download as xlsx, pdf, or txt
You are on page 1of 28

Notas python

#!/usr/bin/python3 Division (/) always returns a float. To do floor division


python3 <namefile.py> you can use the // operator; you can use %: to calcula
exit() control+d 5 ** 2 # 5 squared
Casting x = str(3) y = int(3) z = float(3) In interactive mode, the last printed expression is assi
print(r'C:\some\name') # note the r before the quote
listas [ ] se pueden modificar print("""\
tupla ( ) no se pueden modificar Strings can be concatenated (glued together) with the
print() imprime un linea >>> 3 * 'un' + 'ium'
The built-in function len() returns the length of a string: Strings can be indexed (subscripted), with the first cha
len(s) word = 'Pythonword[0] # character in position 0
diccionario {} word[-2] # second-last character
Note that since -0 is the same as 0, neg
word[0:2] # characters from position 0 (included) to 2
word[-2:] # characters from the second-last (included)
>>> word[:2] + word[2:]

python3 -m compileall -b $PYFILE In interactive mode, the last printed expression is assi
od -t x1
s returns a float. To do floor division and get an integer result (discarding any fractional result)
/ operator; you can use %: to calculate the remainder

de, the last printed expression is assigned to the variable _


ame') # note the r before the quote C:\some\name
""")
ncatenated (glued together) with the + operator, and repeated with *:
unununium'
dexed (subscripted), with the first character having index 0
rd[0] # character in position 0 P'
rd[-2] # second-last character o'
te that since -0 is the same as 0, negative indices start from -1.
acters from position 0 (included) to 2 (ex Py'
acters from the second-last (included) to on'
Python'

de, the last printed expression is assigned to the variable _


for variable in secuencia:
Iterando a través de una lista: Iteracion remplazada por anterior
my_list = [1, 2, 3, 4, 5] my_list = [1, 2, 3, 4, 5]
for num in my_list: for i in range(len(my_list)):
print(num) print(my_list[i])
Iterando a través de una cadena: Iterando con índices usando la función enumerate():
my_string = "Hello, World!" my_list = ["a", "b", "c"]
for char in my_string: for i, item in enumerate(my_list):
print(char) print(i, item)
Iterando a través de un rango de números: Iterando en orden inverso usando la función reversed():
for i in range(5): my_list = [1, 2, 3, 4, 5]
print(i) for num in reversed(my_list):
Iterando a través de un diccionario: print(num)
my_dict = {"a": 1, "b": 2, "c": Iterando sobre múltiples secuencias al mismo tiempo -función zip():
for key, value in my_dict.items(): names = ["Alice", "Bob", "Charlie"]
print(key, value) ages = [25, 30, 35]
for name, age in zip(names, ages):
print(name, age)
Iterando sobre un conjunto de valores únicos en un diccionario usando la función set() y el método values():
my_dict = {"a": 1, "b": 2, "c": 3, "d": 2}
for value in set(my_dict.values()):
print(value)
Iterando sobre los caracteres de una cadena en orden inverso usando el índice negativo:
my_string = "Hello, World!"
for i in range(len(my_string)-1, -1, -1):
print(my_string[i])

Iterando sobre los elementos de una lista mientras se realiza un seguimiento de la posición actual utilizando la func
my_list = [1, 2, 3, 4, 5]
for i, num in enumerate(my_list):
if i == 2:
continue
print(num)
Iterando hasta que se cumpla una condición usando la palabra clave break:
my_list = [1, 2, 3, 4, 5]
for num in my_list:
if num == 3:
break
print(num)
Iterando solo sobre elementos únicos usando la función set():
my_list = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
for num in set(my_list):
print(num)
Iterando sobre una lista de listas (anidada):
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for inner_list in my_list:
tiempo -función zip(): for item in inner_list:
print(item)
Iterando en incrementos usando la función range():
for i in range(0, 10, 2):
print(i)
el método values():

ón actual utilizando la función enumerate() y la palabra clave continue:


while condición:
# código a repetir mientras se cumpla la condición
i += 1 x += 3 i += 2 Validando la entrada del usuario hasta que se propo
print("¡Entrada válida!")
Sumando los números enteros positivos hasta un valor máximoUsando el ciclo while para implementar una pila sim
stack = []

max_value = 10 while True:


total = 0 user_input = input("Ingrese un elemento (o presio
i=1 if not user_input:
break
while i <= max_value: stack.append(user_input)
total += i
i += 1 while stack:
print(stack.pop())
print(total)

Adivinando un print("¡Adivinaste!")
número aleatorio generado por la computadora:
ada del usuario hasta que se proporcione un valor válido:
álida!")
while para implementar una pila simple:

put("Ingrese un elemento (o presione enter para salir): ")


ut:

user_input)

())
string.islower()true//false abs(number)
string1 = "hello world" print(string1.islower()) # True chr(number)
string2 = "Hello World" print(string2.islower()) # False El uso de i // 10 y i % 10 es una form
round() round(number, digits)digits - optional
113.0625 >>> round(_, 2) 113.06
range() iterate over a sequence of numbers
It generates arithmetic progressions:
type()
if __name__ == "__main__":
It Allows You to Execute Code When the File Runs as a Script,
but Not When It’s Imported as a Module
number = random.randint(-10, 10)
islower = __import__('7-islower').islower
print("a is {}".format("lower" if islower("a") else "upper"))
ord(c) Return the Unicode code point for a one-character string.
The function list() is another; it creates lists from iterables:
list(range(5)) [0, 1, 2, 3, 4]
map r = map(func, seq)
uso de i // 10 y i % 10 es una forma eficiente de obtener los dígitos de las decenas y unidades respectivamente. El operador //
ctivamente. El operador // realiza una división entera, devolviendo la parte entera del resultado, mientras que el operador % rea
ras que el operador % realiza una operación de módulo, devolviendo el residuo de la división.
Para instalar pyenv en Ubuntu, puede seguir los siguiente1. dependencias En Ubuntu, puedes actualiza
sudo apt-get install -y build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wg
2. Descargue e instale pyenv ejecutando los siguientes comandos Abre una terminal en tu siste
curl https://pyenv.run | bash
3. Configure su shell para que pyenv esté disponible en el terminal: Actualiza la lista de paquete
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bsudo apt-get update
echo 'eval "$(pyenv init --path)"' >> ~/.bashrc Luego, actualiza los paquete
exec "$SHELL"
ya instalado sudo apt-get upgrade
pyenv install --list Para verificar la versión actu
seleccione la version que desea instalar
pyenv install 3.11.0 python --version
Establezca la versión recién instalada de Python como la versión predeterminada en sSi la versión de Python es an
pyenv global 3.9.6
sudo apt-get install python3
En este caso, se instalará la
python3.9 --version
Después de la instalación, v
sudo rm /usr/bin/python ls -l /usr/bin/python*
sudo ln -s /usr/bin/python3.9 /usr/bin/python
sudo apt-get install --reinstall python3-apt

al instalar python me salio esta informacion , que significa? pyenv install 3.11.0 Downl
Este mensaje indica que ha instalado Python 3.11.0 utilizando el administrador de ver

La primera advertencia indica que la extensión "tkinter" de Python no se ha compilado


La segunda advertencia indica que la extensión "lzma" de Python no se ha compilado
En general, estas advertencias no deberían ser un problema para la mayoría de los us

lrwxrwxrwx 1 root root 16 mar 2 09:37 /usr/bin/python -> /usr/bin/python2


lrwxrwxrwx 1 root root 18 mar 2 09:31 /usr/bin/python2 -> /usr/bin/python2.7
lrwxrwxrwx 1 root root 19 mar 2 10:16 /usr/bin/python3 -> /usr/bin/python3.10
-rwxr-xr-x 1 root root 5921160 nov 14 11:10 /usr/bin/python3.10
lrwxrwxrwx 1 root root 34 nov 14 11:10 /usr/bin/python3.10-config -> x86_64-linux-gnu-python3.10
-rwxr-xr-x 1 root root 6890080 ago 12 2022 /usr/bin/python3.11
lrwxrwxrwx 1 root root 17 ago 18 2022 /usr/bin/python3-config -> python3.10-config
-rwxr-xr-x 1 root root 960 ene 25 03:29 /usr/bin/python3-futurize
-rwxr-xr-x 1 root root 964 ene 25 03:29 /usr/bin/python3-pasteurize
Ubuntu, puedes actualizar Python utilizando el administrador de paquetes apt-get. Para actualizar Python a la última versión,
dline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev python-openssl git
re una terminal en tu sistema Ubuntu.

tualiza la lista de paquetes disponibles en el repositorio usando el siguiente comando:

do apt-get update
ego, actualiza los paquetes instalados a la última versión disponible usando el siguiente comando:

do apt-get upgrade
ra verificar la versión actual de Python instalada en tu sistema, escribe el siguiente comando en la terminal:

hon --version
a versión de Python es anterior a la que deseas instalar, instala la versión más reciente usando el siguiente comando:

do apt-get install python3


este caso, se instalará la última versión de Python 3 disponible en el repositorio. Si deseas una versión específica, puedes ag

spués de la instalación, verifica la versión de Python nuevamente usando el comando "python --version". La nueva versión de

pyenv install 3.11.0 Downloading Python-3.11.0.tar.xz... -> https://www.python.org/ftp/python/3.11.0/Python-3.11.0.tar.xz Install


do el administrador de versiones de Python llamado "pyenv". Sin embargo, la instalación ha generado algunas advertencias y e

ython no se ha compilado y que puede faltar el toolkit Tk. La biblioteca Tk se utiliza para crear interfaces gráficas de usuario (G
ython no se ha compilado y que puede faltar la biblioteca lzma. La biblioteca lzma se utiliza para comprimir y descomprimir arc
para la mayoría de los usuarios, a menos que esté utilizando específicamente tkinter o la biblioteca lzma en su código de Pyth

6_64-linux-gnu-python3.10-config

n3.10-config
ython a la última versión, sigue estos pasos:
ma-dev python-openssl git

guiente comando:

ión específica, puedes agregar el número de versión después de "python3".

on". La nueva versión de Python debería aparecer.

ython-3.11.0.tar.xz Installing Python-3.11.0... Traceback (most recent call last): File "<string>", line 1, in <module> File "/home/
o algunas advertencias y errores:

ces gráficas de usuario (GUI) en Python. Si planea utilizar tkinter, puede instalar el paquete tk-dev o tcl-dev en su sistema ope
primir y descomprimir archivos en formato xz. Si planea utilizar la biblioteca lzma, puede instalar el paquete liblzma-dev en su
lzma en su código de Python. Si no planea utilizar estas bibliotecas, puede ignorar estas advertencias. Sin embargo, si necesit
in <module> File "/home/roaduque/.pyenv/versions/3.11.0/lib/python3.11/tkinter/__init__.py", line 38, in <module> import _tkin

tcl-dev en su sistema operativo y luego reinstalar Python.


aquete liblzma-dev en su sistema operativo y luego reinstalar Python.
s. Sin embargo, si necesita utilizar tkinter o lzma en su código de Python, deberá solucionar estos problemas.
in <module> import _tkinter # If this fails your Python may not be configured for Tk ^^^^^^^^^^^^^^^ ModuleNotFoundError: No
ModuleNotFoundError: No module named '_tkinter' WARNING: The Python tkinter extension was not compiled and GUI subsys
compiled and GUI subsystem has been detected. Missing the Tk toolkit? Traceback (most recent call last): File "<string>", line
last): File "<string>", line 1, in <module> File "/home/roaduque/.pyenv/versions/3.11.0/lib/python3.11/lzma.py", line 27, in <mod
/lzma.py", line 27, in <module> from _lzma import * ModuleNotFoundError: No module named '_lzma' WARNING: The Python l
WARNING: The Python lzma extension was not compiled. Missing the lzma lib? Installed Python-3.11.0 to /home/roaduque/.p
11.0 to /home/roaduque/.pyenv/versions/3.11.0
NamedTuple
es city:
una str
clase en el módulo typing de Pythonprint(p.city)
que se utiliza para crear
# Output: tuplas
"New York"con cam
A diferencia de una tupla normal, donde los elementos se acceden mediante índices
numéricos, en una NamedTuple los elementos se acceden mediante nombres.
p = Person("Jane", p.age, p.city) # Crea una nueva instancia de
Person con el nuevo valor para el campo name
alternos basicos
https://www.mygreatlearning.com/python/free-courses?p=3#subject-courses-section https://docs.python.org/3/tu
https://wiki.python.org/moin/BeginnersGuide/Programmers https://python.swaroopch.co
https://youtube.com/playlist?list=PLGLfVvz_LVvTn3cK5e6LjhgGiSeVlIRwt https://peps.python.org/pep
https://www.digitalocean.com
https://www.w3schools.com/python/ https://pyformat.info/

https://www.youtube.com/watch?v=DInMru2Eq6E
https://www.youtube.com/watch?v=6i3EGqOBRiU&list=PLdo5W4Nhv31bZSiqiOL5ta39vSnBxpOPT

https://www.youtube.com/redirect?event=video_description&redir_token=QUFFLUhqbWo5a0VoNy13cW9PR180WXd

https://realpython.com/ https://www.youtube.com/w
https://www.youtube.com/w
https://www.youtube.com/w

https://github.com/okeeffed/
instalacion
ps://docs.python.org/3/tutorial/index.html https://computingforgeeks.com/how-to-install-python-on-ubuntu-linux-s
ps://python.swaroopch.com/first_steps.html https://docs.python.org/3/tutorial/venv.html
ps://peps.python.org/pep-0008/
ps://www.digitalocean.com/community/tutorials/how-to-write-your-first-python-3-program
ps://pyformat.info/

5a0VoNy13cW9PR180WXdBS2MzcEx4eER4QXxBQ3Jtc0tsZ0swR2NFdkt5TDhoaWNwRFA3ZnVvYnZHcG5nVTBraC1IVE1pcFJaa3I3a

ps://www.youtube.com/watch?v=lvKKzSZUIHA&list=PLbu9W4c-C0iCW2IC2-WX-TLY4RoUiI6b_
ps://www.youtube.com/watch?v=2LWv9ezwYy4&list=PLei96ZX_m9sVd6GTQXBHrlbjsKENbc6tn
ps://www.youtube.com/watch?v=DWgzHbglNIo&list=PLsyeobzWxl7poL9JTVyndKe62ieoN-MZ3&index=7

ps://github.com/okeeffed/cheat-sheets/blob/master/Python-Data-Structures.md
-python-on-ubuntu-linux-system/

5nVTBraC1IVE1pcFJaa3I3aTBGaFZ2M2NyV0tvUGdLU1AxZGpMY3luOGFNVXRnaUJEMVJmTWZjTFZCbzI4U01aY2tfMFk5cmMwZjI1
4U01aY2tfMFk5cmMwZjI1RXItcTR6WUhEbw&q=https%3A%2F%2Fcalcur.tech%2Fpython-courses&v=QnRx6V8YQy0
QnRx6V8YQy0

You might also like