Can't get a function to work - python

I am try to create a function that will end my game with a message counting down until it ends, and I am having to repeat this block of code a lot in my text adventure game, so I decided to make a function of it for the sake of neatness, and efficiency. But I cannot figure out how to define and call such a function. This is the code I am trying to execute:
print "That\'s a real shame..."
time.sleep(1)
print 'Exiting program in 5 seconds:'
time.sleep(1)
print '5'
time.sleep(1)
print '4'
time.sleep(1)
print '3'
time.sleep(1)
print '2'
time.sleep(1)
print '1'
time.sleep(1)
sys.exit('Exiting Game...')
break
So I defining the function like this:
def exit():
print "That\'s a real shame..."
time.sleep(1)
print 'Exiting program in 5 seconds:'
time.sleep(1)
print '5'
time.sleep(1)
print '4'
time.sleep(1)
print '3'
time.sleep(1)
print '2'
time.sleep(1)
print '1'
time.sleep(1)
sys.exit('Exiting Game...')
break
And I am calling the function like this:
elif ready == 'n':
exit
What am I doing wrong?

You would 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 piece of code.
def exit():
print "That\'s a real shame..."
time.sleep(1)
print 'Exiting program in 5 seconds:'
time.sleep(1)
count_down(5) # Call Countdown clock
print 'Exiting Game...'
sys.exit()
def count_down(number):
for i in reversed(range(number)):
print i+1
time.sleep(1)
exit() # <-- This how you call exit, you were missing the parentheses at the end.
Output:
That's a real shame...
Exiting program in 5 seconds:
5
4
3
2
1
Exiting Game...
Edit: Added more in-depth explanation.
The first linedef count_down is a function that takes one parameter and has one purpose, to handle the count down.
def count_down(number):
The second row contains what we call a for loop. The purpose of this code is to loop through objects. Starting from 4 then 3,2,1 etc. And the variable i at the same row will change for each time the loop goes through a number and is accessible only inside the loop. The first time print is executed it will be 5, then the next time 4 and so on.
for i in reversed(range(number)):
In this function we also use two additional keywords and one parameter, reversed, range and the parameter number.
reversed(range(number))
range is used to create a list of numbers e.g. [0, 1, 2, 3, 4], that the for statement will loop through starting with 0, then it takes the next number all the way until it reaches the last number 4. I will explain why it starts at zero and only goes to four, and not five at the end of my answer.
reversed is used to reverse the list we created with range. Since we want to start at 4, and not 0.
Before reversed => [0,1,2,3,4]
After reversed] => [4,3,2,1,0]
number is a parameter. A parameter is a value that we provide when we execute the function from your exit() function by including a value inside the parentheses (). In this case we specified 5, so the list we created with
range will range from 0 - 4 (0,1,2,3,4 = five numbers in total). If you instead specified 10 within the parentheses it would create a list starting from 0 all the way to 9. And your code would count down from 10 to 1, instead of from 5 to 1.
When Python has started working on the for loop it will execute the code inside, starting with print and then sleep, and continues to do so for for each number in the list created by range. Since we specified five in this case, it will execute the code a total of five times.
As Python is executing the code within the for loop it will first call the print function. Because the for loop will start at 4, not 5, we need to do some basic arithmetics and increase the value of each item we loop through by one. We do this by typing + 1 after our variable i.
The reason why it starts at 4 and not 5 is because in programming lists starts with the number 0, and not 1. There is a more technical explanation available on the reason why lists start with 0, and not 1 (or 4, and not 5 in this case since we reversed the list) here

You are supposed to call it as exit(), not exit.

It is simple. Use a tuple that holds the message and the timer delay so you can even control the delay time for each message.
import time, sys
messages = [
("That's a shame", 1),
("Exiting program in 5 seconds", 1),
(None, 5)
]
for k,v in messages:
if k:
print(k)
time.sleep(v)
else:
# start countdown timer
while v:
print v
time.sleep(1)
v -= 1
sys.exit()

A good way to do this code is:
def exit():
timer= 5
print "That\'s a real shame..."
time.sleep(1)
print 'Exiting program in 5 seconds:'
for i in range (5):
time.sleep(1)
print timer
timer = timer - 1
sys.exit('Exiting Game...')
##You call the function like this
exit()

Related

Restarting a script in Python

I'm wondering how I can restart a script without just calling the function itself. You can see the example below. After "two" is printed I want the script to restart itself without just calling one().
import time
zero = 0
def one():
global zero
for i in range(50):
time.sleep(0.5)
zero += 1
print(zero)
if zero == 10:
two()
def two():
print("two")
#Restart the script
one()
You want to do some condition forever, so the most practical way is to use a while loop with a condition that is always true.
while True:
one()
You probably also want to return from function one after calling two
if zero == 10:
two()
return
You can try with a while loop,
import time
zero = 10
i = 0
while i <= zero:
time.sleep(0.5)
zero += 1
print(zero)
print("two")

Closing a program when a condition is met

I am just starting out and can't figure this one out.
I am writing a program to do some simple calculations for me at school.
Different calculations will be accessible through input of simple numbers from 1 to X. Every number will call a function just for that calculation.
My problem is this:
I want that if the user enters an empty string when prompted for a number, the program will ask the user to re enter a number for a certain amount of times before closing. Here's my code:
def pick_procedure():
procedure = raw_input("> ")
if not procedure:
counter = 0
print "Enter a value. "
while counter <4:
counter = counter + 1
main()
if counter == 4:
break
def main():
print "\nStudy helper 1.0.\n"
print """Procedure list:
1.Area of circle.
2. Circumference of a circle.
Please pick a procedure: """
pick_procedure()
main()
No matter how many times an empty string is entered, the program does not close.
How to do it correctly and cleaner?
As you say, you need to reorganise your code:
def pick_procedure(valid_choices):
print "Enter a value. "
for _ in range(4): # prompt for a choice up to 4 times
choice = raw_input("> ")
if choice in valid_choices:
return choice
return None # A valid choice was not entered
def main():
print "\nStudy helper 1.0.\n"
choice = 1
while choice:
print """Procedure list:
1. Area of circle.
2. Circumference of a circle.
Please pick a procedure: """
choice = pick_procedure(["1", "2"])
if choice:
print "Doing choice", choice
main()
The following approach makes use of a while choice loop to keep prompting if a valid choice is entered. If no choice is entered 4 times, the pick_procedure() function returns None causing the while loop to exit cleanly. If a valid choice is entered, it returns that choice.
I also pass the list of valid responses to the function, that way the function can be used for other questions simply by passing a different list of valid responses.
You created a vicious circle.
First time that procedure is false, pick_procedure calls main and then main calls again pick_procedure. It continues recursively.
If you just want to finish the program when an event is fired, you can use sys.exit(0) and your problems are solved.

Don't understand the error message : Invalid syntax in for statement

I am writing a very simple program to output the 0-10 in numbers using a for loop. However it comes up with a syntax error when I click run, highlighting in red the "=" in the 8th line. I don't understand why it is wrong? I am using python 3.5.2 in idle mode.
def numbers():
print ("This program will count to ten, just you wait...")
import time
time.sleep(1)
print ("\n\nLiterally wait I just need to remember base 10 because I
only work in binary!")
time.sleep(4)
int(counter) = 0
for counter <**=** 9:
print ("\n" + counter)
counter = counter + 1
print ("\n\nAnd there you go. Told you I could do it. Goodbye :) ")
time.sleep(2)
exit()
numbers()
Try it like this:
def numbers():
print ("This program will count to ten, just you wait...")
import time
time.sleep(1)
print ("\n\nLiterally wait I just need to remember base 10 because I only work in binary!")
time.sleep(4)
for i in range(1, 10): #11 if you want 10 to be printed
print i
print ("\n\nAnd there you go. Told you I could do it. Goodbye :) ")
time.sleep(2)
This is wrong syntax for for. As per docs:
The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object.
which is not your case, or you can use range() to create the sequence:
for i in range(1, 10):
yet it's artificial workaround and while it will work, is not what you should be doing really.
You should use while instead. Docs say:
The while statement is used for repeated execution as long as an expression is true
while counter <= 9:
A couple of points. The excerpt:
int(counter) = 0
for counter <**=** 9:
print ("\n" + counter)
counter = counter + 1
has multiple errors.
int(counter) = 0 is not valid python syntax.
for counter <**=** 9 is not a valid for statement.
The lines print ("\n" + counter) and counter = counter + 1 are lacking proper indentation.
Replace those four lines with
for counter in range(10):
print(counter)

Python continue Not Working Properly

I am writing a method using Python and I believe that the continue statement is not working properly. Can some explain to me what is wrong there?
The method code is below:
def xlToLinkedDt(lst1, lst2, name1, name2):
logging.info(">> New iteration")
dates1, times1, dates2, times2 = [], [], [], []
for i, (dt1, dt2) in enumerate(zip(lst1, lst2)):
if bool(dt1) + bool(dt2) == 1:
name = name1 if not dt1 else name2
issues.append("The %s date of trip no. %d must be provided." %(name, i+1))
dates1.append("")
dates2.append("")
times1.append("")
times2.append("")
logging.info("Exiting loop")
continue
logging.info(Continued after bool condition.)
raise AssertionError("Stop!")
When I run this code I get an error and the following logging in one of the iterations:
>> New iteration
>> Exiting loop
>> Continued after bool condition
The code is not supposed to log both messages, only one of them. Also when I replaced continue with break it worked well. What am I missing?
The code is not supposed to log both messages.
Yes, it is.
After your code executes continue, the loop moves back to the beginning of the block inside the for-loop, in the next iteration. If the condition in your if-block is not met at the next iteration, you will get exactly the behaviour you describe.
In [5]: for i in range(10):
print("Trying with i={:d}".format(i))
if i%2 == 0:
print("`i` even, continuing")
continue
print("What am I doing here?")
...:
Trying with i=0
`i` even, continuing
Trying with i=1
What am I doing here?
Trying with i=2
`i` even, continuing
Trying with i=3
What am I doing here?
Trying with i=4
`i` even, continuing
Trying with i=5
What am I doing here?
Trying with i=6
`i` even, continuing
Trying with i=7
What am I doing here?
Trying with i=8
`i` even, continuing
Trying with i=9
What am I doing here?
As you can see, there is still a What am I doing here? printed after the i even, continuing notification, but it belongs to a later iteration of the loop. If we replace continue by break, we get very different behaviour:
In [6]: for i in range(10):
print("Trying with i={:d}".format(i))
if i%2 == 0:
print("`i` even, not continuing")
break
print("What am I doing here?")
...:
Trying with i=0
`i` even, not continuing
As you can see, it stops immediately because (by our definition), 0 is even.
You used continue, I guess you meant break.
continue will skip to the next iteration of your for loop.
break will leave the for loop.
Try that :
def test():
print("Function start")
for i in range(10):
if i == 1:
print("Exiting loop")
continue
print("Am I printed or not ?")
print("I'm out of the loop")
Then replace continue by break and see what happens.
Since print("Am I printed or not ?") is part of the for loop, it will be executed on next for iteration after "Exiting loop", if you use continue. If you use break, it will be skipped.

how to exit try loop after code succeed?

my code below tries to execute a function x but because x takes time to build, i need to sleep until it is built then call it. So it usually takes me about 300s to build. When i run the code below, it will loop through the try loop about 3 times but print 0 every time it pass through the except code.
Is it right to put the print x (for when code succeeds and i break) outside the for loop like below or somewhere else? Also, how do i make i print the number of time it is trying instead of 0?
for i in range(0,10):
while True:
try:
x = my_get_fuction
except:
print "error"
print i
time.sleep(100)
continue
break
print x
Your while loop doesn't seem to be related to your design. Try this:
for i in range(0,10):
try:
x = my_get_fuction
except:
print "error"
print i
time.sleep(100)
continue
break
print x
This code will loop a maximum of 10 times, sleeping each time for 100s. If the assigned x = my_get_function doesn't complete by 1000s or so, then the loop gives up.

Categories