Here, we will explain about "variables" for Python beginners. It is assumed that you are using Python 3 series.
When defining a variable, write "variable name = value". At this time, = (equal) does not mean that the left side and the right side are "equal", but that the left side and the right side are "equalized", that is, the right side is substituted for the left side. There may or may not be a space before and after the'=', but it is customary to insert a half-width space for easy viewing.
variable_1.py
var_str = 'Hello, World!'
var_int = 123
var_bool = True
Half-width alphanumeric characters and underscores ('_') can be used for variable names. You can use double-byte characters in Python3, but you won't have much chance to use them. When the variable name is more than 2 words, it is common to connect them with an underscore. Try to give the variable a name so that anyone can easily see what value is stored. However, the variable name must not be a reserved word (a word already defined inside Python) or start with a number.
variable_2.py
print = 'Hello, World!' #There is no error at this point, but when I run the print function I get an error.
1num = 123 #An error will occur.
In the above print example, if you write it a little difficult, you will get the image that the object called print was originally a function, but it is replaced with a variable and cannot be executed as a function.
As I write below, variables can be updated in value. On the other hand, when defining a variable (constant) on the assumption that the value will not be updated, it will be easier to understand that the value is not updated by making the variable name all uppercase.
constant.py
CONST = 'constant' #The value can be updated according to the specifications.
You can refer to the value by specifying the variable name as an argument of the print function.
variable_3.py
var_str = 'Hello, World!'
print(var_str)
var_int = 123
print(var_int)
var_bool = True
print(var_bool)
print('var_str') # var_It is output as str.
Note that if you enclose the variable name in quotation marks, it will be output as the character string of the variable name itself, not the value of the variable.
You can update the value of a variable by setting "variable name = value" for the variable that has already been defined.
variable_4.py
var = 'Hello, World!'
print(var) #Definition
var = 'Hello, Python!'
print(var) #update
Here, I explained variables in Python. Since it is used in various situations, I think it is good to deepen your understanding while actually writing a script.
What is the programming language Python? Can it be used for AI and machine learning?
Recommended Posts