I'm trying to create a function that allows me to pass in a string into an age variable using a while loop. This is the simplified version of the code using the .format string. The following code works as expected.
num = 1
while num<7:
age = 'My age is {}'.format(num)
print(age)
num+=2
The output is as shown below:
My age is 1
My age is 3
My age is 5
However, when I attempt to capture the string 'My age is {}' in the age variable using the while loop it doesn't work. Here is the code.
num = 1
age = 'My age is {}'
while num<7:
age = age.format(num)
print(age)
num+=2
I get the following output.
My age is 1
My age is 1
My age is 1
Any idea the reason the num does not increment in the while loop in the second example? What's the solution?
You're overwriting the age
string so there's nothing left to format in the second iteration. You could use two strings - one with the template to format in to, and one with the formatted result:
num = 1
template = 'My age is {}'
while num<7:
age = template.format(num)
print(age)
num+=2
The first time through the loop, you've replaced the {}
in the string with a number. From that point forward, format
doesn't have anything to do since the string doesn't have any formatting markers in it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With