Python while loop not stopping? - Stack Overflow
Python - While loop won't stop - Stack Overflow
python - While loop doesn't stop - Stack Overflow
python - Why doesn't the while loop stop when the condition becomes False? - Stack Overflow
Videos
No matter where I put the break or “return,” it just won’t work. I need it to end then go onto the next defined function (printInvoice) but it either continues on an endless loop or ends but won’t go onto the next function.
Here's the code:
Dictionary1 = {'Brad': 18.99, 'Chad': 16.99, 'Andy': 15.99, 'Suzy': 12}
Shipping = {'Ally Express': [10.00, 0.50], 'DHL Express': [11.75, .35], 'Bob Economy': [10.00,40], 'Queen Priority':[13.00, 0.40]}
GST = 0.05
def checkInput():
order = []
while True:
for value in Dictionary1:
try: decision = int(input("How many sets of " + value + " do you want?"))
order.append(str(decision))
except ValueError:
print("You did not enter an integer")
decision = int(input("How many sets of " + value + " do you want?"))
break
def printInvoice(order):
print("We can deliver by Ally Express, Bob Economy or Queen Priority Shipping")Because you're using while True and True is always equal to True, so this loop will never stop. You can do something like this:
while True:
if P1 != cg2:
cg2 = (mn+mx)/2 #guess based on middle of highest and lowest
print "Computer has guessed: %d" %cg2
previousguess.append(cg2)
count2+=1
else:
print "The Computer has guessed it in %d times" %count2
break # use break to break the loop
Or just like this:
while P1 != cg2:
cg2 = (mn+mx)/2 #guess based on middle of highest and lowest
print "Computer has guessed: %d" %cg2
previousguess.append(cg2)
count2+=1
if P1 != cg2 is equal to False, this loop will terminated.
Try this:
while P1 != cg2:
cg2 = (mn+mx)/2 #guess based on middle of highest and lowest
print "Computer has guessed: %d" %cg2
previousguess.append(cg2)
count2+=1
You will also need to properly update mn & mx within the loop. These are not the only problems, but they should get you to the next stage of debugging. Please consider adding print statements to track the progress of your program, both where it goes and what data it computes.
num_of_runs = sys.argv[1]
num_of_runs is a string at that stage.
while self.run_number <= self.num_of_runs:
You are comparing a string and an int here.
A simple way to fix this is to convert it to an int
num_of_runs = int(sysargv[1])
Another way to deal with this is to use argparser.
import argparse
parser = argparse.ArgumentParser(description='The program does bla and bla')
parser.add_argument(
'my_int',
type=int,
help='an integer for the script'
)
args = parser.parse_args()
print args.my_int
print type(args.my_int)
Now if you execute the script like this:
./my_script.py 20
The output is:
20
Using argparser also gives you the -h option by default:
python my_script.py -h
usage: i.py [-h] my_int
The program does bla and bla
positional arguments:
my_int an integer for the script
optional arguments:
-h, --help show this help message and exit
For more information, have a look at the argparser documentation.
Note: The code I have used is from the argparser documentation, but has been slightly modified.
When accepting input from the command line, data is passed as a string. You need to convert this value to an int before you pass it to your Crawler class:
num_of_runs = int(sys.argv[1])
You can also utilize this to determine if the input is valid. If it doesn't convert to an int, it will throw an error.
A while loop does not terminate when the condition becomes false. It terminates when it evaluates the condition and the condition is found to be false. That evaluation doesn't happen until the beginning of each loop iteration, not immediately after some event occurs that will allow the condition to become false.
A better way to write this loop is to simply use True as the condition, as it doesn't require you to initialize command to a known non-terminating value, then let a break statement somewhere the loop terminate the command when appropriate.
started = False
while True:
command = input('Enter a Command: ').lower()
if command == 'quit':
break
if command == 'start':
if started:
print("Car already Started! Let's go!")
else:
started = True
print("Car Started.... Ready to Go!!!")
elif command == 'stop':
if not started:
print('Car already stopped!')
else:
started = False
print('Car stopped!')
elif command == 'help':
print(" 'start' - to start the car\n'stop' - to stop the car\n'quit' - to quit/close the game.")
else:
print('Sorry, I do not understand that!')
Of course, you don't need two separate if statements as I've shown here; you could combine them into one with if command == 'start' being the first elif clause of the combined if statement. But this provides an explicit boundary between "code that terminates the loop" and "code that allows the loop to continue".
The program actually stops when you type quit, but before stopping it prints "Sorry, I do not understand that!". You can fix this by putting command = input('Enter a Command: ').lower() before while and in the end of the while like this (so that while will check if command != quit immediately after inputing):
command = ''
started = False
command = input('Enter a Command: ').lower()
while command != 'quit':
if command == 'start':
if started:
print("Car already Started! Let's go!")
else:
started = True
print("Car Started.... Ready to Go!!!")
elif command == 'stop':
if not started:
print('Car already stopped!')
else:
started = False
print('Car stopped!')
elif command == 'help':
print(" 'start' - to start the car\n'stop' - to stop the car\n'quit' - to quit/close the game.")
else:
print('Sorry, I do not understand that!')
command = input('Enter a Command: ').lower()
A common, but very frustrating and time-wasting typo, which can get even the best Python developers. Replace roll2 == random.randint(1,6) + random.randint(1,6) with roll2 = random.randint(1,6) + random.randint(1,6).
Also, I think you need roll2 != roll and roll2 != 7. From a stylistic point of view, it's better to omit the parenthesis around the statement evaluated in an if or while line.
Your loop has a slight amount of redundancy in it though. You check for roll2 being roll or 7 at the top of each loop and at the end of each loop. You could also consider trying this:
while True:
# do everything in the same way as before
or
while roll2 != roll and roll2 != 7:
# do stuff with the roll
roll = random.randint(1,6) + random.randint(1,6)
return 1 if roll2 == roll else return 0 # a "ternary operator" in Python
A double equals sign tests for equality. Change it to single for your code to work. Here is your edited code:
import random
def craps()
roll = random.randint(1,6) + random.randint(1,6)
if (roll == 7 or roll == 11): #Tests if the player should win. If so it adds a 1 to the win counter
return 1
elif (roll == 2 or roll == 3 or roll == 12): #Tests if player should lose. If so adds 0
return 0
else:
roll2 = 0 #initializes roll2 for the while
while (roll2 != roll or roll2 != 7): #The player keeps rolling until they get a 7 or the initial roll
roll2 = random.randint(1,6) + random.randint(1,6) #Rolls the dice
if (roll2 == roll): #Tests if the player should win
return 1
elif (roll2 == 7): #Tests if the player should lose
return 0
win = 0 #Start the win counter at 0
games = int(input("Enter the amount of games you want played: ")) #Accept how many games will be played
for i in range (games):
win = win + craps() #adds a 1 or a 0 depending on if a game was won
print ("The probability of winning is:", win, "/", games, " =", float(win)/games) #print the probability of winning
Here is an example:
>>> import time
>>> x = 7
>>> x == 7
True
>>> while x != 6:
... x == 6
... time.sleep(1)
...
False
False
False
^CTraceback (most recent call last):
File "<stdin>", line 3, in <module>
KeyboardInterrupt
>>> while x != 6:
... x = 6
... time.sleep(1)
...
>>>
login_or_register != 'login' or login_or_register != 'register' will always be True. You probably want to use a logical and:
while login_or_register != 'login' and login_or_register != 'register':
# ....
The condition of your loop cannot possibly become true.
or returns True if one or both of the two conditions becomes True.
If your input is 'login', the first condition is False and the second is True.
For 'register' the first condition becomes True and the second 'False'.
In all other cases both conditions are True. Therefore you have created an infinite loop.
A solution would be connecting the two conditions with an and or even better create a list with all allowed inputs and use an in to check if the user input is in that list. That will be more clear if you have more different options the user is allowed to enter.
For example:
login_or_register = None
while login_or_register not in ['login', 'register']:
login_register = input('Would you like to login or register?')
login_or_register = login_register.lower()
You may also want to take a look at the python docs for or and and
this is b/c the while True does not end unless you use the keyword break wich breaks outside the loop and continues the code.
the while True never ends
the while loop
while (condition):
#code
never ends until the condition is False, witch would never be true for the True condition.
do your code should be:
game_list = ['0','1','2']
while True:
position = myfunc()
replacement(game_list,position)
if not play_again():
break
print(game_list)
or you could do:
game_list = ['0','1','2']
while play_again():
position = myfunc()
replacement(game_list,position)
print(game_list)
This code should work:
while (play_again()):
position = myfunc()
replacement(game_list,position)
You should know that in Python a while loop (like in every other programming language) takes a single "argument", that is a condition of type bool:
while (i > 3): # i>3 is a boolean condition
...
In fact this is equivalent to
while (True): # the loop continues until condition is False, so in this case it will never stop
if (i > 3):
break
In Python break is a keyword that makes you exit the loop.
Then, as you probably understood, this code is equivalent to the first snippet in this answer:
while (True):
position = myfunc()
replacement(game_list,position)
if (not play_again()):
break
just indent your code correctly:
def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
return period
if period>12: #i wrote this line to stop it..but seems its doesnt work....help..
return 0
else:
return period
You need to understand that the break statement in your example will exit the infinite loop you've created with while True. So when the break condition is True, the program will quit the infinite loop and continue to the next indented block. Since there is no following block in your code, the function ends and don't return anything. So I've fixed your code by replacing the break statement by a return statement.
Following your idea to use an infinite loop, this is the best way to write it:
def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
break
if period>12: #i wrote this line to stop it..but seems its doesnt work....help..
period = 0
break
return period
def determine_period(universe_array):
period=0
tmp=universe_array
while period<12:
tmp=apply_rules(tmp)#aplly_rules is a another function
if numpy.array_equal(tmp,universe_array) is True:
break
period+=1
return period
I think your understanding of what a while loop does is incorrect. The loop condition is only checked at the top of the loop, so, once before searchUnguided is called and never again (since you have a break statement after the last call). It is not tested in between the function calls.
What I think you want is something like this:
sky = searchUnguided(searchUnguided(inframe, skysearch, debug=debug)
if sky == "none":
sky = searchPQ(ad, skysearch, maxpq, debug=debug)
if sky == "none":
sky = searchAB(ad, maxpq, debug=debug)
# you may want another "if" here to do something else if sky is still "none"
The while loop will have no effect in this case, because the first time around it will evaluate to true and there will be no evaluation the second time around due to the break
looks like ifs are not a bad way to go
Hey everyone,
I've been learning Python for about a month, and I just recently got into exceptions. I was working through a problem from a book, and I can't figure out why my while loop isn't functioning how I want it to. The problem asks me to write a code in which you take in two numbers as input values and add them while also accounting for the "ValueError" exception. In my code, which I've linked below, the while loop doesn't terminate when I enter "quit" as the first_number. It only terminates when I enter it as the second_number. In other words, it only breaks when I enter "quit" twice in a row. However, since I use the "or" keyword, shouldn't the while loop terminate if I enter "quit" as either the first or second number? My code is linked below along with what I see in the terminal. Any help or feedback would be appreciated. Thank you.
Code: while loop code
Terminal: output
It does terminate if your enter quit as the first number and anything else as the second number. But you still need to enter the second number, because it doesn't check what was entered until after both inputs.
At the moment, your code is doing this:
ask for first input
ask for second input
check inputs
If you want it to be able to terminate before asking for the second input, you will need to check the first input before asking for the second.
ask for first input
check first input
ask for second input
check second input
I'm doing a CS50p project on making a grocery list. The only issue I'm having is once the list prints, I need the program to end. No matter where I break, it either doesn't stop the program or does stop it but bugs something else.
This is what I have:
def main():
list = []
while True:
try:
item = input()
list.insert(0, item)
continue
except EOFError:
list.sort()
while list != None:
for word in list:
x = list.count(word)
if x != 0:
print(str(x) + " " + str.upper(word), sep=" ")
list = [i for i in list if i!=word]
else:
break
breakmain()