Trying to build a character triangle in Python

So, my professor is trying to get us to write a function inside a function that prints a triangle with different characters, for example:

&

&

& &

%

%%

%%%

@

@@

@@@

@@@@

I can write a triangle function and print it in this format, but it's hard for me to take a mental leap to attach a variable character. In short, I can print the correct form, but not with different characters. Here is what I still have:

s = "&" def stars(i): '''Prints n number of stars''' print(i*s) def triangle_of_symbols(s, n): '''Creates symbol triangle function with variable n.''' for i in range (n): stars(i+1) triangle_of_symbols(s, 1) triangle_of_symbols(s, 2) triangle_of_symbols(s, 3) triangle_of_symbols(s, 4) 

How would I do that? Even pointing in the right direction would be extremely helpful right now.

+5
source share
2 answers

Currently, the stars function takes i , namely, how many stars are printed, and then extracts from the global variable s for which character to print.

Instead, parameterize s in stars so that you can specify a function whose symbol will be printed every time it is called.

 def starts(i, s): print(s * i) # I think that order scans better -- "s, i times". YMMV 

Then in triangle_of_symbols go s together with i+1 .

 ... for i in range(n): stars(i+1, s) 

although there really is a small reason for separating the two functions.

 def triangle_of_stars(s, n): for i in range(n): print(s * i+1) 
+4
source

You can also put your characters in the dictionary.

 shapes = {"stars": "*", "at": "@"} def generate_triangle(shape_key, lines): for i in range(lines): print (shapes[shape_key] * (i+1)) generate_triangle('at', 4) generate_triangle('stars', 4) 
+2
source

Source: https://habr.com/ru/post/1267072/


All Articles