246

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 when I'm printing text either side of it?

Here is my code:

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: " births "births"
Bob Uni
  • 2,601
  • 5
  • 17
  • 13
  • 4
    Be careful in 2020 (common sense, I know :D ). Print has become a function in Python3, needs to be used with brackets now: `print(something)` (Also Python2 is outdated since this year.) – PythoNic Jul 17 '20 at 17:21
  • The other version of the question seems to have been less viewed, despite getting more votes and having better quality (more comprehensive and higher voted) answers. My best guess is that this is because the other version had a poor title. I attempted to improve the title and then closed this as a duplicate; the other one looks like the best canonical to me. – Karl Knechtel Jan 02 '23 at 00:58

18 Answers18

362

Use , to separate strings and variables while printing:

print("If there was a birth every 7 seconds, there would be: ", births, "births")

, in print function separates the items by a single space:

>>> print("foo", "bar", "spam")
foo bar spam

or better use string formatting:

print("If there was a birth every 7 seconds, there would be: {} births".format(births))

String formatting is much more powerful and allows you to do some other things as well, like padding, fill, alignment, width, set precision, etc.

>>> print("{:d} {:03d} {:>20f}".format(1, 2, 1.1))
1 002             1.100000
  ^^^
  0's padded to 2

Demo:

>>> births = 4
>>> print("If there was a birth every 7 seconds, there would be: ", births, "births")
If there was a birth every 7 seconds, there would be:  4 births

# formatting
>>> print("If there was a birth every 7 seconds, there would be: {} births".format(births))
If there was a birth every 7 seconds, there would be: 4 births
Georgy
  • 12,464
  • 7
  • 65
  • 73
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
148

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
Georgy
  • 12,464
  • 7
  • 65
  • 73
Gagan Agrawal
  • 1,481
  • 1
  • 7
  • 3
  • 1
    Decision is related to your programming style: M2 is procedural programming, M3 is object-oriented programming. Keyword for M5 is [formatted string literal](https://docs.python.org/3/reference/lexical_analysis.html#f-strings). String operations like M1 and M4 should be used if needed, which is not the case here (M1 for dictionaries and tuples; M4 e.g. for ascii-art and other formatted output) – PythoNic Jul 17 '20 at 17:12
68

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

Edit:

Its 2022 and python3 has f strings now.

>>> x = 15
>>> f"there are {x} births"
'there are 15 births'
TehTris
  • 3,139
  • 1
  • 21
  • 33
29

If you want to work with python 3, it's very simple:

print("If there was a birth every 7 second, there would be %d births." % (births))
Christian Ternus
  • 8,406
  • 24
  • 39
19

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))
Sulfkain
  • 5,082
  • 1
  • 20
  • 38
ms8277
  • 191
  • 1
  • 4
18

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
PabTorre
  • 2,878
  • 21
  • 30
12

You can either use a formatstring:

print "There are %d births" % (births,)

or in this simple case:

print "There are ", births, "births"
enpenax
  • 1,476
  • 1
  • 15
  • 27
9

If you are using python 3.6 or latest, f-string is the best and easy one

print(f"{your_varaible_name}")
Mathanraj-Sharma
  • 354
  • 1
  • 3
  • 7
4

Starting from Python-3.8, you can use f-strings with variable name printing!

age = 19
vitality = 17
charisma = 16
name = "Alice"
print(f"{name=}, {age=}, {vitality=}, {charisma=}")
# name='Alice', age=19, vitality=17, charisma=16
  • Naming mistakes are almost impossible here! If you add, rename or remove a variable, your debug print will stay correct
  • The debug line is very concise
  • Don't worry about alignment. Is the 4-th argument charisma or vitality? Well, you don't care, it's correct regardless.
VasiliNovikov
  • 9,681
  • 4
  • 44
  • 62
3

On a current python version you have to use parenthesis, like so :

print ("If there was a birth every 7 seconds", X)
Sufiyan Ghori
  • 18,164
  • 14
  • 82
  • 110
Dror
  • 5,107
  • 3
  • 27
  • 45
3

You would first make a variable: for example: D = 1. Then Do This but replace the string with whatever you want:

D = 1
print("Here is a number!:",D)
2

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"
Amber
  • 507,862
  • 82
  • 626
  • 550
  • thank you for the answer Amber. Can you explain what the 'd' does after the % symbol? thanks – Bob Uni Jun 17 '13 at 18:03
  • 2
    `%d` means "format value as an integer". Similarly, `%s` would be "format value as a string", and `%f` is "format value as a floating point number". These and more are documented in the portion of the Python manual I linked to in my answer. – Amber Jun 17 '13 at 18:04
2

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) 

or

print('If there was a birth every 7 seconds, there would be: %d births' %(births))
# Will replace %d with births
1

Just use , (comma) in between.

See this code for better understanding:

# Weight converter pounds to kg

weight_lbs = input("Enter your weight in pounds: ")

weight_kg = 0.45 * int(weight_lbs)

print("You are ", weight_kg, " kg")
Manrique
  • 2,083
  • 3
  • 15
  • 38
0

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.

Debug255
  • 335
  • 3
  • 17
-1

Slightly different: Using Python 3 and print several variables in the same line:

print("~~Create new DB:",argv[5],"; with user:",argv[3],"; and Password:",argv[4]," ~~")
Qohelet
  • 1,459
  • 4
  • 24
  • 41
-1

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))
Bromount
  • 1
  • 2
-1

If you use a comma inbetween the strings and the variable, like this:

print "If there was a birth every 7 seconds, there would be: ", births, "births"