G

PrintA

public
Guest Feb 26, 2025 Never 26
Clone
Python PrintA 63 lines (54 loc) | 2.49 KB
1
def print_letter(size: int, glyph: str = "*") -> None:
2
"""Prints a representation of a letter with a given glyph
3
Parameters
4
----------
5
size : int
6
Height / Width of the character to print
7
glyph : str, default: *
8
Char to use to print the character
9
"""
10
# Calculate center line of the letter
11
center: int = (size // 2)
12
13
for line_index in range(size):
14
# Precompute index + 1 as it is used at some more calculations
15
line_count = line_index + 1
16
17
# Generate padding string to print on the left/right of the letter
18
pad_width: int = size - (line_count)
19
pad_str: str = " " * pad_width
20
21
# Compute the center of the letter
22
# Start with a single instance of the glyph
23
center_str: str = f"{glyph}"
24
25
# Distinct between the center line and all others
26
# On the center line, it get's filled with the letters glyph,
27
# else we just put spaces in between
28
if line_index == center:
29
fill_glyph = glyph
30
else:
31
fill_glyph = ' '
32
33
# On every other line than the first one (theres only a single glyph at the peak of the 'A')
34
# we compose the center section as follows:
35
if line_index != 0:
36
# main glyph + ((index * 2) - 1 * center glyph) + main glyph
37
center_str = f"{center_str}{(line_index * 2 - 1) * fill_glyph}{glyph}"
38
39
# Compose the output string from padding, center and padding
40
print(f"{pad_str}{center_str}{pad_str}")
41
42
43
if __name__ == "__main__":
44
# Set height to none so we can repeat user input until it is a valid value
45
height: [int | None] = None
46
while height is None:
47
try:
48
# Prompt user input and try to convert it to an integer
49
height = int(input("Enter odd character height: "))
50
# Make sure we have at least five lines (else the letter won't work
51
if height < 5:
52
print("Set height to minimum value of 5")
53
height = 5
54
# Make sure to have an odd height, else the a won't have a peak and a defined center
55
if height % 2 == 0:
56
height += 1
57
print(f"Odd height required, adjusted value to {height}")
58
# Re-prompt number if input was invalid
59
except Exception:
60
print("You need to specify a valid integer")
61
62
# Send height to the upper function
63
print_letter(height)