0

I'm creating a pennies game, which has now already been created in C++, however I am having some trouble converting it to Python. It seems I can't figure out how to convert something such as this loop into Python.

       void penniesLeftOver(int amountOfPenniesCurrent) //Displays the amount of Pennies left to the user.
       {
         cout << "Pennies Remaining: " << amountOfPenniesCurrent; //Displays the amount of Pennies remaining.
         for (int i = 0; i < amountOfPenniesCurrent; i++)
         {
         cout << " o"; //Uses "o" to represent a Penny.
         }

      cout << "\n" << endl; //Starts a new line.
      }
3
  • 1
    What do you have so far? Commented Nov 22, 2016 at 16:52
  • 6
    The natural way in Python, Pythonic, is to just create a string, print( n*"o" ). Commented Nov 22, 2016 at 16:53
  • Do you know how to use for and range yet? Commented Nov 22, 2016 at 16:53

3 Answers 3

4

In python you can multiply a string by an int, it will create a new string which is the initial string repeated n times. And you can print() multiples things at once. Which gives:

def penniesLeftOver(amountOfPenniesCurrent):
    print("Pennies Remaining:", amountOfPenniesCurrent, " o"*amountOfPenniesCurrent)
Sign up to request clarification or add additional context in comments.

3 Comments

Ahh, thank you. I'm extremely new to Python and forgot that you could multiply strings like this.
Welcome to Python world! You will see that there are multiple "shortcuts" like this one in Python that will save you a lot of time. But when coming from "limited" language such as C++ or Java, it takes some time getting used to such possibilities.
@Guillaume: The equivalent in C++ is cout << string( n, 'o' ).
0
for penny in range(amountOfPenniesCurrent):
    print(" o")

This is a for loop in Python. ("for each penny in the total number of pennies, print " o")

1 Comment

This will print amountOfPenniesCurrent new lines as well.
0

while it makes more sense to modify the string beforehand so you only make one call to print there are other ways to accomplish your task.

sys.stdout.write(string) will write the variable string to stdout (buffered) and calling sys.stdout.flush() will flush that buffer to write immediately. (you can also define the buffer size)

alternatively you can use the print function's keyword argument end='' (which normally defaults to \n) to prevent a newline from being added. in python2.7 this requires calling from __future__ import print_function

>>>for i in range(10):
...    print('o', end='')
...
oooooooooo>>>
>>>for i in range(10):
...    sys.stdout.write('o')
...    sys.stdout.flush()
>>>
oooooooooo>>>

Comments

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.