Reputation: 9
I was trying to have a program using Python to create a "pyramid" based on a number, n, out of o's and came up with this: ( I would print nn, that would be the lines.)
import time
n = 0
while True:
n += 2 #just another way to show n=n+2
nn = n, "o" #nn would be an amount of o's, based on what #n was
time.sleep(1)
print (nn, str.center(40, " "))
Not sure how to make nn the o's and not sure what line 6 does either. Does anyone know the answer to either question? ( I'm not in a class just programming for fun.)
Upvotes: 0
Views: 122
Reputation: 15204
You can also use the built-in formatting options offered by python. Take a look at this:
def pyramid_builder(height, symbol='o', padding=' '):
for n in range(0, height, 2): # wonkiness-correction by @mhawke
print('{0:{1}^{2}}'.format(symbol*n, padding, height * 2))
pyramid_builder(20, 'o')
The ^
symbol says that you want your print centered. Before it ({1}
) comes the padding symbol and after it ({2}
) the total width.
This is fully customisable and fun to play with.
Upvotes: 1
Reputation: 8521
This will be the answer to your question
import time
n = 0
while True:
n += 2
nn = n * "o"
time.sleep(1)
print (nn.center(40, " "))
if n > 30:
break
The reason why they have put time.sleep(1)
is to make it look like an animation. print (nn, str.center(40, " "))
this must be changed to nn.center(40, " ")
as .center
is a method of string.
Upvotes: 1
Reputation: 320
You can try this:
from __future__ import print_function
import time
for n in range(0, 40, 2):
nn = n * "o" #nn would be an amount of o's, based on what #n was
time.sleep(1)
print(nn.center(40, " "))
Upvotes: 1
Reputation: 7006
import time
n = 0
while True:
n += 2 #just another way to show n=n+2
nn = "o" * n #nn would be an amount of o's, based on what #n was
time.sleep(1)
print (nn.center(40," "))
As someone has mentioned in the comments "o" * n will give a a string containing n "o"s. I've fixed the print line to use the correct method a calling the center method.
Upvotes: 1