Super Mario pyramids in Python
Starting this week in the CS50 course, I am now transitioning from C to Python, learning syntax and all the fundamentals of this new language. To kick things off, I have rewritten my very first program, Super Mario pyramids in C. Feels quite nostalgic!
My first attempt in Python looked like this:
def main():
height = get_height()
for i in range(1, height + 1):
print_row(height, i)
# Prompt user for input
def get_height():
MIN_HEIGHT = 1
MAX_HEIGHT = 8
while True:
try:
n = int(input("Height: "))
if MIN_HEIGHT <= n <= MAX_HEIGHT:
return n
except ValueError:
print("Enter a number from 1 to 8")
# Printing columns of the pyramid
def print_row(height, length):
# Printing the spaces on the left
spaces = height - length
print(" " * spaces, end="")
# Printing hashes for the left side of the pyramid
print("#" * length, end="")
# Printing the gap between the sides of the pyramid
print(" ", end="")
# Printing hashes for the right side of the pyramid
print("#" * length)
main()
Then I decided to shrink the print_row function into a single print:
# Printing columns of the pyramid
def print_row(height, length):
spaces = height - length
print(" " * spaces + "#" * length + " " + "#" * length)
But looking at that piece of code, I realised that I don’t need a separate function for this at all. The concatenation of strings within a single print function in Python is amazing!
I’ve also added a condition to check whether the user input is numeric, which might be an overkill for this case, but still good for practice.
So here is my final code:
def main():
height = get_height()
# Print pyramid
for i in range(1, height + 1):
spaces = height - i
print(" " * spaces + "#" * i + " " + "#" * i)
# Prompt user for input
def get_height():
MIN_HEIGHT = 1
MAX_HEIGHT = 8
while True:
height_str = input("Height: ")
if height_str.isnumeric():
height = int(height_str)
if MIN_HEIGHT <= height <= MAX_HEIGHT:
return height
else:
print("Number must be between 1 and 8, inclusive.")
else:
print("Invalid input. Please enter a number.")
if __name__ == '__main__':
main()
That ending felt a bit weird, but as I’ve learned from Google, it seems like a rule of thumb to finish the program with that line to ensure it can be executed only when the file runs as a script, but not through importing as a module.