Python condition not applying (if/elif) - python

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.

Related

Can anyone find any bugs or mistakes in this code?

I have been working on this code for hours, and I still can solve it.
inside the function build a forever loop (infinite while loop) and inside the loop complete the following
I want it to use a variable to gather input which is supposed to be either an integer of 'q' to quit.
It should check if the input string is a digit (integer) and if it is...
add input integer to report variable.
If the variable is "A" add the numeric character(s) to the item string seperated by a new line.
If the report type is q,
If the report type is "A" print out all the integer items entered and the sum total.
If report type is "T" then print out the sum total only
break out of while loop to end the function after printing the report ("A" or "T").
If not a digit and if not a "Q" then print a message that the "input is invalid".
def adding_report(report=[]):
report = []
at = input("Choose a report type: 'A' or 'T' : ")
while at.lower() != 'a' and at.lower() != 't':
print('what?')
at = input("Choose a report type: 'A' or 'T' : ")
while True:
re = input("print an integer or 'Q' : ")
if re.isdigit() is True:
report.append(re)
report.append('\n')
elif re.startswith('q') is True:
if at.lower() == 'a' is True:
break
print(report)
print(sum(report))
elif at.lower() == 't' is True:
print(sum(report))
break
else:
pass
elif re.isallnum() is False and re.lower().startswith('q') is False:
print('invalid response.')
else:
pass
adding_report(report=[])
If anyone found any way to fix the bugs, could they please tell me. Thanks in advance.
you must put tabulation to code at least here
def adding_report(report=[]): # <-- You have errors here, defined function has nothing in it
report = [] # <-- I suggest tabulating this
this is incorrect usage, and it works
if re.isdigit() is True: # Not recommended
whenever you check if something is True, just Do not do it,
this is better way for simple if statement:
if re.isdigit(): # Recommended, will excecute when it returns any value, except (False and None)
move break after code, if you want it to excecute:
break # <-- this stops loop! you won't print anything that is after it
print(report)
print(sum(report))
I guess you are trying to do something like this maybe? I've changed a bit your code and made some comments where the errors where present.
def adding_report(report=[]):
report = []
at = input("Choose a report type: 'A' or 'T' : ")
while at.lower() != 'a' and at.lower() != 't':
print('what?')
at = input("Choose a report type: 'A' or 'T' : ")
while True:
re = input("print an integer or 'Q' : ")
print(re)
if re.isdigit(): # Remove is true
report.append(int(re)) # Add integer to list. Use int() to convert string to int
elif re.startswith('q'): # Remove is true
if at.lower() == 'a':
print(report) # This two prints MUST be above de break statement in ordered to be executed
print(sum(report))
break
elif at.lower() == 't': # Remove is true
print(sum(report))
break
else:
pass
elif not re.isdigit() and not re.lower().startswith('q'): # Replaced is False with not
print('invalid response.')
else:
pass
adding_report(report=[])

"while loop" not breaking (using Python)

This is my code :
#Choose Report
def chooseReport():
print "Choose a report."
while True:
choice = raw_input("Enter A or B: ")
if choice == 'a' or choice == 'A':
reportA()
break
elif choice == 'b' or choice == 'B':
reportB()
break
else:
continue
When I input either a or b, it just asks me to "Enter A or B" again. It doesn't go to the functions its supposed to.
Any idea why is this?
The code is perfect, except a redundant else, as mentioned in the comment. Are you entering a (a + space) rather than simply a (a without space) ? The problem is in the input that you are providing and not in the code!
def chooseReport():
print "Choose a report."
t=True # t starts at true
while t:
choice = raw_input("Enter A or B: ")
if choice == 'a' or choice == 'A':
reportA()
t=False # t turns false to break out of loop
elif choice == 'b' or choice == 'B':
reportB()
t=False
Try this. It keeps looping when t is true and stops when t is false. The problem might also be in reportA or reportB or how you are calling chooseReport.
The problem is in the raw_input(). It returns a string but maybe this string is "a " or "a\n" though you have entered "a" or "b".
I would do this:
def chooseReport():
print "Choose a report."
while True:
choice = raw_input("Enter A or B: ")
if "a" in choice or "A" in choice:
reportA()
break
elif "b" in choice or "B" in choice:
reportB()
break
else:
continue
Tried your code in the following script, it works fine both on Linux and on Windows.
def reportA():
print "AAAAA"
def reportB():
print "BBBBB"
#Choose Report
def chooseReport():
print "Choose a report."
while True:
choice = raw_input("Enter A or B: ")
if choice == 'a' or choice == 'A':
reportA()
break
elif choice == 'b' or choice == 'B':
reportB()
break
else:
continue
chooseReport();
First, your code works fine, the most probably error is that you are writing a wrong input (e.g: with more characters). To solve that you could use "a" in choice or "A" in choice. But if it isn't working... keep reading.
It's seems that break isn't affecting the while loop, I don't have python 2 so I am not very sure why (in python 3 [after change raw_input to input and print to print()] your code works perfect). So you should use the condition of the while to break it.
while True work theorically for ever because each time the code is executed it checks the condition -True- and because it's true it keeps looping.
You could manipulate that condition in order to break the loop (don't allow execute again its code).
For example you could use this:
#Choose Report
def chooseReport():
print "Choose a report."
allow = True # allow start as True so the while will work
while allow:
choice = raw_input("Enter A or B: ")
if choice.lower().strip() == "a": # This is better. .lower() make "A" > "a", and .strip() delete " a " to "a", and "a/n" to "a".
reportA()
allow = False # allow now is False, the while won't execute again
elif choice.lower().strip() == "b":
reportB()
allow = False # allow now is False, the while won't execute again
# The else is complete redundant, you don't need it
Code is fine. I think you call your chooseReport() function in a loop or your input has extra characters and if conditions didn't satisfied.

Python: Recursion, I keep getting the wrong value, what I can do?

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"

Python loop restarting even though there is a try: except:

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

How to go back to first if statement if no choices are valid

How can I have Python move to the top of an if statement if no condition is satisfied correctly.
I have a basic if/else statement like this:
print "pick a number, 1 or 2"
a = int(raw_input("> ")
if a == 1:
print "this"
if a == 2:
print "that"
else:
print "you have made an invalid choice, try again."
What I want is to prompt the user to make another choice for this if statement without them having to restart the entire program, but am very new to Python and am having trouble finding the answer online anywhere.
A fairly common way to do this is to use a while True loop that will run indefinitely, with break statements to exit the loop when the input is valid:
print "pick a number, 1 or 2"
while True:
a = int(raw_input("> ")
if a == 1:
print "this"
break
if a == 2:
print "that"
break
print "you have made an invalid choice, try again."
There is also a nice way here to restrict the number of retries, for example:
print "pick a number, 1 or 2"
for retry in range(5):
a = int(raw_input("> ")
if a == 1:
print "this"
break
if a == 2:
print "that"
break
print "you have made an invalid choice, try again."
else:
print "you keep making invalid choices, exiting."
sys.exit(1)
You can use a recursive function
def chk_number(retry)
if retry==1
print "you have made an invalid choice, try again."
a=int(raw_input("> "))
if a == 1:
return "this"
if a == 2:
return "that"
else:
return chk_number(1)
print "Pick a number, 1 or 2"
print chk_number(0)
Use a while loop.
print "pick a number, 1 or 2"
a = None
while a not in (1, 2):
a = int(raw_input("> "))
if a == 1:
print "this"
if a == 2:
print "that"
else:
print "you have made an invalid choice, try again."

Categories