Variables In Python
Variables are containers in which we can store information or data values such as words or numbers and also we can manipulate them.
Syntax
In Python, we create a variable simply by giving it a name and assigning a value to it using the assignment operator (=).
Example
Data Types
Python has many built-in data types, and variables can hold different types of data. Common data types include integers, floats, strings, booleans, lists, and dictionaries.
In the above example, we didn’t explicitly declare the data type of the variables. Instead, Python dynamically determines the data type based on the assigned values as python is dynamically typed language.
For instance, if you assign a variable a numerical value, Python automatically infers that the variable is of the integer data type.
Printing Variables
We can print the value of a variable using the print() function.
Reassigning Variables
We can change the value of a variable by reassigning it with another value.
Variable Concatenation
For variables type string we can concatenate or combine them using the + operator. If you run the above code the output will be Pythondex as both the first_name & last_name variables are now combined in full_name variable.
Variable Naming Rules
- Begin variable names with a letter (a-z, A-Z) or an underscore (_).
- Variable names should not begin with a number.
- Use letters, numbers, or underscores after the first character.
- Do not use Python keywords (reserved words) as variable names. For example, avoid names like
if
,else
,while
, etc. - Python is case-sensitive, so
myVar
andmyvar
would be considered different variables. - Do not use spaces or special characters (except underscores).
- Choose names that describe the variable’s purpose.
- For multi-word names, connect words with underscores (snake_case).
Example
Variable Case Sensitive Example
The above example illustrates that python is case sensitive. This means that if you have a variable with the same name but differing in the case of at least one character, Python will consider them as 2 different variables.
So this is was the basic overview of variables in Python. By grasping these fundamentals, you’ve acquired the groundwork for handling data in python.