Python: How to keep repeating a program until a specific input is obtained?
There are two ways to do this. First is like this:
while True: # Loop continuously
inp = raw_input() # Get the input
if inp == "": # If it is a blank line...
break # ...break the loop
The second is like this:
inp = raw_input() # Get the input
while inp != "": # Loop until it is a blank line
inp = raw_input() # Get the input again
Note that if you are on Python 3.x, you will need to replace raw_input
with input
.
How to repeat a section of the program until the input is correct?
Add a while
-loop there. This means you're looping the question again infinitely until you've reached a satisfactory result.
while True:
ghuess=input("state a number between 1-100")
if ghuess>number:
print "too high try again!"
elif ghuess<number:
print "too low try again!"
else:
# Jackpot, exit the loop.
break
print "well done! ghuess you have won.."
time.sleep(1)
print "3"
time.sleep(1)
print "2"
time.sleep(1)
print "1"
time.sleep(1)
print prize
How do I make a program keep repeating until I input a specific data that stops it?
Here it is:
def program():
pass
user_input = int(input())
while user_input:
program()
user_input = int(input())
quit(0)
How to keep repeating a program until a specific input?
Just move the input
into the loop:
x = None
lis = []
while x != '':
x = input('Enter a number: ')
if x != '':
lis.append(int(x))
avg = sum(lis) / len(lis)
print(avg)
Also you don't need the if
statement as x
must be equal to ''
anyway so that the while
loop terminates.
How to use a While Loop to repeat the code based on the input variable
Firstly you should remove
value = input("number?:\n")
print(f'you have chosen: {value}')
value = int(value)
from the top of your code, everything must be inside your __main__ program.
Basically what you need to do is create a main While loop where your program is gonna run, it will keeps looping until the response is not "yes".
For each iteration, you ask a new number at the beggining and if it has to keep looping at the end.
Something like this:
# driver program
if __name__ == '__main__':
# starts as "yes" for first iteration
pitanje = "yes"
while pitanje == "yes":
# asks number
value = input("number?:\n")
print(f'you have chosen: {value}')
value = int(value)
# show results
start: SieveOfEratosthenes(value)
# asks for restart
pitanje = input("do you want to continue(yes/no)?")
#if it's in here the response wasn't "yes"
print("goodbye")
How to repeat the input until a special condition is meet in Python?
When the exception happens, a
remains unset. Try this instead.
s = set()
# Notice also correct quoting
print("Please type the number, when you're done please type 'Done':")
while True:
a = input()
try:
n = int(a)
s.add(n)
# Avoid blanket except
except ValueError:
if a == "Done":
break
else:
print('Integer only, please re-type:')
continue
print(s)
Loop until a specific user input
As an alternative to @Mark Byers' approach, you can use while True
:
guess = 50 # this should be outside the loop, I think
while True: # infinite loop
n = raw_input("\n\nTrue, False or Correct?: ")
if n == "Correct":
break # stops the loop
elif n == "True":
# etc.
Loop from the start of the code until the user says stop in Python
I solve your problem by moving your inner while
loop into the else
case. Also, in the if
statement N == 'Y'
, I insert one more N = input(...)
command:
N = input("Do you want to continue to find factors Y/N: ").upper()
while True:
if N == 'Y':
print_factors(int(input("Enter a number: ")))
N = input("Do you want to continue to find factors Y/N: ").upper()
elif N == 'N':
break
else:
while N not in 'YN':
print("Invalid input, please try again.")
N = input("Do you want to continue to find factors Y/N: ").upper()
Result:
Please enter a number: 15
The factors of 15 are:
1
3
5
15
Do you want to continue to find factors Y/N: y
Enter a number: 23
The factors of 23 are:
1
23
Do you want to continue to find factors Y/N: e
Invalid input, please try again.
Do you want to continue to find factors Y/N: y
Enter a number: 32
The factors of 32 are:
1
2
4
8
16
32
Do you want to continue to find factors Y/N: n
>>>
- Side note: running on Python 3.9.1, Window 10.
- Maybe you would want to include the same
try-catch
block into the user-controlledwhile
loop.
Related Topics
How to Merge Elements in List in Python With Condition
Removing White Space Around a Saved Image
Replace Empty Strings With None/Null Values in Dataframe
How to Avoid Last Comma in Python Loop
How to Change a Two Dimensional Array to One Dimensional
In Python, How to Check If a Date Is Valid
Number of Common Letters in Two Strings
How to Get the Url of the Active Google Chrome Tab in Windows
How to Add an Attention Mechanism in Keras
How to Get Value from Json List Within Robot Framework
Compare a Column Between 2 CSV Files and Write Differences Using Python
Winerror 10049: the Requested Address Is Not Valid in Its Context
Cv2 Image Error: Error: (-215:Assertion Failed) !Ssize.Empty() in Function 'Cv::Resize'
Google Chrome Closes Immediately After Being Launched With Selenium
Combine Year, Month and Day in Python to Create a Date
Drop Rows Containing Empty Cells from a Pandas Dataframe
Matplotlib: Attributeerror: 'Axessubplot' Object Has No Attribute 'Add_Axes'