I am having an issue with the following code. When the user selects N I keep getting an error message:
budget = input("please enter the budget amount for given month\n ")
sum_ = 0
expense = 0
i = 0
print("Please enter the expenses for the given month:")
while (1):
expense1 = input("Please enter expense number " + str(i + 1) + " \n")
sum_ = sum_ + int(expense)
c = input("If you want to enter more expense press y else n \n")
if c == 'y':
i += 1
continue
else:
break
if sum_ > budget:
print("You went over budget")
else:
print("You are under budget")
Bug 1. When I run this with Python 3, I get
If you want to enter more expense press y else n
n
Traceback (most recent call last):
File "C:\Programs\python34\tem.py", line 16, in <module>
if sum_ > budget:
TypeError: unorderable types: int() > str()
You should have looked at the error message. It says that sum_ is an int and budget is a string. The obvious fix is to make budget an int with int(budget). If you really could not figure this out, you should probably look at the tutorial more. In any case, you should have posted it as Kevin suggested.
Bug 2. You initialized expense to 0. This masked the bug of calling the entered expense expense1. So you only add int(0) to the initially 0 sum_. The fix is to drop the initialization and correct the misspelling. You should also print the sum at the end to so you can check that it is correct.
Buglet 3. Having to say y/n to enter another expense is really annoying. Just stop when the user does not enter anything.
Two pieces of your code to give you a hint:
budget = input("please enter the budget amount for given month\n ")
expense1 = input("Please enter expense number " + str(i + 1) + " \n")
sum_ = sum_ + int(expense)
Notice some difference?
Also, do not use str(i + 1). "Please blah blah {0} blah\n".format(i + 1).
Related
so i'm writing a program that's supposed to take 2 inputs of data as int's for a user's debt. the variables are debt1 and debt2. it's supposed to add these two values together and then depending on the user's input, it's supposed to give out a specific response using the "if/else" loop i've created. the problem is that the program only prints out the response from the first "if" statement no matter what the input is, it always prints out "your debt is dangerously high". how do i correct this?
** Here is my code **
Name = input("Please enter your name: ")
debt1 = int(input("Please enter your first debt amount: "))
debt2 = int(input("Please enter your second debt amount: "))
totalDebt = debt1+debt2
print("Your total debt is ", totalDebt)
if (totalDebt > 900,000):
print("Your debt is dangerously high ", Name)
elif((totalDebt >= 450,000 and totalDebt < 900,000)):
print("We can help you reduce your debt.")
else:
print("Congratulations, you know how to manage debt.")
Don't use commas in numbers:
if totalDebt > 900000:
print("Your debt is dangerously high ", Name)
elif (totalDebt >= 450000 and totalDebt < 900000):
print("We can help you reduce your debt.")
else:
print("Congratulations, you know how to manage debt.")
As #rdas said, you can use _ for long numbers, in place of ,
I am using Python 3. This is for a homework project for a class, but I'm not looking for something to do the problem for me! I was just wondering if someone could help point out exactly where I've gone wrong, or what I need to look into to make my code work.
def main():
taxPayersList = []
incomesList = []
taxesList = []
taxPayersList, incomesList = inputNamesAndIncomes(taxPayersList, incomesList)
taxesList = calculateTaxes(incomesList)
displayTaxReport(taxesList, incomesList, taxPayersList)
def inputNamesAndIncomes(taxPayersList, incomesList):
print('Welcome to Xanadu Tax Computation Program')
print('')
confirmation = input('Do you have income amounts? y/n ')
index = 0
try:
while confirmation == 'y' or confirmation == 'Y':
taxPayersList[index] = input('Enter a tax payer name: ')
incomesList[index] = float(input('Enter income amount: '))
confirmation = input('Are there more income amounts? ')
index += 1
except:
print('An error occurred. Please only enter numbers for income amount.')
return taxPayersList, incomesList
def calculateTaxes(incomesList):
index = len(incomesList)
while index < len(incomesList):
if incomesList[index] >= 0 and incomesList[index] <= 50000:
taxesList[index] = incomesList[index] * .05
elif incomesList[index] >= 50000 and incomesList[index] <= 100000:
taxesList[index] = 2500 + ((incomesList[index] - 50000) * .07)
elif incomesList[index] >= 100000:
taxesList[index] = 6000 + ((incomesList[index] - 100000) * .09)
index += 1
return incomesList
def displayTaxReport(taxesList, incomesList, taxPayersList):
print('2018 TAX DUES FOR XANADU STATE')
print('')
print('Name\t\tANNUAL INCOME\tTAXDUE')
for n in incomesList:
print(taxPayersList,'\t\t',incomesList,'\t',taxesList)
main()
Right now, I can enter a name into the first input, but as soon as I hit enter it just prints out my error code and then print out the final function like below.
Welcome to Xanadu Tax Computation Program
Do you have income amounts? y/n y
Enter a taxpayer name: Susan
An error occurred. Please only enter numbers for income amount.
2018 TAX DUES FOR XANADU STATE
Name ANNUAL INCOME TAXDUE
I know this is a total mess but any help at all would be so appreciated!
There is an IndexError: list assignment index out of range for the line
taxPayersList[index] = input('Enter a tax payer name: ')
You didn't see it because you excepted all errors and didn't print them. I suggest using
name = input('Enter a tax payer name:')
taxPayersList.append(name)
etc. Note that I append it to the list. I also suggest a different strategy of handling errors.
Alternatively, you might wish to use a dictionary instead of using two lists, since you want to associate an income with a name,
name = input('Enter a tax payer name:')
income = float(input('Enter income amount:'))
incomes[name] = income
You can't just assign into a non-existant index for a list to add items to it:
>>> a = []
>>> a[0] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
Instead you should look at using the .append() method for lists.
(The reason you aren't seeing the IndexError debugging details is because your except clause prevents it from being displayed. Bare except clauses are often considered an antipattern because they mask unexpected errors like this and make it harder to tell what went wrong - they catch any exception, not just ones due to bad user input.)
I've been coding for about a month now and i just began working on functions.
This function will prompt the user to enter an integer. If the number is lower than low or higher than high, it will output an error message to the user and then prompt again. Otherwise, it will return the number that the user typed.
Here is what i have so far
getNumberInRange(x,y):
counter = 0
answer = 0
while counter < y:
answer = answer + x
counter = counter + 1
return answer
You can try this approach also..
def getNumberInRange( low,high ):
n1 = int(input("Enter a number:"))
if ((n1 < low) or (n1 > high)):
print("Please enter the number between the range "+ str(low) +" and "+ str(high))
getNumberInRange(10,100)
else :
print(n1)
return;
getNumberInRange(10,100)
def getNumberInRange(x,y):
counter = 0
answer = 0
while counter < y:
answer += x
counter += 1
return answer, counter
print(getNumberInRange(10,20))
def getNumberInRange(x,y):
while True:
a=int(input("Enter Number"))
if not x < a < y:
print("Invalid")
else:
return a
Try this.
This function will prompt the user to enter an integer. If the number
is lower than low or higher than high, it will output an error message
to the user and then prompt again.
Hope this helps :)
I'm very new to programming, just started working my way through a Python course. I've been looking through the course material and online to see if there's something I missed but can't really find anything.
My assignment is to make a chatbot that takes input and summarizes the input but also calculates the average. It should take all the input until the user writes "Done" and then terminate and print the results.
When I try to run this:
total = 0
amount = 0
average = 0
inp = input("Enter your number and press enter for each number. When you are finished write, Done:")
while inp:
inp = input("Enter your numbers and press enter for each number. When you are finished write, Done:")
amount += 1
numbers = inp
total + int(numbers)
average = total / amount
if inp == "Done":
print("the sum is {0} and the average is {1}.". format(total, average))
I get this error:
Traceback (most recent call last):
File "ex.py", line 46, in <module>
total + int(numbers)
ValueError: invalid literal for int() with base 10: 'Done'
From searching around the forums I've gathered that I need to convert str to int or something along those lines? If there are other stuff that need to be fixed, please let me know!
It seems that the problem is that when the user types "Done" then the line
int(numbers) is trying to convert "Done" into an integer which just won't work. A solution for this is to move your conditional
if inp == "Done":
print("the sum is {0} and the average is {1}.". format(total, average))
higher up, right below the "inp = " assignment. This will avoid that ValueError. Also add a break statement so it breaks out of that while loop as soon as someone types "Done"
And finally I think you are missing an = sign when adding to total variable.
I think this is what you want:
while inp:
inp = input("Enter your numbers and press enter for each number. When you are finished write, Done:")
if inp == "Done":
print("the sum is {0} and the average is {1}.". format(total, average))
break
amount += 1
numbers = inp
total += int(numbers)
average = total / amount
I'm currently working on a program in Python and I need to figure out how to convert a string value to a float value.
The program will ask the user to enter a number, and uses a loop to continue asking for more numbers. The user must enter 0 to stop the loop (at which point, the program will give the user the average of all the numbers they entered).
What I want to do is allow the user to enter the word 'stop' instead of 0 to stop the loop. I've tried making a variable for stop = 0, but this causes the program to give me the following error message:
ValueError: could not convert string to float: 'stop'
So how do I make it so that 'stop' can be something the user can enter to stop the loop? Please let me know what I can do to convert the string to float. Thank you so much for your help! :)
Here is some of my code:
count = 0
total = 0
number = float(input("Enter a number (0, or the word 'stop', to stop): "))
while (number != 0):
total += number
count += 1
print("Your average so far is: " , total / count)
number = float(input("Enter a number (0, or the word 'stop', to stop): "))
if (number == 0):
if (count == 0):
print("")
print("Total: 0")
print("Count: 0")
print("Average: 0")
print("")
print("Your average is equal to 0. Cool! ")
else:
print("")
print("Total: " , "%.0f" % total)
print("Count: " , count)
print("Average: " , total / count)
Please let me know what I should do. Thanks.
I'd check the input to see if it equals stop first and if it doesn't I'd try to convert it to float.
if input == "stop":
stop()
else:
value = float(input)
Looking at your code sample I'd do something like this:
userinput = input("Enter a number (0, or the word 'stop', to stop): ")
while (userinput != "stop"):
total += float(userinput) #This is not very faulttolerant.
...
You could tell the user to enter an illegal value - like maybe your program has no use for negative numbers.
Better, would be to test if the string you've just read from sys.stdin.readline() is "stop" before converting to float.
You don't need to convert the string to a float. From what you've said it appears that entering 0 already stops the loop, so all you need to do is edit you're currently existing condition check, replacing 0 with "stop".
Note a few things: if the input is stop it will stop the loop, if it's not a valid number, it will just inform the user that the input were invalid.
while (number != 0):
total += number
count += 1
print("Your average so far is: " , total / count)
user_input = input("Enter a number (0, or the word 'stop', to stop): ")
try:
if str(user_input) == "stop":
number = 0
break
else:
number = float(user_input)
except ValueError:
print("Oops! That was no valid number. Try again...")
PS: note that keeped your code "as is" mostly, but you should be aware to not use explicit counters in python search for enumerate...