Currency converting issue I am facing now - python

I was trying to print the output under the 2nd for loop (enter the amount Of $20: ...), but I am getting 0. How to fix this issue? The user gets amount of $20 : 1, and amount of $2.00: 2, when they input 22 from keyboard.
Code:
denomitions={"$20.00":0,
"$10.00":0,
"$5.00":0,
"$2.00":0,
"$1.00":0,
"$0.25":0,
"0.10":0,
"0.5":0}
dividers = [2000,1000,500,200,100,25,10,5]
number = float(input("please enter the amount for change:").strip("$"))
#convert dollar to cents
change = int(number*100)
for i in range(len(denomitions)):
amount = int(change/dividers[i])
change= change- amount * dividers[i]
#print the result out
index= float(dividers[i] / 100.00)
print(index,":",amount)
#print the result out
for k in denomitions:
print("amount of "+str(k),amount)

denomitions={"$20.00":0,
"$10.00":0,
"$5.00":0,
"$2.00":0,
"$1.00":0,
"$0.25":0,
"0.10":0,
"0.5":0}
dividers = [2000,1000,500,200,100,25,10,5]
#add an empty list
amount_list = []
number = float(input("please enter the amount for change:").strip("$"))
#convert dollar to cents
change = int(number*100)
for i in range(len(denomitions)):
amount = int(change/dividers[i])
change= change- amount * dividers[i]
#print the result out
index= float(dividers[i] / 100.00)
print(index,":",amount)
#fill the list with the amount at index i
amount_list.append(amount)
#print the result out
i = 0
for k in denomitions:
#now you can retrieve the amount from the list if you keep the same index
print("amount of "+str(k), str(amount_list[i]))
i += 1

The problem is that in the second for loop, it picks up the amount equal to the last round of the previous for loop. At the end of the first loop amount = 0, therefore you will always get zero when printing amount in the second for loop.

Related

How do you Multiply numbers in a loop in Python from a list of user inputs

I need to create something that can multiply values no matter how many values there are. My idea is to use a list and then get the sum of the list with the sum function or get the first value of the list and set it as the total and then multiply the rest of the list by that total. Does anyone have a way to do it?
Here was my original idea:
total = 0
while True:
number = float(input("Enter a number and I’ll keep multiplying until you enter the number 1: "))
if number == 1:
break
else:
total *= number
print(f"The total is: {total}")
however as you may have guessed it just automatically multiplies it to 0 which equals zero. I would also like the code to work for subtraction and division (Already got Addition working)
thanks!
Thanks to the comments I worked out that the way to do it is by changing the beginning total to a 1 when fixed it is this:
total = 1
while True:
number = float(input("Enter a number and I’ll keep multiplying until you enter the number 1: "))
if number == 1:
break
else:
total *= number
print(f"The total is: {total}")
Since you are multiplying, you must start with 1 cause anything multiplied by 0 is 0. And idk why you need sum()
total = 1
while True:
number = float(input("Enter a number and I’ll keep multiplying until you enter the number 1: "))
if number == 1:
print(f"The total is: {total}")
break
else:
total *= number

Python number processing trouble

I want to write a program that asks a user how many numbers they wish to process, then ask for that many numbers. Then it will find the total and the maximum of the numbers processed. Example output:
Enter the number of values to process: 5
First value: 3
Next value: 9.2
Next value: -2.5
Next value: 0.25
Next value: 6
The total is 15.95
The maximum is 9.20
One thing I am lost on is that if if I have the code for num in (1, 3)
and num gets assigned multiple values, how do I extract both those values?
Set example_list = list(), then do a for loop where each time you ask for input and add the value to the list via example_list.append(input_response).
Extract the values back out using the same for loop to cycle through the list.
example_list = list()
total = 0
max_value = 0
for stored_number in example_list:
# Ask for input and store in input_response variable
example_list.append(input_response)
# Here is where you could add the values to a counter variable,
# as well as check whether they are the maximum
total += stored_number
if stored_number > max:
max_value = stored_number
# Display results
For what you want, you could also just use the built-in functions max and sum:
max_value = max(example_list)
total = sum(example_list)
# ask how many
quantity = int(raw_input("Enter the number of values to process: "))
# ask for numbers and store them in list
numbers = [float(raw_input("Enter number " + str(each) + " : ")) for each in range(0,quantity)]
#print result
print "The total is " + str(sum(numbers)) + " and the maximum is " + str(max(numbers))

Python CD annual precentage

I am doing this assignment. when i input the number of months it is one printing one month. rather it be 5 months or 17 months its only printing 1 months total.
https://drive.google.com/file/d/0B_K2RFTege5uZ2M5cWFuaGVvMzA/view?usp=sharing
Here is what i have so far what am i over looking thank you
calc = input('Enter y or n to calculate your CDs worth?')
month= int(input('Select your number of months'))
while calc == 'y':
while month > 0:
amount = int(input('Please enter the amount:'))
percent= float(input('Please enter the annual percentage:'))
calc= amount + amount* percent/ 1200
print(calc)
You would want to use a for loop rather than while in this sense since you are doing a set amount of operations. You also were reusing calc and assigning calc to from a String to a float, generally a bad idea. The main problem is the formula builds upon the previously calculated number, it starts off with the initial amount entered, 10000 + 10000 * 5.75 / 1200 = 10047.91, then uses 10047.91 in the next calculation, instead of 10000, you never were reusing the previously calculated number, so you weren't getting the right answer. This should do it:
calc = input('Enter y or n to calculate your CDs worth?')
if calc == 'y':
month = int(input('Select your number of months'))
amount = int(input('Please enter the amount:'))
percent = float(input('Please enter the annual percentage:'))
for i in range(month):
if i == 0:
calcAmount = amount + ((amount * percent) / 1200)
else:
calcAmount = calcAmount + ((calcAmount * percent) / 1200)
print calcAmount

How to get this to stop at 20

I would like for this to stop at 20. By which I mean, when it asks you to input another number it should stop after the 20th time.
Currently I have an accumulating counter that when it reaches 20 it prints the "Enter one more number". It does this at the 20th time, but afterwards it keeps going with asking you to input more numbers. I would like it to stop asking for input after the 20th time.
Thanks. This is apart of a larger homework problem.
def main ():
print()
print("Finds the lowest, highest, average, and total to 20 numbers.")
print()
number, count, numberlist = getnumber()
print("Stop.")
def getnumber ():
count = 0
numberlist = []
for count in range(20):
count = count + 1
number = float(input("Please enter another number : "))
numberlist.append(number)
while count != 20:
number = float(input("Please enter one more number : "))
numberlist.append(number)
return number, count
main()
You could do this as follows:
def get_numbers(count=20):
numbers = []
numbers.append(float(input("Please enter a number : "))) # first
for _ in range(count-2):
numbers.append(float(input("Please enter another number : "))) # next 18
numbers.append(float(input("Please enter one more number : "))) # last
return numbers
Note that with a for loop you don't need to manually increment the loop counter. Also, there is no need to return count; you already know how many there will be.
First of all, note that you are not changing value of count inside while loop - that is why it never stops. After for is executed count is exactly 19 and never reaches 20 after that.
Second of all, you do not need while at all - for loop will work for 20 iterations and stop
def getnumber ():
count = 0
numberlist = []
for count in range(20):
count = count + 1
number = float(input("Please enter another number : "))
numberlist.append(number)
return number, count, numberlist
Here is another option (your approach extended)
limit = 5
def main ():
print("Finds the lowest, highest, average, and total to {} numbers.".format(limit))
numbs = getnumber()
print(numbs)
print("lowest:", min(numbs))
print("highest:", max(numbs))
print("avg:", sum(numbs)/len(numbs))
print("total:", sum(numbs))
print("Stop.")
def getnumber ():
numberlist = []
for count in range(limit):
if count == limit-1:
number = float(input("Please enter one more number : "))
numberlist.append(number)
else:
number = float(input("Please enter another number : "))
numberlist.append(number)
return numberlist
main()
Output
Finds the lowest, highest, average, and total to 5 numbers.
[6.0, 3.0, 8.0, 4.0, 2.0]
('lowest:', 2.0)
('highest:', 8.0)
('avg:', 4.6)
('total:', 23.0)
Stop.
There are some problems with the code you posted. First of you should indent the return statement so it is part of getnumber. Secondly you return two values but unpack three values in main. If I fix those two things the code works. The reason that count is 20 after the for loop is that you declare count outside the loop, so on each iteration count will be set to the next integer and then incremented once more by
count = count + 1
If you did not have the extra increment inside the loop, count would be 19 after the for loop terminates because range(N) does not include N.
And you can rewrite the code with a list comprehension to get a very concise version
def getnumber(prompt, n):
return [float(input(prompt)) for _ in range(n)]
This will give you a list of the numbers.

Python - get while loop to run a certain amount of times

I am trying to get a while loop to function dur amount of times, however when I run it it just sits there, I assume calculating, seemingly forever. It is a simple script that shouldn't take very long to run, so I assume I have messed up the while loop.
Here is the code:
#Compound interest calculator
print "Enter amounts without $, years or %"
loan = input("How many dollars is your loan? ")
dur = input("How many years is your loan for? ")
per = input("What percent is the interest on your loan? ")
percent = per / 100
count = 0
#First calculation of amount
first = loan * percent
count = count + 1
#Continued calculation occurs until count is equal to the duration set by the user
while count <= dur:
out = first * percent
#Prints output
output = out + loan
print str(output)
There are a number of problems with your code.
percent will always be 0, because you are using integer division. Try percent = per / 100.0 instead.
As others have noted, you have to increase count to end the loop.
Without changing either first nor percent in the loop, the calculated value of out will be the same in each iteration of the loop. Try first = first * percent instead.
Finally, you do not need the loop at all. Just do this:
output = loan * (1 + per/100.)**dur
You need to increment count in the while loop, otherwise the stop condition (count <= dur) will never happen.
while count <= dur:
# do something
count += 1
If you know in advance the number of times you want to do something you could also use:
for i in xrange(dur): # use range if python3
# do something
Also note that your code has another problem: you're not really calculating compund interest. At every step you recalculate first * percent instead of adding percent to the previous interest. You should do:
# First calculation of amount
out = loan * percent
count = count + 1
while count <= dur:
out *= (1.0 + percent)
count += 1
count never changes within the loop. Do this
while count <= dur:
out = first * percent
count += 1

Categories