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
If you are using python 3.6 or latest, f-string is the best and easy one
print(f"{your_varaible_name}")
You can either use a formatstring:
print "There are %d births" % (births,)
or in this simple case:
print "There are ", births, "births"
I copied and pasted your script into a .py file. I ran it as-is with Python 2.7.10 and received the same syntax error. I also tried the script in Python 3.5 and received the following output:
File "print_strings_on_same_line.py", line 16
print fiveYears
^
SyntaxError: Missing parentheses in call to 'print'
Then, I modified the last line where it prints the number of births as follows:
currentPop = 312032486
oneYear = 365
hours = 24
minutes = 60
seconds = 60
# seconds in a single day
secondsInDay = hours * minutes * seconds
# seconds in a year
secondsInYear = secondsInDay * oneYear
fiveYears = secondsInYear * 5
#Seconds in 5 years
print fiveYears
# fiveYears in seconds, divided by 7 seconds
births = fiveYears // 7
print "If there was a birth every 7 seconds, there would be: " + str(births) + " births"
The output was (Python 2.7.10):
157680000
If there was a birth every 7 seconds, there would be: 22525714 births
I hope this helps.
PYTHON 3
Better to use the format option
user_name=input("Enter your name : )
points = 10
print ("Hello, {} your point is {} : ".format(user_name,points)
or declare the input as string and use
user_name=str(input("Enter your name : ))
points = 10
print("Hello, "+user_name+" your point is " +str(points))
You can use string formatting to do this:
print "If there was a birth every 7 seconds, there would be: %d births" % births
or you can give print
multiple arguments, and it will automatically separate them by a space:
print "If there was a birth every 7 seconds, there would be:", births, "births"
Two more
The First one
>>> births = str(5)
>>> print("there are " + births + " births.")
there are 5 births.
When adding strings, they concatenate.
The Second One
Also the format
(Python 2.6 and newer) method of strings is probably the standard way:
>>> births = str(5)
>>>
>>> print("there are {} births.".format(births))
there are 5 births.
This format
method can be used with lists as well
>>> format_list = ['five', 'three']
>>> # * unpacks the list:
>>> print("there are {} births and {} deaths".format(*format_list))
there are five births and three deaths
or dictionaries
>>> format_dictionary = {'births': 'five', 'deaths': 'three'}
>>> # ** unpacks the dictionary
>>> print("there are {births} births, and {deaths} deaths".format(**format_dictionary))
there are five births, and three deaths