Reputation: 15
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.
}
Upvotes: 0
Views: 66
Reputation: 11075
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>>>
Upvotes: 0
Reputation: 5999
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)
Upvotes: 4
Reputation: 1
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")
Upvotes: 0