Friday, August 19, 2022

Understanding Variables and Their Usage

Python supports various different data types, such as integers for whole‐number values, Booleans for True/False values, and strings for words or other sequences of text characters. After creating a variable, you can assign any type of data to it that Python uses. 

So What Is a Variable?

A variable is an area of memory in which you can store data. When you create a variable, you give it a name that enables you to access it to retrieve or change its contents. When your code runs, Python allocates a space in memory for each variable.

For example, you might create a variable called name to store an employee’s name (A). The name would normally be a string of text characters, such as Anna Connor or Bill Ramirez, so the value would receive the str data type, which Python uses for strings. Similarly, you might create a variable called age to store the employee’s age in years as a whole number (B). That value would be an integer, so Python would assign the value the int data type that it uses for integers. Or you might create a variable called isOnProbation to store the employee’s probation status (C). This variable would store the value True or the value False, and Python would assign the value the bool data type that it uses for Boolean values.


In Python, variables themselves do not have data types, so you do not specify the data type when you
create a variable. Instead, the value assigned to the variable has a type. So instead of, say, creating a
variable and giving it the int data type, which is for integers, you would create a variable and assign data of the int data type to it.

This treatment of variables is called dynamic typing and is different from various other programming languages that enable — or require — you to give each variable a specific data type, a practice called  static typing. For example, Microsoft’s Visual Basic programming language encourages you to declare each variable explicitly and assign a data type. For instance, Dim intAge As Integer “dimensions” — creates — a variable called intAge that has the Integer data type and will accept only integer data. Such explicit declarations prevent you from putting the wrong type of data in a variable — trying to do so causes an error — and from overwriting the variable unintentionally by using the same name later in your code.

Share:

0 comments:

Post a Comment