Introduction
Variables in any programming language are like storage tanks or containers for storing data and the same is in Python as Python Variables store the data and the user performs an operation using/upon those variables.
You can declare a variable by just typing its name and there is no need to assign the type of variable to that variable as python automatically does that for you.
Example
x = 20 y = "I am a variable" z = 'I am also a variable' print(x) print(y) print(z)
Output
20 I am a variable I am also a variable
Also, you can assign a different type of variables to the same variable, see the example below–
Example
x = 20 # integer type x = "aVariable" # string type print(x) # no errors
Output
aVariable
Rules for Naming a Variable
- A variable name must start with a letter or the underscore character
- A variable name cannot start with a number
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Variable names are case-sensitive (age, Age, and AGE are three different variables)
Examples
# legal variable names myVar = 1 YourVar = "var" _thisVar = 20.2 _Thisvar = "notBad" My_Var = "good" MyVar = "Best" # illegal variable names -variable = 12 1variable = "badVarName" my variable = "error"
Multiple Variable Assignment In One Line
Python is the best language if one wants to start learning in the programming world and this is because of its easy syntax here is an example.
You can assign values to any number of variables in a single line, see the example below–
Example
x, y, z = 1, 2, 3 print(x) print(y) print(z)
Output
1 2 3
Assigning one value to many variables in a single line
We can assign a single value to any number of variables in just one line, see the example–
Example
x = y = z = "Hello Dear" print(x) print(y) print(z)
Output
Hello Dear Hello Dear Hello Dear