0

For my university python course I have an assignment which asks:

Create a change-counting game that gets the user to enter the number of coins necessary to make exactly two dollars. Design an algorithm, express it in pseudocode, and then use it to implement a Python program that prompts the user to enter a number of 5c coins, 10c coins, 20c coins, 50c coins, $1 coins and $2 coins. If the total value of those coins entered is equal to two dollars, then the program should congratulate the user for winning the game. Otherwise the program should display a message advising that the total was NOT exactly two dollars, and showing how much the value was above or below two dollars.

I understand how to implement the program but im having trouble trying to apply a variable to the user inputs without repetition.

I would like to use a FOR loop like so:

def main():
    for coin in ['5c','10c','20c','50c','$1','$2']:
        int(input("Enter the number of " + coin + " coins you wish use: "))


#Call the main function
 main()

But how do I assign a new variable to each user input every time it loops?

4
  • 1
    Use list for this. a = [] a.append() Commented Aug 19, 2013 at 1:45
  • 1
    use a dictionary instead, as the coins are a string Commented Aug 19, 2013 at 1:48
  • And you can also present your pseudocode and ask how to map it into Python, for a better and more to-the-point question. Commented Aug 19, 2013 at 1:51
  • Also put your python minor version as the tag, or at least Python 2.x or Python 3.x. Commented Aug 19, 2013 at 1:54

2 Answers 2

1
def main():
    coins = {}
    for kind in ['5c','10c','20c','50c','$1','$2']:
        coins[kind] = int(raw_input("Enter the number of " + kind \
                                 + " coins you wish use: ").strip() or 0)
Sign up to request clarification or add additional context in comments.

Comments

0

The best would be a list or a dictionary.

inputFor= {}
for coin in ['5c','10c','20c','50c','$1','$2']:
    inputFor[coin]= int(input("Enter the number of " + coin + " coins you wish use: "))

In the previous case, a dictionary. Then you can retrieve the user answers in the following way:

... inputFor['5c'] ...
... inputFor['10c'] ...
... inputFor['20c'] ...
... inputFor['50c'] ...
... inputFor['$1'] ...
... inputFor['$2'] ...

The dots represent the context in which you want to use the answers (formulas, display, etc).

2 Comments

In python there are both arrays and map, but they mean different things. These you are using are called lists and dictionaries.
@Antti Haapala Thanks. Corrections applied.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.