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.
Related
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
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.
i have troubling handling input in python. I have a program that request from the user the number of recommendations to be calculated.He can enter any positive integer and blank(""). I tried using the "try: , except: " commands,but then i leave out the possibility of blank input. By the way blank means that the recommendations are going to be 10.
I tried using the ascii module,but my program ends up being completely confusing. I would be glad if anyone could get me on the idea or give me an example of how to handle this matter.
My program for this input is :
while input_ok==False:
try:
print "Enter the number of the recommendations you want to be displayed.\
You can leave blank for the default number of recommendations(10)",
number_of_recs=input()
input_ok=True
except:
input_ok=False
P.S. Just to make sure thenumber_of_recs , can either be positive integer or blank. Letters and negative numbers should be ignored cause they create errors or infinite loops in the rest of the program.
while True:
print ("Enter the number of the recommendations you want to " +
"be displayed. You can leave blank for the " +
"default number of recommendations(10)"),
number_of_recs = 10 # we set the default value
user_input = raw_input()
if user_input.strip() == '':
break # we leave default value as it is
try:
# we try to convert string from user to int
# if it fails, ValueError occurs:
number_of_recs = int(user_input)
# *we* raise error 'manually' if we don't like value:
if number_of_recs < 0:
raise ValueError
else:
break # if value was OK, we break out of the loop
except ValueError:
print "You must enter a positive integer"
continue
print number_of_recs
I want to write a python program, first it asks you to enter two numbers, and then output all daffodil numbers between the two numbers, and it will continue run, until I enter a "q". I write a program, but it is wrong:
#coding=utf-8
while 1:
try:
x1=int(raw_input("please enter a number x1="))
x2=int(raw_input("please enter a number x2="))
except:
print("please enter only numbers")
continue
if x1>x2:
x1,x2=x2,x1
pass
for n in xrange(x1,x2):
i=n/100
j=n/10%10
k=n%10
if i*100+j*10+k==i+j**2+k**3:
print ("%-5d")%n
pass
Can somebody help? I think it should be simple, but I am not able to write it correctly.
I believe you've misunderstood the problem statement. Try this instead:
if i*100+j*10+k==i**3+j**3+k**3:
ref: http://en.wikipedia.org/wiki/Narcissistic_number
for n in xrange(x1,x2):
digits = map(int,str(n))
num_digits = len(digits)
if sum(map(lambda x:x**num_digits,digits)) == n:
print "%d is a magic number"%n
you will still have the issue of not being able to enter "q" since you force the input to be integers
I would like to address the quit event.
while True:
x1 = raw_input("please enter a number x1=")
x2 = raw_input("please enter a number x2=")
quit = ('q','Q')
if x1 in quit or x2 in quit:
break
else:
try:
x1, x2 = int(x1), int(x2)
except:
print("please enter only numbers")
continue
# The mathematical part... (for completeness) (not my code)
if x1>x2:
x1,x2=x2,x1
for n in xrange(x1,x2):
i=n/100
j=n/10%10
k=n%10
if i*100+j*10+k==i+j**2+k**3:
print "%-5d"%n
The pass statement is used only when you don't have anything to be executed in certain block of code. It does nothing more, so don't use it if not needed. It is there for the sake of the code looking clean & with correct indentation.
if some_thing: # don't do anything
else:
some_thing = some_thing_else
Note how the above if statement is syntactically incorrect. This is where pass comes handy. Say, you decide to write the if part later, till then you must provide pass.
if some_thing: # don't do anything
pass
else:
some_thing = some_thing_else
It's a bit tricky to know what's going on without more hints, but some issues I see right off:
You need to be consistent with indentation in Python. Your last if statement is less indented than statements above it (like the previous if and the for loop). This will cause an error. You're also using different amounts of indentation in other places, but since it's not inconsistent that's allowed (if a bad idea). Its usually best to pick one indentation standard (like four spaces) and stick with it. Often you can set your text editor to help you with this (turn on "Expand tabs to spaces" or something in the settings).
You've got two pass statements where they're unneeded or harmful. The first, after the line that has if x1>x2: x1,x2=x2,x1 is going to cause an error. You can't have an indented "suite" of code if you've put a series of simple statements on the end of your compound statement like an if. Either put the assignment on its own line, indented, or get rid of the pass. The last pass at the end of the code is not an error, just unnecessary.
You're missing a colon at the end of your try statement. Every statement in Python that introduces an indented suite ends with a colon, so it should be easy to learn where they're needed.
while True:
x1 = raw_input("please enter a number x1=")
x2 = raw_input("please enter a number x2=")
quit = ('q','Q')
if x1 in quit or x2 in quit:
break
else:
try:
x1, x2 = int(x1), int(x2)
except:
print("please enter only numbers")
continue
if x1>x2:
x1,x2=x2,x1
pass
for n in xrange(x1,x2):
i=n/100
j=n/10%10
k=n%10
if i*100+j*10+k==i+j**2+k**3:
print ("%-5d")%n
pass
i have it! thx to Ashish! it is exactly what i want! and i will quit wenn i enter q! thx a lot!
I am trying to analyse user input and only allow integers to be inputted. I have succesfully managed to only allow denominations of 100s between a certain range, but I cannot work out how to prompt the user to re-enter data if they enter a random string.
Trying to use the "try" command just results in the program getting stuck:
while True:
try:
bet=int(raw_input('Place your bets please:'))
except ValueError:
print 'l2type'
#The following receives a betting amount from the user, and then assesses whether it is a legal bet or not. If not, the user is prompted to enter a legal bet.
while True:
if bet%100==0 and 100<=bet<=20000:
print bet,"Your bet has been accepted, can you make a million?"
break
else:
print bet,"Please enter a legal bet. The table minimum is 100, with a maximum of 20000 in increments of 100."
bet = input('Place your bets please:')
You have the right approach for rejecting non-integer input, but you need to break out of the loop if your user enters valid input. Use the break statement:
while True:
try:
bet=int(raw_input('Place your bets please:'))
break # we only get here if the input was parsed successfully
except ValueError:
print 'l2type'
You will probably also want to move the range checks within the loop. If input that's out of range doesn't naturally lead to an exception, use if statements to make sure "break" is only executed if the input is completely valid.
I rather prefer my recursive version:
def ask_bet(prompt):
bet = raw_input(prompt)
# Validation. If the input is invalid, call itself recursively.
try:
bet = int(bet)
except ValueError:
return ask_bet('Huh? ')
if bet % 100 != 0:
return ask_bet('Huh? ')
if not 100 <= bet <= 20000:
return ask_bet('Huh? ')
# The input is fine so return it.
return bet
ask_bet("Place your bets please: ")
In my opinion, that is much cleaner and easier to read than while loops. You don't have to bother what are attribute values after the first iteration? Adding new validation rules is also really simple.
Generally, I try to avoid while loop in favour of recursive version. Of course, not all the time, since it's slower and the stack is not infinite.