programming languagesPython Programming

Variables and Objects in Python explained with Example Codes

Variables and objects:

variables and objects in python- Variables are used to temporarily store data while the program is running. The content of the variable is lost as soon as the program ends. ToData To save permanently, the contents of variables must be in a file or database.

All data are considered objects in Python – simple numbers, strings, lists, Tuples, sets, files, and functions(!) As well as instances of predefined or your own Classes. If you already have classic object-oriented programming languages ​​like

If you know Java, C# or C++, you have to rethink this point. Python waived to the usual distinction between elementary data types (e.g. integer, Double, Boolean) and classes and treats all data equally.


Variables

There are simple rules for dealing with variables in Python:

  • Assignment before use: Each variable must be assigned a start value before the variable can be evaluated in an expression. So it is not allowed to execute x = x + 1 unless you have previously made an initial assignment like x = 0, x = 1, x = n.
  • No type declaration: In Python variables, objects can be any Type. Python remembers the type and thus knows which one Type of data a variable references. Unlike many others Programming languages ​​can define or restrict the type of a variable, however will. It is easily possible in one and the same variable To save data of different types, e.g. first a number (x = 1), later a string (x = ‘abc’) and finally a list (x = [3,2,1]).
  • Names: Variable names must begin with letters or an underscore. However, the underscore at the beginning of variable names is for Python internals Data provided, which is why you should not use it in your own scripts should use. The other characters may also contain digits, however no hyphens or spaces. German special characters like “äöüß” are as are many other Unicode characters permitted, but uncommon. Variable names usually consist of all lowercase letters. Capital letter are mostly only used for word compounds, e.g. for a long name.
a = 1

b = 'abc'

a = a + 1

a = c + 1   #Error: Nothing ever happened to c

# assigned.

einLangerName = 3  #OK

ein_langer_name = 4  #also OK

that's not possible = 5   #Error: spaces are not

# allowed.

so - it works - also - not = 6  #Error: As the only special character

# is allowed



Mutable or immutable

What happens when b = a, i.e. when one variable is assigned to another? The question is not as trivial as it seems. Let’s start with an example with whole numbers. In the following code, the value 3 is first stored in a. In the Assignment b = a is replaced by 3. So the number 3 is also stored in b. Around To put it more precisely: a and b are now two variables, both of which refer to an object with the integer 3. A = 4 assigns a new value. On b this has no influence. a and b are independent of each other, a now contains the Value 4, b the value 3.

a = 3

b = a # b

a = 4

print (a, b) # Issue 4, 3

The code for the second example looks very similar. However, here in a and b no simple numbers are stored, but lists. After assigning b = a both variables refer to the same list. A [0] = 4 becomes an element of the list changed. As the print call proves, this change applies to both a and b! A and b are therefore not independent of each other as in the previous example!

a = [1, 2, 3]

b = a # b refers to the same list as a

a [0] = 4 # changes the first list element

print (a, b) # output [4, 2, 3] [4, 2, 3]

Why does Python behave so differently for two apparently very similar programs? The reason is that Python distinguishes between mutable and distinguishes between immutable data types – in technical terms between mutable and immutable types. Numbers, strings and tuples are immutable; h., a Change is impossible. Instead it gets new data every time an expression results, also creates a new object! So if you do x = 10 first and then x = x + 1, then Python creates one first Object with the number 10; x refers to this object. The calculation x + 1 then yields the number 11. Another object is created in memory for this number. The variable x is now changed so that it points to the new object 11. The same is also in the first code example in line a = 4 happens: Python has a new object for the Number 4 generated. a now refers to this object. But this has no influence on b; b still references the object for the number 3. Many other data types and especially lists, however, are mutable. That is why it is possible to change the elements of a list without immediately adding a new object produce. The assignment a [0] therefore does not change the list as a whole, but only one Element of the list. In the second example, a and b therefore continue to refer to the same thing Object whose content has changed.


Copying variable data:

How do you proceed if, for example, you need an independent copy of a list? so that two initially similar lists of two variables are independent of each other can be changed? In such cases, use the copy methods or deepcopy from the copy module:

import copy

a = [1, 2, 3]

b = copy.deepcopy (a) # b refers to an independent copy of a.

a [0] = 4 # changes the first list element of a,

# b remains unchanged.

print (a, b) # output [4, 2, 3] [1, 2, 3]

The copy method makes a copy of the specified object. In the example above a new list object is created for b, which then contains the same objects as a contains. deepcopy goes one step further: it also makes copies of all mutable ones Objects to which the source object refers. In the example above, deepcopy superfluous because the list only contains three whole numbers, i.e. unchangeable ones Objects. However, if the list contains objects that can be changed, duplicate it deepcopy the entire object tree, which is often time-consuming in practice. The following example illustrates the difference between copy and deepcopy. a contains a nested list. copy does duplicate the list in its first level, the In both cases, however, the third list element points to another list object with the Contents [3, 4]. A change in this sublist therefore also applies to a and b, copy doesn’t change that either.

The object for d, however, is created from c with deepcopy. This is also where the list object [3, 4] duplicated, so that both lists (ie c and d) as the third list element again contain two independent lists. Therefore the change c now applies [2] [0] really only for c, but not for d.

import copy

a = [1, 2, [3, 4]]

b = copy. deepcopy(a)

a [2] [0] = 7 # applies to a and b despite copy

print (a, b)

# Output [1, 2, [7, 4]] [1, 2, [7, 4]]

c = [1, 2, [3, 4]]

d = copy.deepcopy(c)

c [2] [0] = 7 # only applies to c because of deepcopy

print (c, d)

# Output [1, 2, [7, 4]] [1, 2, [3, 4]]


Data types

Python knows a number of predefined data types (see Table1). Also can objects are created by classes that are defined in external modules. Here we give you an overview of the most important Python data types and classes including an example and the classification of whether the data can be changed are mutable or immutable.

Table 1: Important Python data types and classes

Data type function example Changeable
Int whole numbers x=3 No
Float Floating point numbers x=3.0 No
Complex complex numbers x=3+4j No
Bool boolean numbers x=bool(1) No
Str Strings x=’abc’ No
Tupel Tupel x=(1, 2, 3) No
List Lists x=[1, 2, 3] Yes
Set Sets x={1, 2, 3} Yes
Dict Dictionaries x = {1: ‘red’, 2: ‘blue’} Yes
Bytearray Byte-Arrays x=bytearray(…) Yes
io.TextIOWrapper Files x=open(‘readme.txt’) Yes
. . . other classes . . . Yes

Python distinguishes between variables and data. Variables are actually just Names that refer to objects, similar to pointers in C or links in HTML. If variables appear on the left side of an assignment (x = …), stored a reference to the object resulting from the expression on the right. However, if variables appear in expressions, Python replaces the name by the object to which the variable points.

Because of this separation of variables and data, it is impossible to specify the data type determine a variable! You can only determine the type of data that the Variable shows. The variable itself has no type! You can find the type of objects with type out. You can try out the following examples interactively:

>>> x = 3; type (x)

<class 'int'>

>>> x = 3.1; type (x)

<class 'float'>

>>> x = {1, 2, 3}; type (x)

<class 'set'>

>>> type (1 == 2)

<class 'bool'>


Typecast

Only in a few cases does Python take care of the type conversion independently, when data of different types are mixed in one expression. If you For example, multiplying an integer by a floating point number will result in the integer automatically converted to a floating point number so that a Floating point multiplication is possible. With such exceptions, you must do the cast yourself To take care of. To do this, use functions whose names correspond to the respective data type match (see table1). For example, to get a string and To combine a number into a new, longer string, you use the function str:

s = 'abc'

x = 3

s = s + str (x) # result 'abc3'

In the opposite direction, int and float convert a character string into a number around. Note that the invalid literal error can occur, e.g. if you try to convert the string ‘abc’ to a number.

>>> int ('123'), float ('123.3')

(123, 123.3)



Compare variables and data:

To test whether two variables are equal, you can do a == b or a is b. This section is about the difference between these two variants and about what equality means. Let’s start with ==: This is how you compare data or the content of objects. In the following example, a and b are the same Strings stored. As expected, the comparison a == b applies and the program gives indicates that the strings in a and b match.

a = 'abc'

b = 'abc'

if a == b:

print ("The contents of variables a and b match.")

In the second example, a character string is again stored in a. Subsequently the content of a is assigned to b. Internally, a and b refer to the same object. The Test a is b therefore applies.

a = 'abc'

b = a

if a is b:

print ("a and b refer to the same object.")

The third example is more difficult: Here two lists are created that are identical. As expected, the first print call outputs two identical lists. Compare by a == b Python the lists. They match, so a == b applies. The comparison a is b does not apply here! a and b refer to two different objects. The lists stored there were created very differently.

a = ['a', 'b', 'c']

b = ['a']

append ('b')
append ('c')

print (a, b) # output ['a', 'b', 'c'] ['a', 'b', 'c']

if a == b: # applies

print ("The lists of variables a and b match.")

if a is b: # does not apply

print ("a and b refer to the same object.")


Validity of variables:

Within an ordinary script without defining its own functions or Python does not distinguish between classes of validity levels. As soon as a variable once defined, it can be used further. An example:

if 1:  # that is always fulfilled

x = 1  # therefore this assignment is carried out

print (x) # ok, issue 1

Just for comparison: In Java a comparable code would look like this and do not work! This comparison also shows how compact and clear Python code compared to code in many other languages ​​is:

// Java code

if (1) {

int x = 1;

}

System. out. println (x); // error, x is not known here

Let’s get back to Python. The following applet throws an error. The if-condition is not fulfilled here. The program runs until print (x), then complains Python that no value is known for x (error message: name x is not defined).

if 0: # that is never fulfilled

x = 1 # therefore this assignment is not carried out

print (x) # error: name 'x' is not defined

Functions and classes are a special case. Variables defined there only apply within the function or only for an object of the class. The following code fragment shows the basic idea.

def f (): # defines the function f

x = 3 # local variable, only valid within f!

print (x)

f () # calls f, issue 3

print (x) # error: name 'x' is not defined


Garbage collection:

Imagine your Python program does the following to create an HTML file:

s = ' '

for i in range (1, 101):

s + = '<p> paragraph' + str (i) + '\ n'

f = open ('out .html', 'w')

write(s)
close()

In a loop, a character string is put together step by step, where each line starts a new HTML paragraph with <p>. Each paragraph contains the Text paragraph nnn. With open the file out.html is created and the text there saved.

Please note that the procedure presented here is not efficient and therefore is not recommended! This example makes the line s + = ‘xxx’ interesting. What is happening here? Python creates a new string 100 times. First contains the Character string <p> paragraph 1 \ n, then <p> paragraph 1 \ n <p> paragraph 2 \ n, then <p> paragraph 1 \ n <p> Paragraph 2 \ n <p> Paragraph 3 \ n etc.

Now we pointed out above that character strings are immutable (immutable) are. So, behind the scenes, Python has to do one for every s + = … statement create a new string, but what happens to the old strings? form the for loop with range (1,10001), Python then takes up memory for 10,000 strings? And what happens when the memory is exhausted? To avoid this, Python removes objects that are no longer needed from memory.

This usually works fully automatically, but how does Python recognize that it is allowed to delete an object? It’s simple: Python counts how many variables or other objects refer to an object. As soon as this counter drops to 0, it is clear that nothing and no one needs the object anymore. It can be deleted.

Circular references, however, can cause problems, mostly multiple Objects refer to each other – but even with this special case python gets along most of the time. For removing such closed object chains The so-called garbage collector is responsible from the memory.


Shared references

As a last detail on the management of variables and objects in python, we would like to give you a very brief overview present the idea of ​​shared references: there are often more than one in larger programs Set variables that refer to similar objects. For example there In the following example there are the two variables a and b, both of which contain the integer 15 or, to put it more precisely, both on an object with the number 15 refer. It actually makes sense to have one and the same object for both variables to use. The technical term for this is Shared References – several variables thus refer to an object that they share to a certain extent.

a = 15    # a = 15

b = 14  # with a little detour

b + = 1  # now also b = 15

if a is b: # is fulfilled under Python 3.2 on the Raspberry Pi

print ('a and b point to the same object')

The idea is simple, but it is much more difficult to realize than it seems. For the concept to work, Python has to put a Reference to a new object is saved, testing whether there is already a same object in memory there. This test has to be done extremely quickly, otherwise the saved storage space at the price of excessive performance losses. In fact, it is often difficult to predict when Python will achieve this optimization and when not. In the following example, where a and b are two identical strings are saved, the detection fails:

a = '' * 2

b = ''

if a is b: # is not fulfilled under Python 3.2 on the Raspberry Pi

print ('a and b point to the same object')

Whether the joint use of similar data is successful is heavily dependent on the implementation and can vary depending on the Python version used and the Change platform. In case you are curious how many references there are to a particular one Object, you can determine this with the sys.getrefcount method:

import sys

print ('1 is from Python' + sys. getrefcount (1) + 'used times')

print ('15 is used by Python '+ sys. getrefcount (15) + 'used times')

print ("'' is used by Python" + sys. getrefcount ('') + 'used times')

It’s quite remarkable that it’s obviously about in Python internal code 600 variables exist, all of which refer to an object with the integer 1!

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button