Python Forum

Full Version: why is this variable not printing out properly?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Using python3 and am new - learning via introtopython.org and I'm having a problem.

var1 = (2+2)

print('The result of all calculations is ' + var1 + ' and we are done.')
Which returns the error of
Quote:Traceback (most recent call last):
  File "test.py", line 3, in <module>
    print('The result of all calculations is ' + var1 + ' and we are done.')
TypeError: Can't convert 'int' object to str implicitly

What am I doing wrong? When I change the variable to a string the line executes properly.
(Dec-27-2016, 07:00 AM)dursland Wrote: [ -> ]When I change the variable to a string the line executes properly.
That is exactly it.  You can't concatenate a string and int.

The recommended way would be to use format.  String concatenation in general is not a great technique (though often the first thing taught >.>)

var1 = 2 + 2
 
print('The result of all calculations is {} and we are done.'.format(var1))
Hello!
Using '+' for a string concatenation works but for strings. You are trying to concatenate a string with an integer without to convert the number into string - str(num).

@Mekire has showed you the proper way
Thanks. Good to know, I'm following the lessons in order on introtopython.
Now that 3.6 is out,also f-string.
>>> var1 = 2 + 2
>>> print(f'The result of all calculations is {var1} and we are done.')
The result of all calculations is 4 and we are done.
(Dec-27-2016, 09:43 AM)snippsat Wrote: [ -> ]Now that 3.6 is out,also f-string.
Wow. That is a pretty neat addition.
here is one more method.

>>> var1 = 2 + 2
>>> print "the result of all calculations is %s and we are done." % var1
the result of all calculations is 4 and we are done.
you can also print floats to a specific decimal place. 
>>> PI = 3.14159265389793
>>> print "Pi to the 2nd decimal place is %.02f" %PI
Pi to the 2nd decimal place is 3.14
>>> print "Pi to the 3rd decimal place is \"%.03f\" and pi to the 4th decimal place is \"%.04f\"." %(PI, PI)
Pi to the 3rd decimal place is "3.141" and pi to the 4th decimal place is "3.1415".
The % method of string formatting should really be considered deprecated (despite Zed's irrelevant opinion).
Everything that can be done with it can be done much more cleanly with format.
Use
print('The result of all calculations is ' + str(var1) + ' and we are done.')
(Dec-27-2016, 07:16 AM)Mekire Wrote: [ -> ]The recommended way would be to use format.  String concatenation in general is not a great technique (though often the first thing taught >.>)

var1 = 2 + 2
 
print('The result of all calculations is {} and we are done.'.format(var1))

Could you please explain why that is?
To me, a simple typecast to string seems cleaner.
Pages: 1 2