Here is the code for a small program I just wrote to test some new things I learned.
while 1:
try:
a = input("How old are you? ")
except:
print "Your answer must be a number!"
continue
years_100 = 100 - a
years_100 = str(years_100)
a = str(a)
print "You said you were "+a+", so that means you still have "+years_100+" years"
print "to go until you are 100!"
break
while 2:
try:
b = str(raw_input('Do you want to do it again? If yes enter "yes", otherwise type "no" to stop the script.'))
except:
print 'Please try again. Enter "yes" to do it again, or "no" to stop.'
continue
if b == "yes":
print 'You entered "yes". Script will now restart... '
elif b == "no":
print 'You entered "no". Script will now stop.'
break
It works fine for the for loop. If you type something other than a number, it will tell you only numbers are allowed.
However, in the 2nd loop, it asks you to enter yes or no, but if you enter in something different, it just restarts the loop instead of printing the message after
except:
What did I do wrong and how do I fix it so it displays the message I told it to?
You do not get an exception, because you are always enter a string when using raw_input(). Thus str() on the return value of raw_input() will never fail.
Instead, add an else statement to your yes or no tests:
if b == "yes":
print 'You entered "yes". Script will now restart... '
elif b == "no":
print 'You entered "no". Script will now stop.'
break
else:
print 'Please try again. Enter "yes" to do it again, or "no" to stop.'
continue
Note that you should never use a blanket except statement; catch specific exceptions. Otherwise, you'll mask unrelated problems, making it harder for you to find those problems.
Your first except handler should only catch NameError, EOFError and SyntaxError for example:
try:
a = input("How old are you? ")
except (NameError, SyntaxError, EOFError):
print "Your answer must be a number!"
continue
as that's what input() would throw.
Also note that input() takes any python expression. If I enter "Hello program" (with the quotes), no exception would be raised, but it is not a number either. Use int(raw_input()) instead, and then catch ValueError (what would be thrown if you entered anything that's not an integer) and EOFError for raw_input:
try:
a = int(raw_input("How old are you? "))
except (ValueError, EOFError):
print "Your answer must be a number!"
continue
To use the second loop to control the first, make it a function that returns True or False:
def yes_or_no():
while True:
try:
cont = raw_input('Do you want to do it again? If yes enter "yes", otherwise type "no" to stop the script.'))
except EOFError:
cont = '' # not yes and not no, so it'll loop again.
cont = cont.strip().lower() # remove whitespace and make it lowercase
if cont == 'yes':
print 'You entered "yes". Script will now restart... '
return True
if cont == 'no':
print 'You entered "no". Script will now stop.'
return False
print 'Please try again. Enter "yes" to do it again, or "no" to stop.'
and in the other loop:
while True:
# ask for a number, etc.
if not yes_or_no():
break # False was returned from yes_or_no
# True was returned, we continue the loop
Related
still a beginner at programming, so forgive the mistakes:
I am trying to make my user-defined function loop until the user types in "no."
However, when I was adding extra functions to foolproof the loop, i.e. check to make sure what they typed was actually "yes" or "no" and not random garbage/numbers, it seems to run into problems. Here is the loop statement:
while True:
percentConvert()
stop = input("Would you like to continue? yes or no: ".lower())
print("You inputted:", stop) #added for debugging
if stop != "no" or "yes":
print("INVALID INPUT")
elif stop == "no":
break
else:
continue
First "if" is checking whether the input was not "no" or "yes", next "elif" is checking if the input was "no" and if so stop the program, and "else" (yes) continue. Instead, it asks if I would like to continue, tells me "INVALID INPUT" no matter what, and continues. What am I doing wrong?
stop != "no" or "yes" is not the correct syntax. What you want is either not (stop=="no" or stop=="yes") or stop not in ["no","yes"].
Consider the following modified version of your code:
while True:
percentConvert()
stop = input("Would you like to continue? yes or no: ".lower())
print("You inputted:", stop) #added for debugging
if stop not in ["no","yes"]:
print("INVALID INPUT")
elif stop == "no":
break
Note that the above, while it technically runs, will run percentConvert() in response to an invalid input. Here's a script that behaves in what I suspect is the desired way.
while True:
percentConvert()
while True:
stop = input("Would you like to continue? yes or no: ".lower())
print("You inputted:", stop)
if stop not in ["no","yes"]:
print("INVALID INPUT")
else:
break
if stop == "no":
break
In the loop as it's currently written, the condition is being interpreted as (stop != "no") or ("yes"). "yes" is a non-empty string, which Python considers to be a "truthy" value, which means that the or and if treat "yes" as if it were True, which means that the if-block always executes.
This is a good use case for using custom error handling.
First define the base class for errors, and a custom exception.
# define Python user-defined exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class InvalidInputError(Error):
"""Rasied when user input is not yes/no"""
pass
Then in your while loop, you can use the exception.
percentConvert()
while True:
try:
stop = input("Would you like to continue? yes or no: ".lower())
if stop == 'yes':
percentConvert()
continue
elif stop == 'no':
break
else:
raise InvalidInputError
except InvalidInputError:
print("Must enter either yes/no")
The below code is running however when I am trying to exit out of the code it goes into an infinite loop where even if i type in 1 still it does not break out of the loop. I am a beginner in Python please can anyone help me??
Here is my code,
import urllib2
import sys
urlToRead = ('https://www.google.com')
crawledWebLinks = {}
while urlToRead !='':
try:
urlToRead = raw_input('Please enter the Next weblink to crawl')
if urlToRead == '':
print ('Ok Existing the Loop')
break
shortName = raw_input('Please enter a short Name for the Url to Read ' + urlToRead)
webfile = urllib2.urlopen(urlToRead).read()
crawledWebLinks[shortname] = webfile
except:
print (sys.exc_info()[0])
stopOrproceed = raw_input('You want to Stop or Continue, Please type in 1 to stop or anything else to Continue')
if stopOrproceed == 1:
print ('Okies we are stopping')
break
else:
print ('lets continue')
continue
print (crawledWebLinks.keys())
The following few lines are the ones causing problem,
stopOrproceed = raw_input('You want to Stop or Continue, Please type in 1 to stop or anything else to Continue')
if stopOrproceed == 1:
print ('Okies we are stopping')
break
You see raw_input gets input and stores it as a string. So after getting the value from user. your stopOrproceed variable would have "1"
And when you check for stopOrproceed==1 --> "1"==1. Which is definitely not equal in Python. So always false is evaluated And hence the control never goes inside the if and thus you never break.
Try changing that to this,
if stopOrproceed == "1":
print ('Okies we are stopping')
break
I am attempting to exit a program without using sys.exit()
The user is asked whether they wish to continue and if they input "Yes" a message saying so is printed and the program continues to run. If they input anything else a message saying they chose to exit is printed and then the program is meant to exit.
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
else:
print "You have chosen to quit this program"
What I am struggling with is what to add to ELSE to return something to my main which will cause the program to exit and how to go about writing that in code.
If you are so much keen about not using sys.exit() you could directly use raise SystemExit. Well this exception is technically raised when you call sys.exit() explicitly. In this way you don't need to import sys at all.
def keep_going():
answer = raw_input("Do you wish to continue?")
if (answer == "yes"):
print ("You have chosen to continue on")
else:
print "You have chosen to quit this program"
raise SystemExit
This answer will give you the alternate possible ways.
Try this:
def main():
while keep_going():
keep_going()
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
return True
else:
print "You have chosen to quit this program"
return False
if __name__ == "__main__":
main()
The program will continue calling keep_going() as long as it returns true, that is when a user answers "yes"
An even shorter solution would be to call keep_going() after the "yes" condition:
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
keep_going()
else:
print "You have chosen to quit this program"
Just, return something, and if that is returned, then let your main function exit, either by falling off the end, by using a return statement, or calling sys.exit()/raise SystemExit.
As an example, I'm here returning a string (a different one based on what the user answered):
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
return "keep going"
else:
print "You have chosen to quit this program"
return "please exit"
Now, in main, I can test which of these strings keep_going() returned:
def main():
while keep_going() != 'please exit':
# your code here
if __name__ == "__main__":
main()
While strings will work for this purpose, other values are more commonly used for such a task. If keep_going() returned True (instead of "keep going") or False (instead of "please exit"), then main could be written like
def main():
while keep_going():
# your code here
This also reads pretty naturally ("while keep going do your code"). Note that in this case I'm not comparing the return value to something since True and False are truthy variables - and Python's branching control structures (like if and while) know how they work, i.e. there is no need to write keep_going() == True, and indeed it is considered un-pythonic to do so.
You can try this
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
else:
print "You have chosen to quit this program"
quit()
def answer():
if True:
ans = raw_input('Enter y/n:')
if ans != "y" and ans != "n":
print "Try again"
answer()
elif ans == "n":
return False
elif ans == "y":
return True
if answer():
print "It's working!, you entered Y"
else:
print "You entered N"
When I execute this code, I press Enter several times or enter wrong letters, then I enter y, I always get "You entered N" instead of "It's working!, you entered Y" .
I can't figure out what's the problem, please help me.
You are discarding the return value of your function in the if block. You should change it to:
if ans != "y" and ans != "n":
print "Try again"
return answer()
If you don't return the value, your function will return None, which will be evaluated as False on the outer if. Also, there is no need of if True: inside your function.
P.S: Please avoid using recursion for this task. You can easily do this with a while loop, which iterates till the user doesn't pass correct input, and breaks as soon as succeeds. Also, give user a certain number of attempts to pass correct inputs, to avoid infinite loop.
You don't really need recursion in this case, just use an infinite loop and don't return if the answer is not "y" or "n":
def answer():
while True:
ans = raw_input('Enter y/n:')
if not ans or ans not in "yn":
print "Try again"
else:
return ans == "y" # This is more succinct
if answer():
print "It's working!, you entered Y"
else:
print "You entered N"
I have a problem with a condition in my python code.
It's a mathematics application, and here's the part of the code that is not working well:
def askNumber():
"""Asks the number to test"""
a=raw_input("Select the number to test (type 'exit' for leaving):")
if len(a)!=0 and a.lower!="exit":
try:
b= int(a)
processing(b)
except ValueError:
print "Your input is not valid. Please enter a 'number'!"
time.sleep(1)
askNumber()
elif len(a)!=0 and a.lower=="exit":
answer()
else:
print "Your input can't be 'empty'"
time.sleep(1)
askNumber()
So, when in the raw_input for "a" I type "exit", the supposed condition to apply is the elif one but ends up applying the if one, ending up printing "Your input is not valid. Please enter a 'number'!" Sorry, if it's something obvious, I'm a begginer, although I tried to find the mistake several times.
You need to call the .lower() function.
if len(a) != 0 and a.lower() != "exit":
# ...
elif len(a) != 0 and a.lower() == "exit":
There is no real need to test for len(a)!=0, simply test for a itself:
if a and a.lower() != "exit":
# ...
elif a and a.lower() == "exit":
Empty strings evaluate to False in a boolean context.
Your program flow is a bit inside out, may I suggest some improvements?
def askNumber():
"""Asks the number to test"""
while True:
a = raw_input("Select the number to test (type 'exit' for leaving):")
if not a:
print "Your input can't be 'empty'"
continue
if a.lower() == "exit":
answer()
break
try:
b = int(a)
except ValueError:
print "Your input is not valid. Please enter a 'number'!"
continue
processing(b)
Actually, the not a branch can be eliminated as well (empty inputs will be handled in except).
You could change the condition for the following one:
if a and a.lower() !="exit":
# .....
elif a and a.lower() == "exit":
answer()
elif a and not a.isdigit(): print "invalid input"
else:
#.............
Please note that yo don't need len(a) != 0 , just by using a will evaluate if it's empty or not.