1

I am unable to place an integer inside my print statement alongside a string, and concatenate them together.

pounds = input("Please type in your weight in pounds: ")

weight = int(pounds) * 0.45

print("You " + weight)

I thought that I would be able to put these together, why am I unable to?

Joey
  • 1,436
  • 2
  • 19
  • 33

5 Answers5

3

Python doesn't let you concatenate a string with a float. You can solve this using various methods:

Cast the float to string first:

print("You " + str(weight))

Passing weight as a parameter to the print function (Python 3):

print("You", weight)

Using various Python formatting methods:

# Option 1
print("You %s" % weight)
# Option 2 (newer)
print("You {0}".format(weight))
# Option 3, format strings (newest, Python 3.6)
print(f"You {weight}")
KYDronePilot
  • 527
  • 3
  • 12
1

print("You %s" % weight) or print("You " + str(weight))

1

Since you are trying to concat a string with an integer it's going to throw an error. You need to either cast the integer back into a string, or print it without concatenating the string

You can either

a) use commas in the print function instead of string concat

print("You",weight)

b) recast into string

print("You "+str(weight))

Edit: Like some of the other answers pointed out, you can also

c) format it into the string.

print("You {}".format(weight))

Hope this helps! =)

MPiechocki
  • 46
  • 1
  • 1
    Thanks so much! What exactly goes on with the first example (with the comma)? I guess it reads the "you" as a string but what about the weight? – Christopher Apr 13 '19 at 01:26
  • 1
    `print` is a function. `"You"` and `weight` are two arguments. Try `print(1,2,3)`. or `print(1, 2, 'astring')`. Read up on `print`. It's an important function. In the bigger picture you want to learn `format` (and the older `%` style), and `str()` and `repr()` functions. – hpaulj Apr 13 '19 at 01:35
  • @Christopher Yep "you" will be read as a string, and weight will still be an integer, but by separating them with commas in your print function, it lets Python know that you are only trying to print the two variables out and not trying to combine them with concatenation. =) – MPiechocki Apr 13 '19 at 01:36
1

Another way is to use format strings like print(f"You {weight}")

scarecrow
  • 6,624
  • 5
  • 20
  • 39
0

Python is dynamically typed but it is also strongly typed. This means you can concatenate two strs with the + or you can add two numeric values, but you cannot add a str and an int.

Try this if you'd like to print both values:

print("You", weight)

Rather than concatenating the two variables into a single string, it passes them to the print function as separate parameters.

chucksmash
  • 5,777
  • 1
  • 32
  • 41