Table of Contents
An important characteristic of the Python language is the consistency of its object model. Every number, string, data structure, function, class, module, etc. exists in the Python interpreter as a Python object. Each object has an associated type (e.g. string or function) and internal data. In practice this makes the language very flexible, as even functions can be treated like any other object.
In Python, a variable is a name that you assign to an object by using the equal sign. In the first line of the following example, the name a is assigned to the object 3:
1a=1 2b=2 3a+b
In Python, you change a variable’s type simply by assigning it to a new object. This is referred to as dynamic typing.
Python is case-sensitive, so a and A are two different variables. Variable names must follow certain rules:
- They must start with either a letter or an underscore
- They must consist of letters, numbers, and underscores
In the context of objects, variables are called attributes and functions are called methods: attributes give you access to the data of an object, and methods allow you to perform an action. To access attributes and methods, you use the dot notation like this: myobject.attribute and myobject.method().
Let’s make this a bit more tangible: if you write a car racing game, you would most likely use an object that represents a car. The car object could have a speed attribute that allows you to get the current speed via
car.speed, and you might be able to accelerate the car by calling the accelerate method car.accelerate(10), which would increase the speed by ten miles per hour.
The data types int and float represent integers and floating-point numbers, respectively. To find out the data type of a given object, use the built-in type:
If you want to force a number to be a float instead of an int, use either a trailing decimal point or the float constructor:
Using the int constructor, you can turn a float into an int. If the fractional part is not zero, it will be truncated.