Looping two actions - python

How would I go about looping these two actions only in the code.
driver.find_element_by_xpath("//*[#id='skipAnimation']").click() time.sleep(1) driver.find_element_by_xpath("// *[#id='openAnother']").click()
I don't want to loop the whole code I want these two codes to repeat until I stop it

Your goal is not really clear: "I don't want to loop the whole code I want these two codes to repeat until I stop it".
Do you expect to end the loop 'manually'?
If so, then you can ask for user input in Python with input().
If my understanding of the problem is correct, you want to run your two functions until you decide to manually stop them running?
I believe a while loop could be used for this task.
You have different options depending if you want to press a key at each iteration, or if you want it to loop until you press a specific key.
Press at each iteration:
while True: # infinite loop
user_input = input("Want to continue? ")
if user_input == "No":
break # stops the loop
else:
# do whatever computations you need
driver.find_element_by_xpath("//*[#id='skipAnimation']").click()
time.sleep(1)
driver.find_element_by_xpath("// *[#id='openAnother']").click()
print('looping')
Now, if you want it to constantly run, until you press a key, there are two options:
while True:
try:
# do whatever computations you need
driver.find_element_by_xpath("//*[#id='skipAnimation']").click()
time.sleep(1)
driver.find_element_by_xpath("// *[#id='openAnother']").click()
print('looping')
except KeyboardInterrupt:
break
Or
import msvcrt
while True:
# do whatever computations you need
driver.find_element_by_xpath("//*[#id='skipAnimation']").click()
time.sleep(1)
driver.find_element_by_xpath("// *[#id='openAnother']").click()
print('looping')
if msvcrt.kbhit():
break
But pay attention to the behavior if you're in a notebook.

Related

How do I offer the choice to run the program again or end it in Python?

I'm trying to run this program which takes a message from the user and then prints it out backwards. The while loop works but at the end I'd like to implement a decision point that carries on or exits altogether.
See here:
print("\nHi, welcome to my program that will reverse your message")
start = None
while start != " ":
var_string = input("\nSo tell me, what would you like said backwards:")
print("So your message in reverse is:", var_string[::-1])
input("Press any key to exit")
Please advise how I may include something like 'input("\nIf you want another go, tell me what:)' which would restart the loop if the user decides to. Would this be an if/or indentation?
This is early days for me.
I think your question has less to do with while loops, and more with conditional statements and continue / break statements, i.e. "control flow tools". See my suggestions in the edit to your code below:
print("\nHi, welcome to my program that will reverse your message")
# This bit is unnecessary. Why use the `start` variable if you're never going to
# reassign it later in your program?
#start = None
#while start != " ":
# Instead, use `while True`. This will create the infinite loop which you can
# 'continue` or `break` out of later.
while True:
var_string = input("\nSo tell me, what would you like said backwards:")
print("So your message in reverse is:", var_string[::-1])
# Prompt the user again and assign their response to another
# variable (here: `cont`).
cont = input("\nWould you like another try?")
# Using conditional statements, check if the user answers "yes". If they do, then
# use the `continue` keyword to leave the conditional block and go another
# round in the while loop.
if cont == "Yes":
continue
# Otherwise, if the user answers anything else, then use the `break` keyword to
# leave the loop from which this is called, i.e. your while loop.
else:
input("Press any key to exit")
break

Breaking out of nested loops with user input

Is there an efficient way to break out of a nested loop by having a user simply providing an input at the particular time they want to break out (e.g. press a key)? I have conditional statements in the loops themselves that I can use to break the loops, but if for example I simply want to stop the loops at any time yet still want the rest of the code to run, is there a simple way to do that? To clarify the motivation, I would like to do something like:
for x in xrange(1000):
for y in xrange(1000):
for z in xrange(1000):
print x,y,z #function of loop
if (user_has_pressed_key) == True: #a user input that
#can come at any time
#but there should NOT be
#a prompt needed for each iteration to run
break
else:
continue
break
else:
continue
break
I have considered using raw input, but would not want the loops to wait each iteration for the user as there will be numerous iterations. There appear to be some proposed solutions when using different packages, but even these seem to only be Windows-specific. I am running this code on multiple computers so would ideally want it to function on different OS.
You can break out of the nested loops if the user issues a Ctrl+C keystroke, since it throws a KeyboardInterrupt exception:
try:
for x in xrange(1000):
for y in xrange(1000):
for z in xrange(1000):
print x,y,z #function of loop
except KeyboardInterrupt:
print("Stopped nested loops")
If you want the loop to break whenever any key is pressed by the user, then you can try this import:
from msvcrt import getch
while True:
key = getch()
if (key is not None):
break

Interest Calculator looping issue Python

beginner here. I've made an interest calculator program to help me with my loans of different sorts. I'm having two issues to finalize my program. Here's the program. I tried looking up the problems but I wasn't sure how to word it so I thought I'd just ask a question in total.
x=1
while x==1:
import math
loan=input("Enter Loan amount: ")
rate=input("Enter rate: ")
if rate.isalpha() or loan.isalpha():
print("Hey that's not a number!")
break
rate=rate.replace("%","")
loan=float(loan)
rate=float(rate)*0.01
amount1y=round(loan*(math.e**(rate*1)),2)
amount5y=round(loan*(math.e**(rate*5)),2)
amount10y=round(loan*(math.e**(rate*10)),2)
monthlypay=round(amount1y-loan,2)
print("Year 1 without pay: " + str(amount1y))
print("Year 5 without pay: " + str(amount5y))
print("Year 10 without pay: " + str(amount10y))
print("Amount to pay per year: " + str(monthlypay))
print("Want to do another? Y/N?")
ans=input('')
ans=ans.lower()
y=True
while y==True:
if ans=="n" or ans=="no":
x=0
break
elif ans=="y" or ans=="yes":
y=False
else:
print("You gotta tell me Yes or No fam...")
print("I'll just assume that mean's yes.")
break
My issue is in two locations. First during the
if rate.isalpha() or loan.isalpha():
print("Hey that's not a number!")
break
How do I write this so that instead of it ending the program all together, it instead restarts from the top until they put in a number. Also as a side just for fun and knowledge. Lets say they enter text three times in a row, and at that point it just executes the program how would I go about doing that also?
Finally during this part of the code:
while y==True:
if ans=="n" or ans=="no":
x=0
break
elif ans=="y" or ans=="yes":
y=False
else:
print("You gotta tell me Yes or No fam...")
print("I'll just assume that mean's yes.")
break
the else at the end, without that break, will continue printing "You gotta tell me Yes or No fam..." forever. How do I make it so that instead of breaking the while statement, it'll just restart the while statement asking the question again?
Thanks for your help!
P.S. This is python 3.4.2
You make an infinite loop, that you break out of when all is well. Simplified:
while True:
x_as_string = input("Value")
try:
x = float(x_as_string)
except ValueError:
print("I can't convert", x_as_string)
else:
break
It is easier to ask forgiveness than permission: You try to convert. If conversion fails you print a notice and continue looping else you break out of the loop.
On both of your examples, I believe your looking for Python's continue statement. From the Python Docs:
(emphasis mine)
continue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition or finally clause within that loop. It continues with the next cycle of the nearest enclosing loop.
When continue passes control out of a try statement with a finally clause, that finally clause is executed before really starting the next loop cycle.
This basically means it will "restart" your for/while-loop.
To address your side note of breaking the loop if they get the input wrong after three tries, use a counter variable. increment the counter variable each time the user provides the wrong input, and then check and see if the counter variable is greater than 3. Example:
counter = 0
running = True:
while running:
i = input("Enter number: ")
if i.isalpha():
print("Invalid input")
counter+=1
if counter >= 3:
print("Exiting loop")
break
Unrelated notes:
Why not use a boolean value for x as well?
I usually recommend putting any imports at the module level for the structure an readability of one's program.
Your problem is straightforward. You have to use continue or break wisely. These are called control flow statements. They control the normal flow of execution of your program. So continue will jump to the top-most line in your loop and break will simply jump out of your loop completely, be it a for or while loop.
Going back to your code:
How do I write this so that instead of it ending the program all together, it instead restarts from the top until they put in a number.
if rate.isalpha() or loan.isalpha():
print("Hey that's not a number!")
continue
This way, you jump back (you continue) in your loop to the first line: import math. Doing imports inside a loop isn't useful this way the import statement is useless as your imported module is already in sys.modules list as such the import statement won't bother to import it; if you're using reload from imp in 3.X or available in __builtin__ in Python 2.x, then this might sound more reasonable here.
Ditto:
if ans=="n" or ans=="no":
x=0
break
elif ans=="y" or ans=="yes":
continue
else:
print("You gotta tell me Yes or No fam...")
print("I'll just assume that mean's yes.")
continue
To state this snippet in English: if ans is equal to "n" or "no" then break the loop; else if ans is equal to "y" or "yes" then continue. If nothing of that happened, then (else) continue. The nested while loop isn't needed.
Lets say they enter text three times in a row, and at that point it just executes the program how would I go about doing that also?
Not sure if I understood your question, you can take input three times in different ways:
for line in range(3):
in = input("Enter text for lineno", line)
...do something...

Leave loop early based on user input without prompting each iteration

I have a program that takes a very long time to run, and I want it to be able to do what it needs to do but then if the user hits a specific key then I want the loop to break at a certain point. Most Q&A's I have seen pertaining to this problem prompt the user to enter something on each iteration of the loop, however I do not want this. I want the loop to run undisturbed until it needs to quit.
The script will be running as an executable in a command prompt (Windows) so I guess the user could just close the window but I want the loop to break at a certain point. For example:
while True:
print "Doing whatever I feel like"
userinput = raw_input()
if userinput == 'q':
break
So this keeps printing until the user enters 'q', but it prompts the user for input each iteration. How can I avoid this?
If you do not need to stop at a specific point, but just to be able to stop it, you could use a try/except with KeyboardInterrupt (Ctrl-C).
try:
while True:
print "Doing whatever I feel like"
except KeyboardInterrupt:
exit
When the user hits CTRL-C it will exit.
Or this:
import msvcrt
while True:
print "Doing whatever I feel like"
if msvcrt.kbhit(): # True if a keypress is waiting to be read.
if msvcrt.getch()=="q": # will not wait for Enter to be pressed
break
Check msvcrt.
Two possible solutions:
1. Press Ctrl-C to close your program. This also works on linux.
2.
while True:
for _ in range(100)
print "Doing whatever I feel like"
userinput = raw_input()
if userinput == 'q':
break
This only asks the user every 100 iterations.
Start a separate Thread to perform the computation that you need to perform while self.flag == False, and the main program can just sit there waiting for the user input. Once the user input is given, set Thread.flag = True, which will stop the Thread. Wait for the Thread to finish and join, then you can exit from the main program as well.

Python loop not working as intended

After selecting 2 as my choice on the menu, when I input 1 as the option, the program prints "Thanks for using.....Goodbye" and then loops back to the menu instead of stopping. I cannot figure out what the cause is, since I tried numerous times to fix it but failed. Please advise me what to do. Thanks
code: http://pastebin.com/kc0Jk9qY
Sorry I couldn't implement the code in this comment, was becoming a hassle.
All your code if in a while n!=1: loop. Set n=1 when you want to quit and that's it. So just change your code to the following and it will stop:
elif endex==1:
print "\nThank you for using RBDC Bin2Dec Converter \nGoodbye"
time.sleep(1)
error2=False
n=1
break will only terminate the innermost loop, so need to make sure all the outer ones get terminated as well.
EDIT
Changed code is:
if choice==2:
while error2:
try:
endex=input("Do you want to Exit? \nInput (1)y or (2)n: ")
if endex== 0 or endex >=3:
print"Try again"
if endex==2:
print "You have chosen to run this programme again...\n"
if endex==1:
print "\nThank you for using RBDC Bin2Dec Converter \nGoodbye"
time.sleep(1)
error2=False
n=1
What you have supplied looks correct. That break will break you out of the while error2 loop. So the problem must lie after that. I expect that if choice==2 is within another loop, and you are not breaking out of that.
OK, this is it. Your error2 value is uneccessary. Simply start an infinite loop and break out on valid responses. I would consider doing this in your other loops too.
if choice==2:
while True:
try:
endex=input("Do you want to Exit? \nInput (1)y or (2)n: ")
if endex== 0 or endex >=3:
print"Try again"
if endex==2:
print "You have chosen to run this programme again...\n"
break
if endex==1:
print "\nThank you for using RBDC Bin2Dec Converter \nGoodbye"
time.sleep(1)
n=1
break

Categories