Reputation: 13
I have recently started learning Python and I have a countdown timer. It works fine but I wanted to add an asterisk to the output.
A recreation of the output is:
Countdown timer: How many seconds? 4
4****
3***
2**
1*
Blast off
So far I have:
import time
countDown = input('Countdown Timer: How many seconds?')
for i in range (int(countDown), 0, -1):
print (i)
time.sleep(1)
print ('BLAST OFF')
Upvotes: 1
Views: 2682
Reputation: 266
If you are using python3 then try this code
import time
countDown = input('Countdown Timer: How many seconds?')
for i in range (int(countDown), 0, -1):
print(i, end=" ")
print ('*' * i)
time.sleep(1)
print ('BLAST OFF')
Upvotes: 0
Reputation: 360
You can make your code more flexible by defining it as a function.
What is a funtion?
Function is an organised block of code which provides modularity so that the code can be reused.
Say, a function blastOff() is defined. We can call this function with any value of countdown, whether 4 or 10 or 20, passed as an argument of a function within the parenthesis. And we can do this without having to write the code again and again.
import time
def blastOff(n):
"""Returns "Blast Off" after a reverse countdown of n"""
for i in reversed(range(1, n + 1)): # iterate over a reversed range
print(i, i * "*") # multiply "*" by the ith number of the range.
time.sleep(1) # sleep for a second before looping over the next number in the range.
return "BLAST OFF"
blastOff(4)
4 ****
3 ***
2 **
1 *
Out: 'BLAST OFF'
Upvotes: 0
Reputation: 7504
Just add the *
while printing with numbers.
import time
countDown = input('Countdown Timer: How many seconds?')
for i in range (int(countDown), 0, -1):
print (i,"*"*(i))
time.sleep(1)
print ('BLAST OFF')
Or print str(i)+"*"*(i)
- without space after the number.
Upvotes: 1
Reputation: 266
You can use the below code for the desired output
import time
countDown = input('Countdown Timer: How many seconds?')
for i in range (int(countDown), 0, -1):
print (i),
print ('*' * i)
time.sleep(1)
print ('BLAST OFF')
Upvotes: 0
Reputation: 1550
Following code will work:
import time
countDown = input('Countdown Timer: How many seconds?')
for i in range (int(countDown), 0, -1):
print(i*'*') # This will print i number of '*'s
time.sleep(1)
print ('BLAST OFF')
Upvotes: 0