Variables

Variables are containers for values that can change during the program:

x = 5     # The value 5 is assigned to a variable with the identifier (name) x.
x += 2 # Add 2 to the old value of x (5) => x = 7
 

Data type

A data type or simply type is an attribute of data which tells the compiler or interpreter how the programmer intends to use the data.

Python distinguishes between the following data types:

String

x = "Test"


Integer

y = 4321


Floating point number (float)

z = -1.2e-3            # z = -1.2 - 10-3 = -0.0012

(E or e stands for a power of ten.)

 

Conversion of data types


If necessary, Python automatically converts the data type. Sometimes, however, it is necessary to perform this conversion explicitly.

Example 1:
myStr = input("Enter a number: ")          # The function input() returns a string

myFloat = float(myStr)                     # In order to be able to calculate with it, 
# a conversion into a number must take place (here float)
myInt = int(myStr)                         # Conversion of the string into an integer

myFloat = float(input("Enter a number: ")) # It's also possible without going through an intermediate variable


Example 2:
myInt = 2
print(myInt + ". Item") # Does not work like this,
# a number must first be converted into a string,
# so that it can be connected to another string

print(str(myInt) + ". Item") # This is how it works. str() converts a number into a string.


Last modified: Monday, 28 October 2019, 10:51 AM