I'm having trouble with an or condition in a function. The if statement keeps evaluating as True no matter what value choice is. When I remove the or, the if works correctly.
def chooseDim ():
**choice = input ('Do you need to find radius or area? ')
if choice == 'A' or 'a':**
area = 0
area = int(area)
areaSol ()
elif choice == 'R' or 'r':
radSol ()
else:
print ('Please enter either A/a or R/r.')
chooseDim ()
'a' evaluates to True, so you need to construct your if statement correctly.
def chooseDim ( ):
**choice = input ('Do you need to find radius or area? ')
if choice == 'A' or choice == 'a':**
area = 0
area = int(area)
areaSol ( )
elif choice == 'R' or choice == 'r':
radSol ( )
else:
print ('Please enter either A/a or R/r.')
chooseDim ( )
The answers about or itself are correct. You're literally asking if "a" is True, which it always is. But there's an alternative approach:
if choice in 'Aa':
Then again, there's nothing wrong with:
if choice.lower() == 'a':
It would be easier to just use the in operator in this case:
if choice in ['A', 'a']: ...
if choice == 'A' or choice =='a':
Related
How can I go about creating a input and output with Y\N (yes or no) function in a question?
My example; if my question is Would you like some food? (Y \ N):, how can I do this and have the answers show Yes, please. or No, thank you. for either choice and then proceed to the next question with the same function?
I thought about using this: valid=("Y": True, "y": True, "N": False, "n": False) but that only shows up as True or False for me, or is there a way to change from True \ False to Yes \ No? or this one:
def user_prompt(yes_no):
while True:
user_input=input(yes_no)
But I'm really not sure how else to proceed with this one, or if there's any other easier solution to this.
I think what you're looking for is a conditional print statement rather than a true/false return statement on the function.
For example:
def user_prompt():
while True:
user_input = input("Would you like some food? (Y \ N)")
print ("Yes, please" if user_input == 'Y' else "No, thank you")
Or, more readable:
def user_prompt():
while True:
user_input = input("Would you like some food? (Y \ N)")
if (user_input == 'Y'):
print("Yes, please")
elif (user_input == 'N'):
print("No, thank you")
I hope I understood your question correctly, you basically check the first letter (incase user enters yes/no) every time the user enters a value and try to verify that if it's Y/N you break the loop if not you keep asking the same question.
def user_prompt(yes_no):
while True:
user_input=input(yes_no)
if user_input[0].lower() == 'y':
print("Yes, please.")
break
elif user_input[0].lower() == 'n':
please("No, thank you.")
break
else:
print("Invalid, try again...")
Not sure if this is the best way, but I have a class based implementation of same
""" Class Questions """
class Questions:
_input = True
# Can add Multiple Questions
_questions = [
'Question 1', 'Question 2'
]
def ask_question(self):
counter = 0
no_of_question = len(self._questions)
while self._input:
if counter >= no_of_question:
return "You have answred all questions"
user_input = input(self._questions[counter])
self._input = True if user_input.lower() == 'y' else False
counter += 1
return "You have opted to leave"
if __name__ == '__main__':
ques = Questions()
print(ques.ask_question())
Firstly there is many ways you can go around this, but I am guessing you found the solution yourself already but here is one that is the best.
def get_yes_no_input(prompt: str) -> bool:
allowed_responses = {'y', 'yes', 'n', 'no'}
user_input = input(prompt).lower()
while user_input not in allowed_responses:
user_input = input(prompt).lower()
return user_input[0] == 'y'
continue = get_yes_no_input('Would you like to proceed? [Y/N]: ')
And there we go.
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=[])
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.
"""
This program presents a menu to the user and based upon the selection made
invokes already existing programs respectively.
"""
import sys
def get_numbers():
"""get the upper limit of numbers the user wishes to input"""
limit = int(raw_input('Enter the upper limit: '))
numbers = []
# obtain the numbers from user and add them to list
counter = 1
while counter <= limit:
numbers.append(int(raw_input('Enter number %d: ' % (counter))))
counter += 1
return numbers
def main():
continue_loop = True
while continue_loop:
# display a menu for the user to choose
print('1.Sum of numbers')
print('2.Get average of numbers')
print('X-quit')
choice = raw_input('Choose between the following options:')
# if choice made is to quit the application then do the same
if choice == 'x' or 'X':
continue_loop = False
sys.exit(0)
"""elif choice == '1':
# invoke module to perform 'sum' and display it
numbers = get_numbers()
continue_loop = False
print 'Ready to perform sum!'
elif choice == '2':
# invoke module to perform 'average' and display it
numbers = get_numbers()
continue_loop = False
print 'Ready to perform average!'"""
else:
continue_loop = False
print 'Invalid choice!'
if __name__ == '__main__':
main()
My program processes only if I enter 'x' or 'X' as input. For other inputs the program just quits. I've commented out the elif parts and ran with only if and else clauses. Now a syntax error is thrown. What am I doing wrong?
It's about the line if choice == 'x' or 'X'.
Correctly, it should be
if choice == 'x' or choice == 'X'
or simpler
if choice in ('X', 'x')
because the or operator expects boolean expressions on both sides.
The current solution is interpreted as follows:
if (choice == 'x') or ('X')
and you can clearly see that 'X' does not return a boolean value.
Another solution would be of course to check whether if the uppercase letter equals 'X' or the lowercase letter equals 'x', which might look like that:
if choice.lower() == 'x':
...
Your problem is with your if choice == 'x' or 'X': part.To fix that change it to this:
if choice.lower() == 'x':
if choice == 'x' or 'X':
is not doing what you think it's doing. What actually get's parsed is the following:
if (choice == 'x') or ('X'):
You probably want the following:
if choice == 'x' or choice == 'X':
which can be written as
if choice in ('x', 'X'):
As the interpreter says, it is an IndentationError. The if statement on line 31 is indent by 4 spaces, while the corresponding else statement is indent by 5 spaces.
I want to write an interface using a while loop and raw_input.
My code looks like this:
while True:
n = raw_input("'p' = pause, 'u' = unpause, 'p' = play 's' = stop, 'q' = quit)
if n.strip() == 'p':
mp3.pause()
if n.strip() == 'u':
mp3.unpause()
if n.strip() == 'p':
mp3.play()
if n.strip() == 's':
mp3.stop()
if n.strip() == 'q':
break
But I want it to break if I input anything that isn't specified in the raw_input.
if not raw_input:
break
Returns and IndentationError: unindent does not match any outer indentation level.
if not raw_input:
break
Does not return any error but doesn't work as I want it to. As far as I know, it does nothing at all.
Also, if there's a cleaner way to write my loop, I love to hear it.
You are getting an indent error because you do not have a closing double quote.
n = raw_input("'p' = pause, 'u' = unpause, 'p' = play 's' = stop, 'q' = quit")
If you want to have the while look break if there is any other value then put all of your conditions into elif statements, and an all includisve else at the end. Also I just put lower and strip onto the end of the raw_input statement.
while True:
n = raw_input("'p' = pause, 'u' = unpause, 'pl' = play 's' = stop, 'q' = quit").strip().lower()
if n == 'p':
mp3.pause()
elif n == 'u':
mp3.unpause()
elif n == 'pl':
mp3.play()
elif n == 's':
mp3.stop()
elif n == 'q':
break
else:
break
You could also put all of the valid answer options into a dictionary, but it looks like you should start with the simple solution to understand the flow. Also you used a p for both play and pause. You will want to use a unique value to differentiate so I added 'pl' for play.
I think you can use a dict to hold all function is a cleaner way.
func_dict = {
'pause': mp3.pause,
'unpause': mp3.unpause,
'play': mp3.play,
'stop': mp3.stop,
}
while True:
n = raw_input("'p' = pause, 'u' = unpause, 'p' = play 's' = stop, 'q' = quit")
if n.strip() in func_dict.keys():
func_dict[n]()
else:
break