Python Forum
While Loop; Can Else Point Back To Initial Input Command?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
While Loop; Can Else Point Back To Initial Input Command?
#1
Guys and gals, I have lost my ever-loving mind. I was given a homework assignment (Intro to Python) and I have mostly figured this out, but I cannot get one thing right: When cents < 0, point back to require the input again (for now I have it break, but even that is broken). This is driving me crazy, there is something simple I am missing, I know it and I need a little nudge to get me to see it.

The assignment states I have to calculate a user defined value from 0-99 and kick back how many quarters, dimes, nickels and pennies are required to make that value (using highest value coins first, so if a single coin can hold a value/remainder, it must before a lower coin can fill any remaining void).

My issue is that even though I did just that, the teacher has kicked it back and states I need to have the input put back in when the value of cents < 0. I took a pseudo-code course last semester, but then was off all Summer, so I have forgotten a lot of the logic.

Python is hard, but I a pushing forward and am not asking anyone to do the work for me. I cannot figure out my logic here, I am missing something. I have made this far and dagburnit after two nights on this I have to move on and accept I don't see it. Please, someone, give me a hint, where have I failed logically to loop this back so I can learn from this horrible, horrible second program (our first program was Hello World!, and now this; yes, this is Week 2 homework). I bet it is easy... I just don't see it. My code is below, and real talk, thank all of you for what you do. I doubt many people aren't grateful, but trust me when I say that I am. Reading these forums has taught me so much and I hate I have to bother you for this little problem, but I must move on and learn from this; I can't hold up any longer, it is due in four days and I have given it my all. R.I.P. My Logic.

Cheers,

~Rod

# program to get user-defined input (0-99)
# program will calculate number of coins required to make exact change using highest value coins first

# get user input
# use int; float will not round decimals accurately for req'd math
cents = int(input("Enter change: Amount of change must be between 0 and 99.\n"))

# set each coin [quarter, dime, nickel, penny] to 0
quarter = 0
dime = 0
nickel = 0
penny = 0

# while loop to test if each addition will equal/overlap user-defined cents
while cents >= 0:
    if cents >= 25:
        quarter += 1
        cents -= 25
    elif cents >= 10:
        dime += 1
        cents -= 10
    elif cents >= 5:
        nickel += 1
        cents -= 5
    elif cents >= 1:
        penny += 1
        cents -= 1
    else:
        print("Amount of change must be between 0 and 99.\n")
        break

# set list
# guessing here: >>> list0 = [quarter, dime, nickel, penny]

# output message displaying appropriate coins to equal user-defined cents
print("Quarters:", quarter)
print("Dimes:", dime)
print("Nickels:", nickel)
print("Pennies:", penny)
Reply
#2
Have a while True: loop for the input. If the input is invalid, give a message and let it loop again. Otherwise, break.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
There is the % operation (modulo operator) in python, do you have the right to use it?
Using the / operator on integers to get how much times you have the second number fitting in the first, and then having the modulo to know how much money you can try with the next one is a more elegant way to do this, I let you figure out how.
>>> 103%25
3
>>> 5 / 2
2
Alternatively, you can do this with while loops, but make sure you have finished to fit in all the quartets before you get to the next one. It can be cleaner to have a separate loop for each, or make use of a for loop to get the right amount of iterations without having to bother with "while true" stuff

>>> a = [25, 10, 5, 1]
>>> for value in a:
...     print value
... 
25
10
5
1
>>> 
Reply
#4
Sorry everyone for the delay, I am only now returning to this assignment. Thank you all for your input. I will see what I can do.

[quote='Krookroo' pid='25313' dateline='1505520346']
There is the % operation (modulo operator) in python, do you have the right to use it?
Using the / operator on integers to get how much times you have the second number fitting in the first, and then having the modulo to know how much money you can try with the next one is a more elegant way to do this, I let you figure out how.
>>> 103%25
3
>>> 5 / 2
2
Very interesting. I will look into this indeed.
Reply
#5
@Krookroo You are awesome. I found an example in the book on the last chapter we covered that touched on the integer division opeartor (//) and a whole whopping two sentences on the Modulos Operator (%). So I said, yeah, I can use this. What does it do, the book has this inches to feet example, but nothing on the (%), so let me look into it on Python.org.

I had no idea I could touch into this logic. I rewrote that entire code above, into this:
cents = int(input("Enter an amount of change must be between 0 and 99.\n"))

quarter = cents // 25
cents = cents%25

dime = cents // 10
cents = cents%10

nickel = cents // 5
cents = cents%5

penny = cents // 1
cents = cents%1

print("Quarters:", quarter)
print("Dimes:", dime)
print("Nickels:", nickel)
print("Pennies:", penny)
And just like that, it was running. Not only that, I no longer have to loop back to the original input, so we will likely touch on that at a later date. With that said, I am still going to work on that loop for this program. I will follow-up when I get the time.

*Edit*
I couldn't stop thinking about this, and with the process so small and simple, I knew the else statement would take care of it (I didn't loop back, but it will break when cents < 0 or > 99).
Y'all have no idea how grateful I am. Good looking out for us new to Pythonic bliss!

Here is my code with the while-else (a whole 19 lines):
cents = int(input("Enter an amount of change must be between 0 and 99.\n"))

while cents < 0 or cents > 99:
    print(cents, "must be between 0 and 99.")
    break

else:
    quarter = cents // 25
    cents = cents%25
    dime = cents // 10
    cents = cents%10
    nickel = cents // 5
    cents = cents%5
    penny = cents // 1
    cents = cents%1
    print("Quarters:", quarter)
    print("Dimes:", dime)
    print("Nickels:", nickel)
    print("Pennies:", penny)
*End Edit*

It just blows my mind I was able to rewrite all of that into such few lines of code. Holy moly...

Thanks to all of you for your input. It was truly helpful and again, thank all of you for what you do.

Enjoy your weekend!

i am root,

~Rod
Reply
#6
Nice :)
Just add a little bit, here's how I would have done it. The idea is to store the data we use in lists so that we can very easily tweak the algorithm for another set of currencies, just by editing the lists containing the currencies and their values. The logic behind is the same as yours, expressed in a more general way.
There might be a cleaner / more efficient way to do this with dictionaries, but I never used dictionaries before (and won't for a while).

currency_values = [25, 10, 5, 1]
currency_names = ['quartet', 'dime', 'nickel', 'cent']

cents_to_convert = int(input('Hey little boy how much cents do you want me to convert?\n'))

final_answer = "I'll give you "
for name, currency in enumerate(currency_values):
    if cents_to_convert<=0: #if we have converted all the cents, just end and give the result.
        break
    if cents_to_convert>=currency: #if less, we don't need to print that we give this guy 0 of this coin.
        current_currency_number = cents_to_convert/currency
        final_answer += ' {0} {1} '.format(str(current_currency_number), currency_names[name])
        cents_to_convert = cents_to_convert % currency
print final_answer
Reply
#7
(Sep-17-2017, 06:33 PM)Krookroo Wrote: Nice :)
Just add a little bit, here's how I would have done it. The idea is to store the data we use in lists so that we can very easily tweak the algorithm for another set of currencies, just by editing the lists containing the currencies and their values. The logic behind is the same as yours, expressed in a more general way.
There might be a cleaner / more efficient way to do this with dictionaries, but I never used dictionaries before (and won't for a while).

currency_values = [25, 10, 5, 1]
currency_names = ['quartet', 'dime', 'nickel', 'cent']

cents_to_convert = int(input('Hey little boy how much cents do you want me to convert?\n'))

final_answer = "I'll give you "
for name, currency in enumerate(currency_values):
    if cents_to_convert<=0: #if we have converted all the cents, just end and give the result.
        break
    if cents_to_convert>=currency: #if less, we don't need to print that we give this guy 0 of this coin.
        current_currency_number = cents_to_convert/currency
        final_answer += ' {0} {1} '.format(str(current_currency_number), currency_names[name])
        cents_to_convert = cents_to_convert % currency
print final_answer

I love the structure and organization. Thank you! I have been using many list ideas in my pseudocode of late that I couldn't turn in, but this will help me put those ideas into action when I get around to it when I am messing around on my own and not having to stick to the MyProgrammingLab rubric.
Reply
#8
I find it a little easier to use zip on the two lists in the for loop to avoid indexing the lists.

(Also, changed / to // as OP appears to be using Python 3, and simplified the answer string generation)

currency_values = [25, 10, 5, 1]
currency_names = ['quarter', 'dime', 'nickel', 'cent']
 
cents_to_convert = int(input('Hey little boy how much cents do you want me to convert?\n'))
 
final_answer = "I'll give you "
for name, currency in zip(currency_names, currency_values):
    if cents_to_convert<=0: #if we have converted all the cents, just end and give the result.
        break
    if cents_to_convert>=currency: #if less, we don't need to print that we give this guy 0 of this coin.
        current_currency_number = cents_to_convert//currency
        final_answer +=  f' {current_currency_number} {name} '
        cents_to_convert = cents_to_convert % currency
print(final_answer)

Couldn't resist (I'm bored) tweaking, and demonstrating the point @Krookroo made about how easy it is to change currency when using two lists:

#!/usr/bin/env python3
# simple programme to calculate largest denominations of change to give

# denominations lists, values and names one-to-one mapping!
# sterling
currency_values = [200, 100, 50, 20, 10, 5, 2, 1]
currency_names = ['two pound', 'pound', 'fifty pence', 
                    'twenty pence', 'ten pence', 
                    'five pence', 'two pence', 'one pence']

def breakdown(amountstr):
  if not amountstr:
    return ""
  change = ""
  amount = int(amountstr)
  for name, currency in zip(currency_names, currency_values):
      if amount <= 0: # end if no change left
          break
      if amount >= currency: # we have some of this denomination to pay
          quantity = amount // currency
          change +=  f'\n{quantity}x \t{name} '
          amount = amount % currency
  return change
 
while True:
  change = breakdown(input('\nHow much needs to be returned in change (return to exit)? '))
  if change:
    print(f'Change breakdown is: {change}')
  else:
    break
Also available on repl.it.
I am trying to help you, really, even if it doesn't always seem that way
Reply
#9
Wow, the day that I can program out of boredom like that to help others... I can't wait. Thank you, it really helps me seeing different approaches to the same problem. I really do appreciate all of this.
Reply
#10
(Oct-04-2017, 03:21 AM)RodNintendeaux Wrote: Wow, the day that I can program out of boredom like that to help others... I can't wait. Thank you, it really helps me seeing different approaches to the same problem. I really do appreciate all of this.
Glad it helped. I'm pretty new to Python myself, and coming up with solutions to these little problems is good for me. (I learned to programme decades ago in languages like Fortran, Pascal, Ada, Cobol, Assembler - but went in a different direction in IT, and only started to relearn programming, focused on the modern languages, recently).

The link I posted doesn't automatically show updated versions. I did make a few more slight tweaks.
I am trying to help you, really, even if it doesn't always seem that way
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Adding string numbers, while loop and exit without input. Jose 11 7,371 Apr-15-2020, 08:34 AM
Last Post: Jose
  Question about running comparisons through loop from input value Sunioj 2 2,362 Oct-15-2019, 03:15 PM
Last Post: jefsummers
  Help with loop & user input rdDrp 11 11,352 Dec-23-2016, 06:10 AM
Last Post: rdDrp
  loop in system command fails roadrage 1 3,596 Dec-01-2016, 11:21 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020