You can call the function by typing exit() . I modified your countdown code and turned it into a function that I called inside exit() to demonstrate how to call one function from a piece of code.
def exit(): print "That\ a real shame..." time.sleep(1) print 'Exiting program in 5 seconds:' time.sleep(1) count_down(5)
Output:
That a real shame... Exiting program in 5 seconds: 5 4 3 2 1 Exiting Game...
Edit: Added a more detailed explanation.
The first line of def count_down is a function that takes one parameter and has one purpose to handle the countdown.
def count_down(number):
The second line contains what we call for the loop . The purpose of this code is to cycle objects around. Starting with 4 , then 3,2,1 , etc. And the variable i in the same line will change every time the cycle goes through a number and is available only inside the cycle. It is executed the first time when 5 is executed, then the next time 4, etc.
for i in reversed(range(number)):
In this function, we also use two additional keywords and one parameter reversed , range and parameter number .
reversed(range(number))
range is used to create a list of numbers, for example. [0, 1, 2, 3, 4] that the for statement will loop around starting at 0 , then it gets to the next number until it reaches the last number 4 . I will explain why it starts from scratch and only reaches four, not five at the end of my answer.
reversed is used to modify the list we created with the range. Since we want to start with 4 , not 0 .
Until reversed => [0,1,2,3,4]
After reversed] => [4,3,2,1,0]
number is a parameter. A parameter is the value that we provide when executing a function from your exit() function by including the value in parentheses () . In this case, we indicated 5, so the list that we created using range will vary from 0 to 4 (0,1,2,3,4 = five numbers in total). If you specify 10 in parentheses, it will create a list starting from 0 to 9. And your code will count from 10 to 1, not from 5 to 1.
When Python started working with for loop , it will execute the code inside, starting with print and then sleep , and continues to do this for every number in the list created by range . Since in this case we specified five, it will execute the code five times.
When Python executes the code inside a for loop , it will first call the print function. Since the for loop starts with 4 , not 5 , we need to do some basic arithmetic and increase the value of each element that we scroll one. We do this by typing + 1 after our variable i .
The reason it starts with 4, not 5, is because the number 0 , not 1 , starts in the programming lists. There is a more detailed technical explanation for the reason that lists start with 0, not 1 (or 4, not 5 in this case, when we canceled the list) here