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")
Related
I'm creating a function in python that is repeated two times when it ends even if it doesn't have to do it.
def first ():
numuser = int(input("Write a number"))
if(0 < numuser < 26):
print("Ok")
else:
print("Wrong!, restart it!")
first() #If the number is out of the range it restart the function
return numuser
first()
def second():
numuserfirst = first() #retrive the number choosen in the first function
second()
Repetition is caused by the variable call numuserfirst = first(), how can I solve it?
Thanks
Don't use recursion to implement a simple loop; use a while statement. One possible implementation:
def first():
while True:
numuser = int(input("Write a number"))
if 0 < numuser < 26
break
print("Wrong!, try again")
print("OK")
return numuser
(Python 3.10.4)
I have a for condition and inside this for a have a function that need a break and go back to the top like "continue" do, but i can't use break outside a loop, how can i go back to the top of the code? I will use this function so many times after and i don't want to have so many if in my code
import time
def function1():
if pyautogui.locateCenterOnScreen('file.png')
pyautogui.moveTo(x=612, y263)
time.sleep(1)
break
How can i break the code in this case:
for c in range (0,10):
print('begin for')
#FUNCTION
function1():
#
#
#REST OF THE CODE
It's hard to imagine what you meant by 'break the code' with your incorrect code indentations. I guess you meant to break the for loop
when the function breakes.
Use a variable out side the function to indicate when you're done with your function.
And check for the value of the variable within the for loop to break or pass
br = 0
def function1():
if pyautogui.locateCenterOnScreen('file.png')
pyautogui.moveTo(x=612, y=263)
br = 1
time.sleep(1)
return 0
for c in range (0,10):
print('begin for')
#FUNCTION
function1()
if br == 1:
break
else:
pass
#
#
#REST OF THE CODE
I am new to python and programming and having difficulty breaking out of a while loop that calls a few functions. I have tried a variety of different options but they all end the same, well they don't end it just keeps running. I am only on here because I have really researched and tried for a long time to fix this. Below is some of the code where you can see there might be confusion with a function. I am not posting the full program just the last part. Thank you for any assistance while I learn. This is also my first time posting, I've been using stackoverflow for the past year dabbling.
def main():
choice = input('''Hello,
Would you like to do basic math or return an average?
Please select 1 for basic math and 2 for average and 3 to quit:
''')
if choice == '1':
print(performCalculation())
elif choice == '2':
print(calculateAverage())
elif choice == '3':
print(main())
j = 0
k = 0
while j < 3:
print(main())
while k == 3:
break
print('All Done!')
Simply change
j = 0
k = 0
while j < 3:
print(main())
while k == 3:
break
print('All Done!')
to
j = 0
while j < 3:
print(main())
j += 1
print('All Done!')
The reason your while loop never breaks is because you have while j < 3:, but you never change the value of j, so if it was smaller to begin with, it will forever be smaller.
Also, k will never equal to 3, and even if it will, the break statement within that while loop will only make that while loop terminate, not the main one.
You have several basic mistakes here. I'll go in order of your program execution.
You aren't incrementing your loop variables.
You've started your loop variables with j and k (why not i and j?) set to zero, and are looped based on the value of these variables. Since they are never incremented, your loop never hits an exit condition.
You can increment the variables with j += 1, and k += 1 at the end of the respective loops.
Your loops are "unpythonic"
These would typically be written as my example below. You don't need to declare i separately, or increment it here. Python handles that for you.
for i in range(0, 3):
...
You're printing a function that doesn't return anything.
Your main function doesn't have a return value, so calling print(main()) is nonsense. You can replace this with simply main() unless you change main() to have some kind of return "foo" statement.
I just learned about break and return in Python.
In a toy code that I wrote to get familiar with the two statements, I got stuck in a loop, but I don't know why. Here is my code:
def break_return():
while True:
for i in range(5):
if i < 2:
print(i)
if i == 3:
break
else:
print('i = ', i)
return 343
break_return()
I'm new to programming, any suggestions will be appreciated.
With the for-else construct you only enter the else block if the for loop does not break, which your for loop always does because i inevitably becomes 3 with your range generator. Your infinite while loop is therefore never able to reach the return statement, which is only in the said else block.
nvm I'm super wrong here
First of all, when you define a function in Python, any code that belongs in the function should be in the same indentation block. With this in mind, your code would look like this:
def break_return():
while True:
for i in range(5):
if i < 2:
print(i)
if i == 3:
break
else:
print('i = ', i)
return 343
break_return()
The next problem I see is that your else statement isn't correctly formatted with an if statement. If you mean for it to go on the 2nd if statement, your code would look like this:
def break_return():
while True:
for i in range(5):
if i < 2:
print(i)
if i == 3:
break
else:
print('i = ', i)
return 343
break_return()
This is only formatting. But in this example, the code would only run once because it immediately returns and exits the function.
I think this may be a better example of using both break and return:
def break_return(value):
for i in range(5):
print(i)
if i == 3:
break #This exits the for loop
if i == 4:
print("This won't print!")
#Won't print because the loop "breaks" before i ever becomes 4
return value * 2 #Returns the input value x 2
print(break_return(30)) #Display the return value of break_return()
This demonstrates how break exits a for loop and how return can return a value from the function.
The output of the code above is:
0 #Value of i
1 #Value of i
2 #Value of i
3 #Value of i
60 #The value returned by the function
Glad to hear you're learning Python! It's a lot of fun, and super useful.
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()