Thursday, June 20, 2024

Python Basics, Variables, Data Types and Simulating Constants

The first thing you will notice about the Python programming language is that it differs from other programming languages in its simplicity. You should keep in mind that the Python programming language was created more out of a need to quickly code a solution when you have a programming or mathematical challenge. Everything considered unnecessary in programming languages, such as writing curly braces, was literally removed from it. Then some things that other programming languages have were added. For example, if we compare the Python programming language with the C# programming language, the first thing you will think is that it has fewer data types than the C# programming language, and these are basic ones.

Another significant difference of the Python programming language is that it is not a strongly typed programming language; rather, it is considered a dynamically typed programming language. This means that you do not have to declare data types of variables when defining them; the Python language interpreter itself determines the data type of a variable based on the value you assign to it. Likewise, in the Python programming language, you can change the type of a variable during program execution. If you have no experience with programming, you might wonder, what are variables? You can think of variables as small memory boxes of different sizes into which you can only put one type of data. For example, you cannot put letters in a box intended for integers.

A Programmer Codes in the Python Programming Language at Work

A Programmer Codes in the Python Programming Language at Work

However, you can put integers in a box for letters, but those numbers will no longer be numbers; they will be treated as a string of characters, just like letters. Simply put, variables in every programming language reserve space and store values in the computer's memory. When you create a variable and assign it a value, you are actually reserving free space in the computer's memory. That variable and its value remain in memory as long as your program is running. When you close the program, the variable is deleted. To permanently save a value, you need to write it to a file or database and use variables to transfer that value. Every programming language has different data types intended for different values, and so does the Python programming language.

In the Python programming language, an object is also a basic unit of data, just as it is in the C# programming language. The Python programming language, like the C# programming language, is an object-oriented programming language, which means that all values are treated as objects. Depending on the type of data you use, you will use the appropriate type of variable. It is important for you to learn what types of data are available, what data types you have at your disposal, and how to use them in the Python programming language in the best possible way. Therefore, we will focus solely on that. So, let's look at the basic types in the Python programming language:

bool - boolean type is used for data that can only be True or False.

int - integer type is used for whole numeric data.

float - numeric type used for floating-point numbers.

complex - complex data type used with various mathematical functions.

str - string type used for data consisting of letters and other characters.

list - list data type that can contain different types of data in the same list.

tuple - data type similar to the list data type, but the data can only be read.

dictionary - dictionary data type is a kind of hash table useful for key-value pair data.

Everything You Need to Know About Data Types in Python: Where are char, long, decimal, etc.?

We'll talk about that later! Now it is important to concentrate on these basic data types. As you know, whatever you learn and do, especially in programming, practice is the most important thing. As you code, you will realize that everything we said through practice is simple. So, first start PyCharm or one of your IDE – Integrated Development Environment, which you use. Open the python_tutorial project, which we created in the last post, see here; or create a new python_tutorial project, by naming the directory with the same name. Create a variables.py file and type the following code:

"""

BASIC DATA TYPES, VARIABLES AND CONSTANTS
MANUEL RADOVANOVIC - 2024-06-20
"""

import sys
from decimal import Decimal

print()
print("\t\tBASIC DATA TYPES IN PYTHON PROGRAMMING LANGUAGE\n")
print()

# bool
print("bool")
print("min value:"False)
print("max value:"True)
print(type(True))
print()

# int
print("int")
print("min value:", -sys.maxsize -1)
print("max value:", sys.maxsize)
print(type(0))
print()

# float
print("float")
print("min value:", -sys.float_info.max)
print("max value:", sys.float_info.max)
print(type(0))
print()

# decimal
print("decimal")
print("min value:", Decimal('-Infinity'))
print("max value:", Decimal('Infinity'))
print(type(Decimal()))
print()


# complex
print("complex")
print("min value:"complex(-sys.float_info.max, -sys.float_info.max))
print("max value:"complex(sys.float_info.max, sys.float_info.max))
print(type(0+0j))
print()

# str
print("str")
print("min value: empty string.")
print("max value: Python does not have a fixed, limited length for strings, "
      "so in theory, a string can be of infinite length. 
However, in practice, "
      "memory and performance constraints on the computer determine the actual "
      "limit"
)
print(type(""))
print()

# list
print("list")
print("min value: ", [])
print("max value: Python does not have a fixed, limited length for lists, "
      "so in theory, a list can be of infinite length. However, in practice, "
      "memory and performance constraints on the computer determine the actual "
      "limit"
)
print(type([]))
print()

# tuple
print("tuple")
print("min value: ", ())
print("max value: Python does not have a fixed, limited length for tuples, "
      "so in theory, a tuple can be of infinite length. However, in practice, "
      "memory and performance constraints on the computer determine the actual "
      "limit"
)
print(type(()))
print()

# dictionary
print("dictionary")
print("min value: ", {})
print("max value: Python does not have a fixed, limited length for dictionaries, "
      "so in theory, a dictionary can be of infinite length. However, in practice, "
      "memory and performance constraints on the computer determine the actual "
      "limit"
)
print(type({}))
print()

print('-' 30)
print()

# constants
print("The Python programming language has no constants, only variables!")
print("All you need to do is use a variable instead of a constants, "
      "but name it in uppercase to distinguish it from variables in the code!"
)

When you execute the previous code, you will get the following result:

D:\python_tutorial\Scripts\python.exe D:\python_tutorial\variables.py

 

                                BASIC DATA TYPES IN PYTHON PROGRAMMING LANGUAGE

 

 

bool

min value: False

max value: True

<class 'bool'>

 

int

min value: -9223372036854775808

max value: 9223372036854775807

<class 'int'>

 

float

min value: -1.7976931348623157e+308

max value: 1.7976931348623157e+308

<class 'int'>

 

decimal

min value: -Infinity

max value: Infinity

<class 'decimal.Decimal'>

 

complex

min value: (-1.7976931348623157e+308-1.7976931348623157e+308j)

max value: (1.7976931348623157e+308+1.7976931348623157e+308j)

<class 'complex'>

 

str

min value: empty string.

max value: Python does not have a fixed, limited length for strings, so in theory, a string can be of infinite length. However, in practice, memory and performance constraints on the computer determine the actual limit

<class 'str'>

 

list

min value:  []

max value: Python does not have a fixed, limited length for lists, so in theory, a list can be of infinite length. However, in practice, memory and performance constraints on the computer determine the actual limit

<class 'list'>

 

tuple

min value:  ()

max value: Python does not have a fixed, limited length for tuples, so in theory, a tuple can be of infinite length. However, in practice, memory and performance constraints on the computer determine the actual limit

<class 'tuple'>

 

dictionary

min value:  {}

max value: Python does not have a fixed, limited length for dictionaries, so in theory, a dictionary can be of infinite length. However, in practice, memory and performance constraints on the computer determine the actual limit

<class 'dict'>

 

------------------------------

 

The Python programming language has no constants, only variables!

All you need to do is use a variable instead of a constants, but name it in uppercase to distinguish it from variables in the code!

Process finished with exit code 0


You can also see how we created all this and how it all looks in the following video.

Python - 2. Variables, Data Types and Constants

In the results of the executed code, pay attention to the values you get from the basic data types. The maximum and minimum values of the data types generally depend on the computer or device you are using.

bool

As you can see in the code, the first basic type in the Python programming language is bool. It can be True or False. It cannot be true or false. The Python programming language is case-sensitive, meaning it distinguishes between lowercase and uppercase letters. You can convert the number 1 or 0 to the bool data type to turn it into True or False, but the numbers 1 and 0 are not of the bool type, nor are they substitutes for True or False.

int

The integer data type is meant for positive and negative whole number values, and it simply has no limits and can be of arbitrary length. What limits it is only the device you are using and the amount of memory available. This is why the Python programming language has no long data type since Python 3.x. It has been simply removed. If you need a long data type, just use the integer data type. The integer type can also have values in binary, octal, and hexadecimal forms. You can also use underscores (_) when assigning numbers. For example:

b = 1_000_000

print(b) # result 1000000

float

The float data type is used for floating-point numbers. However, for some calculations with the float data type, you need to be careful, because, for example, for the float data type, the value of 2.55 * 100 is not 255, but approximately. Similarly, 0.1 + 0.2 is not 0.3 but approximately, which can be incorrect for some calculations. Therefore, pay close attention and be cautious when using the float data type.

decimal

To use this data type, you need to import it into your *.py file.

from decimal import Decimal

What applies to the float data type also applies to decimal, except that the decimal data type is slightly more precise because it uses more digits.

complex

As for the complex data type, it is reserved for mathematical calculations. Visually, a complex number can be represented as a pair of numbers, where the first number represents the real part and the second the imaginary part of the complex number. For this purpose, we use the complex data type. Visually, a complex number can be represented as a pair of numbers forming a vector on a diagram, which mathematicians call the Argand diagram, representing the complex plane. In the C# programming language, there is a Complex data type that you can use if you include the System.Numerics namespace where the input arguments are two values of the double type, while in the Python programming language, you do not need to import the complex data type as it is one of the basic Python data types. Additionally, Python has numerous functions and libraries that facilitate mathematical computations.

str

In the Python programming language, the string data type is used by default to store textual data and can contain one or more characters. You can use numerous methods with it that will make text manipulation easier. A string can use both single and double quotes, but my recommendation is to use double quotes. In the Python programming language, there is no char data type. Instead, you use the string data type, but in that case, use single quotes. To get an ASCII character and vice versa, there are the functions chr() and ord() for this purpose. The string type is limited only by your computer's memory, otherwise, you can put an entire book into a string variable.

list

In the Python programming language, the list data type represents a collection of data that allows you to store multiple elements of different data types, such as numbers, strings, boolean values, other lists, etc. A list can be defined by listing the elements separated by commas between square brackets. The list data type is mutable, meaning you can add or remove elements. You can access list elements using their indices, which start at 0 for the first element. It is used when you need to store related elements or when you need to dynamically add and remove elements. You can also use a list as a temporary storage for data processing. The list also has many built-in methods that can be used to manipulate its elements.

tuple

The tuple data type is a type that represents an ordered collection of elements of different data types, similar to a list. Ordered means that the elements of a tuple are fixed and cannot be added, removed, or changed after being defined. The tuple data type is defined by listing the elements separated by commas between regular parentheses. It is used for storing and transferring a fixed number of related data elements that are protected from accidental modification. Some examples of using tuples are storing coordinates of points in a plane or space, storing data on dates, names and surnames, or any other similar data structures that do not change.

In the Python programming language, there are other data types that do not fall under the basic types, which you will get to know in future posts when using them in our tutorial. Each of them has its purpose and is used in specific situations. The Python programming language also introduces new data types in newer and future versions. Here are the ones we know so far:

  • bytesa data type representing an immutable sequence of bytes. Defined using the prefix b.
  • bytearraya data type representing a mutable sequence of bytes. Defined using the bytearray() function.
  • set a data type representing an unordered collection of unique elements. There are no duplicates.
  • frozenset a data type representing an unordered collection of unique elements that cannot be changed.
  • range – a data type representing a sequence of numbers. Defined using the range() function.
  • memoryview – a data type representing a memory view of an object. Defined using the memoryview() function.
  • enumerate – a data type used to iterate through a collection and access elements and their indices. Defined using the enumerate() function.
  • etc.

Simulating Constants in Python: How and Why?

In the Python programming language, there is no special data type for constants; instead, they are often defined as variables that do not change throughout the program. The convention in Python is to write constants in all capital letters to distinguish them from variables. This is primarily useful for other developers reading your code, but also for yourself, to know the difference.

LIGHT_SPEED = 299792458 # m/s






No comments:

Post a Comment