Can anyone find any bugs or mistakes in this code? - python

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=[])

Related

Python while loop isn't doing as expected

I'm trying to complete my assignment and have been struggling. The idea is that you select report type, A or T. From there you enter keep entering integers until you quit. Once you quit, it should print out the total of integers added together for report 'T'; or for report 'A', it should print the total, plus a list of integers entered.
The problem I'm encountering at the moment is from report 'T', once I'm entering integers nothing will make it error or quit. It just keeps constantly asking me to enter another integer. Then from report 'A', every integer I enter it just comes up with 'invalid input'. I'm sure there are probably plenty more issues with my code but can't get past these ones at the moment. Any pointers would really be appreciated. Thanks
def adding_report(report):
total = 0
items = []
while True:
user_number = input("Enter an ingteger to add to the total or \"Q\" to quit: ")
if report.upper == "A":
if user_number.isdigit():
total += int(user_number)
items.append(user_number)
elif user_number.upper() == "Q":
break
else:
print("Invalid input\n")
elif report.upper() == "T":
if user_number.isdigit():
total += int(user_number)
elif user_number.upper() == "Q":
break
else:
print("Invalid input\n")
report = input("Report types include All Items (\"A\") or Total Only (\"T\")\nPlease select report type \"A\" or \"T\": ")
while True:
if report.upper() in "A T":
adding_report(report)
else:
print ("Invalid input")
report = input("Please select report type \"A\" or \"T\": ")
The in operator needs a collection of possible values. Use
if report.upper() in ("A", "T")
or (closer to what you have)
if report.upper() in "A T".split()
Your first problem is in this line:
if report.upper == "A":
This always evaluates to False, because report.upper is a function object, not a value. You need
if report.upper() == "A":
to return the value. You would also do well to rename the input variable and replace its value to the internal one you want:
report = input("Report types include All Items (\"A\") or Total Only (\"T\")\nPlease select report type \"A\" or \"T\": ")
report = report.upper()
This saves you the mess and time of calling upper every time you access that letter.
Please look through your code for repeated items and typos; you'll save headaches in the long run -- I know from personal experience.
Try this
def adding_report(report):
total = 0
items = []
while True:
user_number = input("Enter an integer to add to the total or \"Q\" to quit: ")
#You used "report.upper" instead of "report.upper()"
if report.upper() == "A":
if user_number.isdigit():
total += int(user_number)
items.append(user_number)
elif user_number.upper() == "Q":
break
else:
print("Invalid input\n")
elif report.upper() == "T":
if user_number.isdigit():
total += int(user_number)
#You forgot ot add this : "items.append(user_number)"
items.append(user_number)
elif user_number.upper() == "Q":
break
else:
print("Invalid input\n")
break
#Add this for loop termination: "or 0 to quit: "
report = input("Report types include All Items (\"A\") or Total Only (\"T\")\nPlease select report type \"A\" or \"T\" Or 0 to quit: ")
while True:
#it should be this ""if report.upper() in "A" or "T":"" not this ""if report.upper() in "A T":""
if report.upper() in "A" or "T":
adding_report(report)
#The condition below terminates the program
elif report == '0':
break
else:
print("Invalid input")
report = input("Please select report type \"A\" or \"T\": ")

How can i check if an inputted variable either starts with "Q" or it is a number

I am new so plz help. i am writting a program that adds numbers. it asks for input and until "Q" is inputed it keeps asking for input
def add_num(vari = "" , total = 0):
vari = input("Enter a num or press \"Q\" to stop: ")
while (vari.startswith("Q") and int(vari).isdigit() ) == False:
print("Error")
vari = input("plz enter again: ")
else:
print("Nice")
there are no indentation error. The problem i have is how can i check if it starts with "Q" or it is a number. I think this is the code that has errors
while (vari.startswith("Q") and int(vari).isdigit() ) == False:
vari.isdigit() is enough to check that all characters are digits.
You have a logic error in the while condition: it cannot be that vari.startswith("Q") and at the same time vari.isdigit(), so that would be always false, and comparing that to False would always be true.
Change it to while (vari.startswith("Q") or vari.isdigit()) == False:

"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 condition not applying (if/elif)

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.

python if--elif-else usage and clarification

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

Categories