Close container

...with new Python Tips and Tricks
in every couple of weeks


Guide of Python variables and Data Types

Posted on May 26, 2021 By Pawan Jain python

Understanding python variable and data types, a comprehensive guide explaining strings, float, integers, boolean datatypes, with the best practices to follow
Ultimate guide to python variables and datatypes

In this article, you will learn:

  • How to use variables in python
  • How many data types in Python
  • How to play with integer and floating-point numbers;
  • What is the string in python?
  • How to name variables like a pro
  • Best practices to follow with variables

Variables can be seen as a small box, especially used to "hold" the data in the program. Each variable has a unique name, and the data in the variable can be found by the name of the variable. Whether variables are used well or not is very crucial to the quality of the code. Among the many questions about variables, it is a widespread query to give them a good name.

The basic difference between variable and constant is that the data saved by the variable can be modified multiple times, while the constant cannot be modified once a certain data is saved.

Data types

Data Types in python are used to define the type of a variable. In this article, we’ll list out all the data types and discussion the functionality of each.

1. Integer Types

Python 3 supports many types of numeric types, for example, but most commonly used among them are intfloat, and bool. Integers are numbers without fractional parts. It can be positive, 0, and negative similar to the integers on the number line in mathematics

Some strongly typed programming languages ​​provide multiple types of integers. Each type has a different length, and the size of the integers that can be accommodated is also different. Developers should choose different types according to the actual number.

For example, the C language provides four types of integers: short, int, long, and long long, and their lengths increase in sequence. Beginners are often confused when choosing integer types and sometimes lead to numerical overflow.

# Assign a large integer to y >>> x = 88888888888888 >>> print(x) 88888888888888 >>> print(type(x)) class 'int' # Assign a negative integer to y >>> y = -777777777777 >>> print(y) -777777777777 >>> print(type(y)) class 'int'

But Python is different. Integers are not divided into types or that it has only one kind of integer. The value range of Python integers is unlimited. No matter how big or small the number is, Python can easily handle it.

When the used value exceeds the computing power of the computer itself, Python will automatically switch to high-precision calculation (extensive number calculation).

2. Float types

In programming languages, decimals are usually stored as floating-point numbers. Floating-point numbers and fixed-point numbers are relative: if the decimal point moves during storage, it is called a floating-point number; if the decimal point does not move, it is called a fixed-point number.

It can be seen from the running results that Python can accommodate tiny and vast floating-point numbers. But when print outputs a floating-point number, it will discard a part of the number according to the length and size of the floating-point number or use scientific notation.

>>> f = 0.34557808421257003 >>> print(f2) 0.3455780843157 >>> print(type(f2)) class 'float' # See how python truncates the long floating numbers

3. String

The collection of several characters is a string (String). Strings in Python must be surrounded by double quotation marks " "or single quotation marks ' '

Dealing with quotation marks in strings

When quotation marks appear in the string content, we need to put some extra attention to it, otherwise, Python will parse errors, for example:

'I'm a great coder!'

Her, Python will match the single quotation mark in the string with the first single quotation mark, so that 'I' will be treated as a string, and the following m a great coder!', resulting in Grammatical errors.

For this situation, we have two solutions:

1) Escaping quotes

Add a backslash("\") in front of the quotation mark to escape the quotation mark and let Python treat it as normal text, for example:

2) Use different quotes to surround the string

If single quotes appear in the string content, we can use double quotes to surround the string and vice versa.

					    
>> >str1 = 'H'appy birthday to you' >>> print(str1) SyntexError: invalid syntex # Either use a backslash str1 = 'H\'appy birthday to you' # Or use different quotes str1 = "H\'appy birthday to you"

String wrapping

Python is not a free-form language. It has strict syntax requirements for program line breaks and indentation. If you want to write a long string in a new line, you must add a backslash at the end of the line \ like this

>>> str2 = 'Hola everyone good there \ Hope you all are fine till now \ Keep me updated'

Booleans

Python provides the bool type to represent true (right) or false (wrong),

For example5 > 3 implies (5 is greater than 3), which is correct. It is called true (right) in the programming world. Python uses True to represent it and on the other hand 4 > 20 is wrong, it is called false (wrong/error) in the programming world, and Python uses False to represent it.

Boolean values can be used with andor and not operation.

  • The operation is an AND operation, only if everything is true True, the and result of the operation is True
  • The operation is an OR operation, as long as one of them is True, the or result of the operation is True
  • Not operation is a non-operation, it is a unary operator, turns True into False, and False into True
>>> True and False False >>> True or False True >>> not True False

How To Name Variables

It's essential to give a defined and better name to a variable because proper variable naming can greatly improve the overall readability of the code.

Variable names should be as concise and clear.

We know that variable names should be descriptive. If you do not put any restrictions on this principle, you will likely write a highly descriptive variable name: how_much_water_in_jug. If the code is full of such long variable names, it is a disaster for code readability.

A two to three words variable name is considered as good. For example, the above name can be abbreviated as jug_water.

Exceptions for short names

Sometimes, there are some exceptions to the above principle. When some variable names with precise meanings but frequently appear, it is entirely possible to use short abbreviations to make the code more concise. But to reduce the cost of understanding, it is best not to use too many such short names in the same piece of code.

For example, when importing modules in Python, short names are often used as aliases.

Avoid names of existing functions

One should avoid naming variables like existing functions in Python like if, else, or, etc. So try not to use them. Python allowed to make the variables the same as the function name, but one will have errors in code.

Example: If someone declares 'mean' as the variable to calculate the average of some quantities, there is pre-existed function with the same name

Variable names must be detailed

The variable name should describe the content it points to as accurately as possible. So, try not to use those too general names:

  • BAD: hour, host, atm, file
  • GOOD: last_hour, hosts_to_reboot, expired_atm, utils_file

One should guess the variable type

Python is a dynamically typed language. However, people usually have some intuitive practices for the relationship between variable names and types summarizes below.

What kind of name will be treated as bool?

The most significant characteristic of a Boolean is that it only has two possible values ​​Yes or No. Therefore, one who read the variable name thinks that this variable will only have "yes" or "no" values. Here are a few good examples:

  • is_owner: "Whether owner", there will only be couple values: yes/no
  • debug: "Whether to enable 'debug' mode" is regarded as bool
  • allow_student: "Whether students are allowed", there will only be allowed/not allowed

What kind of names for integer and float datatypes?

Names related to amounts/quantities are related to int/float; therefore, there can be more intuitive ways to naming a variable. The following are more common:

  • Use words ending in _id, for example, user_id, host_id
  • Use words starting or ending with length/count, for example, length_of_username, max_length, users_count

Conclusion

Python supports a variety of data types. In the computer, any data can be regarded as an "object", and variables are used in the program to point to these data objects. Assigning a value to a variable is to associate the data with the variable.

Assigning a value x = y to a variable is to point the variable x to the real object, which the variable y points to. Subsequent assignment of y to the variable x does not affect the pointing of the variable.

Note: There is no size limit for integers in Python, while integers in some languages ​​have size limits based on their storage length. For example, Java limits the range of 32-bit integers -2147483648to- 2147483647.

Python's floating-point number has no size limit, but it is directly expressed as inf(infinite) if it exceeds a certain range.

One should follow best practices for naming variable in Python including avoiding of pre-existed function names as variables, the name should be concise and clear and able to serve it's purpose and reader or code tester should able to guess the type of the variable by its name