I am using python to work out how many children would be born in 5 years if a child was born every 7 seconds. The problem is on my last line. How do I get a variable to work
use String formatting
print("If there was a birth every 7 seconds, there would be: {} births".format(births))
# Will replace "{}" with births
if you doing a toy project use:
print('If there was a birth every 7 seconds, there would be:' births'births)
print('If there was a birth every 7 seconds, there would be: %d births' %(births))
# Will replace %d with births
Python is a very versatile language. You may print variables by different methods. I have listed below five methods. You may use them according to your convenience.
Example:
a = 1
b = 'ball'
Method 1:
print('I have %d %s' % (a, b))
Method 2:
print('I have', a, b)
Method 3:
print('I have {} {}'.format(a, b))
Method 4:
print('I have ' + str(a) + ' ' + b)
Method 5:
print(f'I have {a} {b}')
The output would be:
I have 1 ball
On a current python version you have to use parenthesis, like so :
print ("If there was a birth every 7 seconds", X)
As of python 3.6 you can use Literal String Interpolation.
births = 5.25487
>>> print(f'If there was a birth every 7 seconds, there would be: {births:.2f} births')
If there was a birth every 7 seconds, there would be: 5.25 births
You can either use the f-string or .format() methods
Using f-string
print(f'If there was a birth every 7 seconds, there would be: {births} births')
Using .format()
print("If there was a birth every 7 seconds, there would be: {births} births".format(births=births))
use string format :
birth = 5.25487
print(f'''
{birth}
''')