Re: Getting error on my code
Leam Hall via Tutor <[email protected]> Fri, 31 Jan 2025 06:31:55 -0600
| Newsgroups | gmane.comp.python.tutor |
|---|---|
| Message-ID | <[email protected]> |
On 1/31/25 06:10, Alan Gauld via Tutor wrote:
> On 31/01/2025 10:46, Leam Hall via Tutor wrote:
>
>>> def_init_(self , name , age):
>>> self.name = name
>>> self.age = age
>>> print(self.name.title() + self.age)
>
>> 2. Made the age a string in the __init__ print method.
>
> As a matter of interest, why?
> print() converts its arguments to strings internally
> so why the explicit conversion?
I thought it would as well, but got a TypeError without the str() cast:
[leam@shaphan toys]$ ./dappy.py
Traceback (most recent call last):
File "/home/leam/lang/python/toys/./dappy.py", line 15, in <module>
my_dog = Dog('willie' , 6)
^^^^^^^^^^^^^^^^^
File "/home/leam/lang/python/toys/./dappy.py", line 13, in __init__
print(self.name.title() + " " + self.age)
~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~
TypeError: can only concatenate str (not "int") to str
[leam@shaphan toys]$ python -V
Python 3.12.1+
Leam
Linux Software Engineer (reuel.net/career)
Scribe: The Domici War (domiciwar.net)
Coding Ne'er-do-well (github.com/LeamHall)
Between "can" and "can't" is a gap of "I don't know", a place of discovery. For the passionate, much of "can't" falls into "yet". -- lh
Practice allows options and foresight. -- lh
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor