filmov
tv
Learn Python Programming Tutorial 2: Concatenation and Addition of Variables

Показать описание
In Python you can use the + (plus) operator either for concatenation or addition.
Which one, depends on the type of variables you are dealing with
Possibilities:
Two text variables = Concatenation
Two numeric variable = Addition
Mixed Text and numeric. You have to convert one of them to the type of the other depending what action you wish the plus sign to implement.
So with the str() function you convert numeric variables to text and thus + will concatenate those variables.
Converting all variables to integers with the int() function ensures that + will add both variables.
Below is the code used in the video:
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
--- a = 17
--- b = 29
--- c = 'Hello'
--- d = 'everybody'
--- a+b
46
--- c+d
'Helloeverybody'
--- c+" "+d
'Hello everybody'
--- a+c
TypeError: unsupported operand type(s) for +: 'int' and 'str'
--- str(a)
'17'
--- str(a)+c
'17Hello'
--- e = str(a)
--- e+c
'17Hello'
--- f='126'
--- f+c
'126Hello'
--- f+d
'126everybody'
--- f+a
TypeError: Can't convert 'int' object to str implicitly
--- int(f)
126
--- a+int(f)
143
--- g=int(f)
--- a+g
143
---
=============================== RESTART: Shell ===============================
---
Which one, depends on the type of variables you are dealing with
Possibilities:
Two text variables = Concatenation
Two numeric variable = Addition
Mixed Text and numeric. You have to convert one of them to the type of the other depending what action you wish the plus sign to implement.
So with the str() function you convert numeric variables to text and thus + will concatenate those variables.
Converting all variables to integers with the int() function ensures that + will add both variables.
Below is the code used in the video:
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
--- a = 17
--- b = 29
--- c = 'Hello'
--- d = 'everybody'
--- a+b
46
--- c+d
'Helloeverybody'
--- c+" "+d
'Hello everybody'
--- a+c
TypeError: unsupported operand type(s) for +: 'int' and 'str'
--- str(a)
'17'
--- str(a)+c
'17Hello'
--- e = str(a)
--- e+c
'17Hello'
--- f='126'
--- f+c
'126Hello'
--- f+d
'126everybody'
--- f+a
TypeError: Can't convert 'int' object to str implicitly
--- int(f)
126
--- a+int(f)
143
--- g=int(f)
--- a+g
143
---
=============================== RESTART: Shell ===============================
---
Комментарии