python if--elif-else usage and clarification - python

"""
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.

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 Selecting menu choice

I'm new to python programming and I'm having trouble selecting an option. I have created a menu for example I have :
Instructions
Catering
Packages
add
When the user selects i, c, a or p each menu will come up. However, if the user selects 'p' before 'a' then I need to set a prompt to select a first..
INSTRUCTIONS = "I"
CATERING = "C"
PACKAGES = "P"
def menu():
userInput = True
while userInput != False:
print("Instructions
Catering
Packages")
userInput = input(">>>")
if userInput == INSTRUCTIONS:
instructions()
elif userInput == CATERING:
Catering()
elif userInput == PACKAGES:
Packages()
else:
print("Error")
Thank you
Here is the Code in a Loop::
def menu():
while True:
u_in=raw_input("Input Here:: ")
u=u_in.lower()
if u_in=="":
continue
elif u=="i":
Instructions()
elif u=="c":
Catering()
elif u=="p":
Packages()
If you are using python2.x, use raw_input() instead of input().
def menu():
mybool == True
userInput = input("Instructions\nCatering\nPackages\n>>> ")
b = userInput.lower()[0]
if b == 'a':
mybool = True
elif b == 'i':
Instructions()
elif b == 'c':
Catering()
elif b == 'p':
if mybool == True:
Packages()
else:
input('Here is where we display a prompt! ')
else:
print("Error")
Basically, this sets a variable to be False, and then gets input. If the input is a, then we set myBool to be True. If the user selects p and myBool is True (a has already been selected), it carries on. Otherwise, it displays a prompt.

"or" condition causing problems with "if"

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':

How to break a loop when inputting unspecified raw_input?

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

Categories