Variable Types in Python, Rounding Numbers | Learn Python From Scratch 2 | Kovolff

preview_player
Показать описание
Python is a dynamically typed language. This is also one of the reasons its performance is slower than that of a statically typed language such as C. At runtime Python has to do some checks on the type of each variable and that costs performance.

A variable in Python points to an object but it does not contain it.
var_1 = 17
This means that var_1 points to the object 17, which in this case is an integer

var_2 = var_1
This is an extension of above and means that var_2 points to whatever var_1 is currently pointing at - the integer 17.

var_1 = ‘hello’
The first variable is now pointing to a new object - the string ‘hello’

What is var_2 pointing to? Still the 17 from previously.

var_2 = ‘var_1
Now the second variable is also pointing to the ‘hello’ string. No one is pointing to the 17 anymore and this object is destroyed by Python to free up memory.

To get the type of a variable var_1 = 17 all you need to write in Python is:
type(var_1)
This produces: ‘int’

Typing type(var_3) for the variable var_3 = 12.52 produces ‘float’,
and type(var_4) for var_4 = ‘hello’ produces ‘str’

You can easily cast or convert variables to another type, using the functions str(), int(), float() to convert variables to a string, integer or float respectively.

ie var_1 = 33
str(var_1) produces ‘33, whereas float(var_1) produces 33.0

So what happens when you add two variables in Python.
Well that depends on the type of each of the two variables.

If both are strings, python concatenates both
ie var_1 = ‘john’, var_2 = ‘smith’
var_1 + var_2 = ‘johnsmith’

If both are numbers, Python adds the numbers. If one is a float then the result is a float
ie var_1 = 25’, var_2 = 33.0
var_1 + var_2 = 57.0

If one variable is a number and the other is a string, you get an error message. Either you convert both to numbers to get an addition or to strings in order to get a concatenation.

One important aspect of good programming is to endow variables with clear names. Pick a naming system that suits you and stick to it.

Clear variable naming enhances the readability of your code for yourself in future and for others.
Use comments to document what certain sections in your code are designed to produce.

#python #variables #beginner
Рекомендации по теме