Python: end execution in while loop - python

we are beginners and want to code the game Mastermind in Python. (Please see our code below.)
Problem:
We want to end the execution of the code if the 'StopIteration' error occurs in the 'while' loop. But somehow 'quit()' doesn't work in this place. Can anyone give us a clue how to solve this problem?
def inconsistent(new_guess, guesses):
for guess in guesses:
res = check(guess[0], new_guess)
(rightly_positioned, right_colour) = guess[1]
if res != [rightly_positioned, right_colour]:
return True # inconsistent
return False # i.e. consistent
while inconsistent (new_guess, guesses):
try:
new_guess=next(generator)
except StopIteration:
print("Error: Your answers were inconsistent!")
break

Break should work. If you want to skip this guess you could use
continue

Related

Function with two loops

I want to make a function what must have 2 loops:
must check that at least 2 characters (letters) are inserted
if the two characters are in the form that the variable must receive at the end, the variable receives the correct orthographic form.
Here is my code (but it throws me in infinite loop) [Please be indulgent im a begginer (: ] :
def sede():
while True:
import re
var_sede_0 = input("Sede : ")
if re.match("([a-zA-Z]+.*?){2,}", var_sede_0):
while True:
if var_sede_0.lower() in 'torino (to)':
var_sede_0 = 'Torino (TO)'
break
elif var_sede_0.lower() in 'reggio calabria (rc)':
var_sede_0 = 'Reggio Calabria (RC)'
break
else:
print("sbagliato")
continue
break
else:
print("formato sbagliato")
continue
return var_sede_0
var_sede = sede()
Your inner loop is the problem:
while True:
if var_sede_0.lower() in 'torino (to)':
var_sede_0 = 'Torino (TO)'
break
elif var_sede_0.lower() in 'reggio calabria (rc)':
var_sede_0 = 'Reggio Calabria (RC)'
break
else:
print("sbagliato")
continue
Consider that nowhere in this loop do you take in new input, so var_sede_0 can never possibly change. Given that, if the first two predicates (if statements) evaluate to false, then you will be in an infinite loop printing out sbagliato. You can probably simply remove the while True (the inner one) and get to what you want.
It is key to note that break and continue really only affect the immediate while context that they are in - they will not 'speak to' the outer while loop.
You also probably do not want to be importing re on every loop. Move import re to the top of your file.

Algorithm for python do-while loop

while True: #exception loop
try:
NumOfPpl=raw_input('Enter the number of people: ')
NumOfPpl=int(NumOfPpl)
break #for early exit the loop if num is an integer
except ValueError:
print ("\nPlease make sure you key in number only! \n\tand please do not leave blank!")
print "\nIs there any of theese person present?: \n\tA. Disabled \n\tB. 65-years-old and above \n\tC. None for Both A. and B. \n"
Above is only a fragment of my code. What I want to know is, how to write it in algorithm and pseudocode version? Or even for flowchart as requested for school assignment. Please and thank you.

Python won't advance

Question: What would be the issue if python continues to ask for the same input over and over again, and won't advance to the end of the program?
Where do you want to go? X
And how many days will you be staying in X? 1
And how many days will you be staying in X? 2
And how many days will you be staying in X? 164
And how many days will you be staying in X? 59
...
Here's the relevant part of the code:
# Import modules
import destinations
import currency
save_itinerary = True
main_function = True
while (main_function):
# Determine length of stay
while True:
try:
length_of_stay = int(input("And how many days will you be staying in " + destinations.destination[0] + "? "))
# Check for non-positive input
if (length_of_stay <= 0):
print("Please enter a positive number of days.")
continue
except ValueError:
print("The value you entered is invalid. Only numerical values are valid.")
break
else:
break
The reason your code is looping forever is that you have two nested while loops, and you never break out of the outer one. You do use break statements to exit the inner loop, but the condition for the outer loop is never changed, and you never execute a break at the right level to exit it.
Here's what I think a better version of your code would be:
# get rid of the outer while loop, which was never ending
while True:
try:
length_of_stay = int(input("And how many days will you be staying in " + destinations.destination[0] + "? "))
if (length_of_stay <= 0):
print("Please enter a positive number of days.")
continue
except ValueError:
print("The value you entered is invalid. Only numerical values are valid.")
# don't break here, you want to stay in the loop!
else:
break
I've used comments to indicate my changes.
You could also move the else: break block up and indent it so that it is attached to the if statement, rather than the try/except statements (and then get rid of the unnecessary continue statement). That's makes the flow a bit more obvious, though there's not really anything wrong with how it is now.

Is the `else:` correct/necessary in this Python program?

Is the line of else: correct/necessary in this Python program?
from random import randrange
for n in range(10):
r = randrange(0,10) # get random int in [0,10)
if n==r: continue # skip iteration if n=r
if n>r: break # exit the loop if n>r
print n
else:
print "wow, you are lucky!\n"
if n<9:
print "better luck next time\n
From the documentation:
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement
So yes, it's correct in your example. Although I've never been a fan of it, using an else clause on a loop makes code confusing at first, I'd rather use a boolean flag for achieving the same effect. IMHO else should be used only for conditionals.
from random import randrange
for n in range(10):
r = randrange(0,10)
if n=r: continue # there should be ==
if n>r: break
print n # should be "\n" ?
else:
print "wow, you are lucky!\n" # Yes, you are! Your python interpreter can make miracles :). Try to run me.append(SexyChick(10)) and let's see what happens!
for...else construct is actually valid. else branch is executed if the loop has not been terminated by break. Look here.

Try statement - multiple conditions - Python 2

I have little problem with try statement along with multiple conditions. When there is error at 2nd condition, it asks for 1st condition. What I want from it to do is to repeat the same condition, not the whole cycle. I hope you understand me, since my English isn't very good and also I'm newbie to Python so I also don't know how to describe it in my native language.
I hope the following example will help you to better understand my thought.
while True:
try:
zacatek = float(raw_input("Zacatek: "))
konec = float(raw_input("Konec: "))
except Exception:
pass
else:
break
it does following:
Zacatek: 1
Konec: a
Zacatek:
but I want it to do this:
Zacatek: 1
Konec: a
Konec:
Thanks in advance for any help.
Write a function to query for a single float, and call it twice:
def input_float(msg):
while True:
try:
return float(raw_input(msg))
except ValueError:
pass
zacatek = input_float("Zacatek: ")
konec = input_float("Konec: ")
What's happening is that your except clause is catching a ValueError exception on your answer to Konec and returning to the top of the loop.
Your float function is trying to cast a non-numeric response "a" to a float and it throwing the exception.
Alternatively, you could write a different loop for each input:
zacatek = None
while not zacatek:
try:
zacatek = float(raw_input("Zacatek: "))
except Exception:
continue
konec = None
while not konec:
try:
konec = float(raw_input("Konec: "))
except Exception:
continue

Categories