Monday, August 22, 2022

Creating a Variable and Assigning Data to It

In Python, you create a variable and assign data to it in a single statement. For example, consider the following line:

price = 125

This line (A) declares a variable called price and initializes it by assigning the value 125 to it. This  value is an integer, a number with no decimal component, so Python gives it the int data type.

You can then change the value if needed, as in the following line:

price = 250

This line (B) assigns the value 250 to the price variable.

You can also assign data of a different data type to the price variable. For example, the following line (C) assigns a string value:

price = "moderate"

Because the price variable does not have a static data type, it accepts the string value without comment. However, some IDEs display a warning when your code contains this kind of change, because it could represent an error, as a programmer would not normally change the data type contained in a variable.


To see what data a variable contains, you can use the print command to display the contents to the console. For example, the following line (A) displays the contents of the price variable:

print(price)

The print command works fine for values that are text or can easily be interpreted as text, but trying to print a variable containing binary data — for example, an image —will usually cause problems.

To see what data type the value assigned to a variable has, you can use the type command with the variable’s name. For example, the following line (B) displays the data type of the value assigned to the price variable:

type(price)

This command returns the value’s class, such as <class 'int'> for the int data type or <class 'str'> for the str data type.



Share:

0 comments:

Post a Comment