Este tutorial le enseñará cómo imprimir varias estrellas y patrones alfabéticos en Python. Explore estos programas de patrones en Python y aprenda cómo funcionan los bucles for anidados. Si está buscando algunos de los mejores libros de Python, no olvide consultar esta lista.
Parte 1: Programas estrella en Python
1. Programa modelo piramidal
# This program prints a pyramid pattern using a for loop # Use a for loop to iterate over the number of rows in the pattern for row in range(1, 6): # Use another for loop to print the number of spaces in each row for space in range(5 - row): print(" ", end="") # Use another for loop to print the number of stars in each row for star in range(2 * row - 1): print("*", end="") # After each row, print a newline character print()
Este programa utiliza un bucle for anidado para imprimir el modelo de pirámide. El bucle for externo se usa para iterar sobre el número de líneas en el patrón y el bucle for interno se usa para imprimir el número de espacios y estrellas en cada línea.
El parámetro final de la función print() se establece en una cadena vacía para evitar que se impriman espacios y estrellas en líneas separadas. Esto produce la siguiente salida:
* *** ***** ******* *********
2. Patrón de reloj de arena
Aquí hay un programa de Python que usa un bucle for para imprimir un patrón de reloj de arena:
# This program prints an hourglass pattern using a for loop # Use a for loop to iterate over the number of rows in the pattern for row in range(1, 6): # If the current row is in the first or last half of the pattern, # print the number of spaces and stars in the current row if row <= 3: for space in range(3 - row): print(" ", end="") for star in range(2 * row - 1): print("*", end="") # If the current row is in the middle of the pattern, # print a row of 7 stars else: for star in range(7): print("*", end="") # After each row, print a newline character print()
Este programa utiliza un bucle for anidado para imprimir el patrón de reloj de arena. El bucle for externo se usa para iterar sobre el número de líneas en el patrón y el bucle for interno se usa para imprimir el número de espacios y estrellas en cada línea.
El parámetro «fin» de la función «imprimir ()» se establece en una cadena vacía para evitar que los espacios y las estrellas se impriman en líneas separadas. Esto produce la siguiente salida:
* *** ***** *** *
Al igual que con los otros patrones, esta es solo una forma de imprimir un patrón de reloj de arena usando Python. Hay muchas otras variaciones y técnicas que se pueden utilizar para lograr diferentes patrones y efectos.
3. Patrón de forma de diamante
Aquí hay un programa simple que imprime un patrón de diamantes en Python:
# define the size of the diamond n = 5 # use a for loop to print the top half of the diamond for i in range(1, n+1): # print spaces on the left side of the diamond for j in range(1, n-i+1): print(" ", end="") # print stars in the middle of the diamond for j in range(1, 2*i): print("*", end="") # print spaces on the right side of the diamond for j in range(1, n-i+1): print(" ", end="") # move to the next line print() # use a for loop to print the bottom half of the diamond for i in range(1, n): # print spaces on the left side of the diamond for j in range(1, i+1): print(" ", end="") # print stars in the middle of the diamond for j in range(1, 2*(n-i)-1): print("*", end="") # print spaces on the right side of the diamond for j in range(1, i+1): print(" ", end="") # move to the next line print()
Este programa utiliza bucles for anidados para imprimir el patrón de diamantes. El primer bucle for se usa para imprimir la mitad superior del diamante y el segundo bucle for se usa para imprimir la mitad inferior del diamante.
Cada línea del diamante se imprime con tres bucles for: uno para imprimir los espacios en el lado izquierdo del diamante, uno para imprimir las estrellas en el centro del diamante y otro para imprimir los espacios en el lado derecho del diamante. .
El número de espacios y estrellas en cada línea del rombo está determinado por las variables de bucle i y j, así como por el tamaño del rombo (n).
Si desea cambiar el tamaño del diamante, puede cambiar el valor de n al inicio del programa. Por ejemplo, si desea imprimir un diamante más grande, puede establecer n = 7 para imprimir un diamante de 7 filas de alto. Esto produce la siguiente salida:
* *** ***** ******* ********* ****** **** **
4. Patrón de estrella cuadrada
Aquí hay una forma de crear un patrón de estrella cuadrada en Python usando bucles for anidados:
size = 5 for i in range(size): for j in range(size): if i == 0 or i == size-1 or j == 0 or j == size-1 or i == j or i + j == size - 1: print("*", end="") else: print(" ", end="") print()
Esto producirá la siguiente salida:
***** * * * * * * *****
El bucle for externo se usa para iterar sobre las filas del modelo y el bucle for interno se usa para iterar sobre las columnas. En cada iteración, verificamos si los índices de fila y columna actuales (ie y j) cumplen alguna de las condiciones para imprimir una estrella y, de ser así, imprimimos una estrella. De lo contrario, imprimimos un espacio.
5. Patrón de estrella inverso en Python
Para crear un patrón de estrella inversa en Python, puede usar bucles for e instrucciones de impresión. Aquí hay un ejemplo:
for i in range(5, 0, -1): for j in range(0, i): print("*", end="") print()
Este código imprimirá el siguiente modelo:
***** **** *** ** *
6. Motivo estrella triangular en Python
Para crear un patrón de estrella triangular en Python, puede usar bucles for e instrucciones de impresión. Aquí hay un ejemplo:
for i in range(1, 6): for j in range(0, i): print("*", end="") print()
Este código imprimirá el siguiente modelo:
* ** *** **** *****
El bucle for exterior comprueba el número de líneas en el patrón y el bucle for interior imprime estrellas en cada línea. El parámetro final en la declaración de impresión se usa para evitar que las estrellas de cada línea se impriman en líneas separadas.
Para crear un patrón de estrella de triángulo de base hacia arriba, puede usar un enfoque similar, pero deberá invertir el rango en el bucle for exterior, así:
for i in range(5, 0, -1): for j in range(0, i): print("*", end="") print()
Este código imprimirá el siguiente modelo:
***** **** *** ** *
También puedes hacer un patrón de estrella triangular con la base hacia abajo, así:
for i in range(1, 6): for j in range(0, 6 - i): print(" ", end="") for j in range(0, i): print("*", end="") print()
Este código imprimirá el siguiente modelo:
* ** *** **** *****
En este ejemplo, el primer bucle for interno se usa para imprimir los espacios antes de las estrellas en cada línea, y el segundo bucle for interno se usa para imprimir las estrellas en cada línea. El parámetro final en la declaración de impresión se usa para evitar que los espacios y estrellas en cada línea se impriman en líneas separadas.
7. Motivo de estrella cuadrada vacía en Python
Para imprimir un patrón de estrella cuadrado vacío con diagonal en Python, puede probar el siguiente código:
size = int(input("Enter the size of the square: ")) for i in range(size): for j in range(size): if i == 0 or i == size-1 or j == 0 or j == size-1 or i == j or i+j == size-1: print("*", end="") else: print(" ", end="") print()
Este código le pedirá al usuario que ingrese el tamaño del cuadrado y luego imprima el cuadrado del tamaño especificado con un centro en blanco y una diagonal.
Aquí hay una salida de muestra para un tamaño de 5:
Enter the size of the square: 5 ***** * * * * * * *****
Tenga en cuenta que la diagonal del cuadrado está formada por los caracteres «*» en las posiciones donde i == jo i+j == tamaño-1.
8. Motivo de estrella de pirámide hueca en pitón
Para hacer que la pirámide quede vacía, puede modificar el código para imprimir solo las estrellas en la primera y última fila y para imprimir solo las estrellas más externas en las otras filas:
# define the number of rows in the pyramid rows = 5 # loop through each row for i in range(1, rows + 1): # print the spaces on the left side of the pyramid print(" " * (rows - i), end="") # if it's the first or last row, print the full row of stars if i == 1 or i == rows: print("*" * (i * 2 - 1), end="") # otherwise, only print the outermost stars on the row else: print("*" + " " * (i * 2 - 3) + "*", end="") # print the spaces on the right side of the pyramid print(" " * (rows - i))
Este código producirá el siguiente resultado:
* * * * * * * *********
Parte 2: Programas de patrones alfabéticos en Python
1. Patrón de alfabeto de triángulo rectángulo
Así es como puede crear un patrón alfabético de triángulo rectángulo usando Python:
# Print a new line at the start of each row for i in range(26): print() # Print the letters for the current row for j in range(i + 1): c = chr(ord('A') + j) print(c, end=" ")
Este código imprimirá un patrón de triángulo rectángulo con 26 líneas, con cada línea conteniendo las letras del alfabeto desde A hasta el número de línea actual. Por ejemplo, la primera línea contendrá solo la letra A, la segunda línea contendrá las letras A y B, y así sucesivamente.
Producción:
A A B A B C A B C D A B C D E A B C D E F A B C D E F G A B C D E F G H A B C D E F G H I A B C D E F G H I J A B C D E F G H I J K A B C D E F G H I J K L A B C D E F G H I J K L M A B C D E F G H I J K L M N A B C D E F G H I J K L M N O A B C D E F G H I J K L M N O P A B C D E F G H I J K L M N O P Q A B C D E F G H I J K L M N O P Q R A B C D E F G H I J K L M N O P Q R S A B C D E F G H I J K L M N O P Q R S T A B C D E F G H I J K L M N O P Q R S T U A B C D E F G H I J K L M N O P Q R S T U V A B C D E F G H I J K L M N O P Q R S T U V W A B C D E F G H I J K L M N O P Q R S T U V W X A B C D E F G H I J K L M N O P Q R S T U V W X Y A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
2. Plantilla de alfabeto de triángulo izquierdo
Así es como puede crear un patrón alfabético de triángulo izquierdo usando Python:
Código:
for i in range(1, 6): for j in range(65, 65+i): print(chr(j), end=" ") print("")
Producción:
A A B A B C A B C D A B C D E
3. Plantilla de alfabeto de rectángulo en blanco
Para crear una plantilla de alfabeto de rectángulo vacío en Python, puede usar bucles for anidados y declaraciones condicionales. Aquí hay un ejemplo:
# define the size of the pattern size = 5 # use two nested for loops to iterate over the rows and columns for i in range(size): for j in range(size): # if the current row is equal to the first or last row, or # the current column is equal to the first or last column, # print the alphabet if i == 0 or i == size - 1 or j == 0 or j == size - 1: print("A", end="") else: # otherwise, print a space print(" ", end="") # after each row is complete, print a newline print()
Este código producirá el siguiente resultado:
AAAAA A A A A A A AAAAA
Tenga en cuenta que puede ajustar el tamaño del patrón cambiando el valor de la variable de tamaño. También puede cambiar el código para usar diferentes letras o símbolos en su plantilla.
4. Plantilla de alfabeto de pirámide hueca
Para crear un patrón de pirámide vacío usando fuentes, puede usar un enfoque similar al descrito anteriormente. La única diferencia es que en lugar de usar asteriscos para crear la plantilla, puede usar una fuente diferente.
Aquí hay un ejemplo de cómo puede crear un patrón de pirámide vacío usando la letra «X» como fuente:
# Get the number of rows from the user num_rows = int(input("Enter the number of rows: ")) # Use a nested for loop to print the pyramid pattern for i in range(1, num_rows + 1): # Print the spaces for j in range(num_rows - i): print(" ", end="") # Print the Xs for j in range(2 * i - 1): if j == 0 or j == 2 * i - 2: print("X", end="") else: print(" ", end="") # Move to the next line print()
Este código imprimirá un patrón de pirámide hueca usando la letra «X» como carácter. La plantilla tendrá el número especificado de filas. Por ejemplo, si el usuario ingresa 5, el patrón se verá así:
X X X X X X X XXXXXXXXX
Como antes, puede personalizar el código para que el patrón se vea exactamente como lo desea. Puede cambiar la fuente utilizada para crear el patrón, la cantidad de espacios entre caracteres o cualquier otro aspecto del patrón.
5. Patrón de alfabeto de diamantes
Para crear una plantilla de alfabeto de diamantes en Python, puede usar bucles for anidados. El bucle exterior se utilizará para imprimir las filas y el bucle interior se utilizará para imprimir las columnas. Puede usar la función print() para imprimir el patrón, usando una combinación de espacios y letras para crear la forma de diamante.
Aquí hay un ejemplo de cómo puede crear una plantilla de alfabeto de diamantes en Python:
# Get the number of rows from the user num_rows = int(input("Enter the number of rows: ")) # Use a nested for loop to print the diamond pattern for i in range(-num_rows + 1, num_rows): # Calculate the absolute value of the current row row = abs(i) # Print the spaces for j in range(num_rows - row): print(" ", end="") # Print the letters for j in range(2 * row + 1): # Calculate the ASCII code for the current letter letter = ord("A") + row - abs(row - j) # Print the letter print(chr(letter), end="") # Move to the next line print()
Este código imprimirá un patrón alfabético de diamantes con el número especificado de líneas. Por ejemplo, si el usuario ingresa 5, el patrón se verá así:
A B B C C D D E E D D C C B B A
Puede personalizar aún más el código para que el patrón de diamantes se vea exactamente como lo desea. Por ejemplo, puede cambiar la cantidad de espacios entre letras o usar una fuente diferente en lugar de letras para crear el patrón.
6. Plantilla de alfabeto de pirámide inversa
Para crear un modelo de alfabeto de pirámide invertida en Python, puede usar bucles for anidados. El bucle exterior se utilizará para imprimir las filas y el bucle interior se utilizará para imprimir las columnas. Puede usar la función print() para imprimir el modelo, usando una combinación de espacios y letras para crear la forma de pirámide invertida.
Aquí hay un ejemplo de cómo crear un modelo de alfabeto de pirámide invertida en Python:
# Get the number of rows from the user num_rows = int(input("Enter the number of rows: ")) # Use a nested for loop to print the reverse pyramid pattern for i in range(num_rows, 0, -1): # Print the spaces for j in range(num_rows - i): print(" ", end="") # Print the letters for j in range(2 * i - 1): # Calculate the ASCII code for the current letter letter = ord("A") + i - 1 # Print the letter print(chr(letter), end="") # Move to the next line print()
Este código imprimirá una plantilla de alfabeto de pirámide inversa con el número de líneas especificado. Por ejemplo, si el usuario ingresa 5, el patrón se verá así:
Enter the number of rows: 5 EEEEEEEEE DDDDDDD CCCCC BBB A
7. Motivo del corazón
Aquí hay un programa de Python que puede imprimir un patrón de caracteres en forma de corazón:
# Get the total number of rows from the user num_rows = int(input("Enter the number of rows: ")) # Create a loop to iterate over the number of rows for i in range(1, num_rows+1): # Create another loop to print the spaces in the current row for j in range(1, num_rows-i+1): # Print a space character at the current position print(" ", end="") # Create another loop to print the heart character in the current row for j in range(1, i*2): # Print the heart character at the current position print("❤️", end="") # Move to the next line after printing the current row print()
Producción:
Enter the number of rows: 4 ❤️ ❤️❤️❤️ ❤️❤️❤️❤️❤️ ❤️❤️❤️❤️❤️❤️❤️
Este programa funciona de la siguiente manera:
- Primero, le pide al usuario que ingrese la cantidad de líneas que se imprimirán en el patrón del corazón.
- Luego, use un ciclo para iterar a través del número de filas. Para cada fila, cree dos bucles para imprimir los espacios y el carácter de corazón en esa fila.
- El primer ciclo imprime los espacios en la línea actual y el segundo ciclo imprime el carácter de corazón en la línea actual. El número de espacios en cada línea es igual al número de líneas menos el número de línea actual, y el número de caracteres de corazón en cada línea es igual al doble del número de línea actual.
- En cada iteración de los bucles internos, el programa imprime el carácter en la posición actual, luego pasa a la siguiente línea después de imprimir la línea actual.
- El parámetro end=» » en la función print() se usa para imprimir los caracteres en la misma línea, con un espacio entre cada carácter.