Codecademy Forums

How can I use an integer in a print function?

why can’t initialize an integer value to my_name?
and how can i do that if i want to.

We can assign any value to a variable, be it a number, string, boolean, list, tuple, set, dict, or the host of other objects.

my_name = 42

Legitimate, yes, but misleading. my_name implies textual data, in particular a name.

my_name = "Wee Gillis"

Note that textual data is enclosed in quotes.

1 Like

The argument (thing inside of the parentheses) of the print() function here:

my_name = "Patrick"
print("Hello and welcome " + my_name + "!")

… uses the + operator. With integers, that operator works as you expect, but with strings, it joins (“concatenates”) the strings. The problem is, that you cannot mix the two.

How to do it?
Either change the int to a string:

my_name = 7
my_name = str(my_name)
print("Hello and welcome " + my_name + "!")

… or use a more flexible method of formatting the output:

my_name = 7
print("Hello and welcome %d !" %(my_name))


my_name = 7
print("Hello and welcome {} !".format(my_name))

Output (all three):

Hello and welcome 7 !

thankyou sir i understood it .

Sorry, i just started to learn but Why can’t you just go

print("Hello and welcome " + my_name + “!”)

That’s what I tried and output was

Hello and welcome 7!

or am I missing a point here? is it not done?

You can for simple strings, but the other formatting methods have features that allow you to easily format tables, for instance, or to ensure that numbers look a certain way, with leading zeros, if that’s what you need, or a certain number of decimal places. The possibilities are nearly unlimited.

megaplayer26142 Whatever you put in my_name is going to be your result

Hi Patrickd314 for what do you use it “str” in phyton?

str() casts another type to the string type so that it can be used, for example, in string formatting.

This will raise an error:

my_list = [1,2,3]
print("This is my list: " + my_list)


Traceback (most recent call last):
  File "C:\path\to\", line 2, in <module>
    print("This is my list: " + my_list)
TypeError: can only concatenate str (not "list") to str

… but if you cast the list to string …

my_list = [1,2,3]
print("This is my list: " + str(my_list))


This is my list: [1, 2, 3]

Thanks for your details notes! very helpful!..
my question - when I replace single digit ‘7’ with say ‘77’ …I get a different print response…why is that? can you please help me understand this?

my_name = 77
print(“Hello and welcome %x !” %(my_name))

Hello and welcome 4d !

It has rendered your name in hexadecimal! That’s because you used x in the placeholder. o would have given you octal, d an integer, f a float, and s a string. Try them!

OMG; Thank you very much :+1: I understand it

1 Like

ohhh, I thought that was very hard of understad :+1:

1 Like

Thank you patrickd314!

1 Like