https://www.w3schools.com/python/exercise.asp?filename=exercise_variables1
Python Variable Names
Every Python variable should have a unique name like a, b, c. A variable name can be meaningful like color, age, name etc. There are certain rules which should be taken care while naming a Python variable:
- A variable name must start with a letter or the underscore character
- A variable name cannot start with a number or any special character like $, (, * % etc.
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Python variable names are case-sensitive which means Name and NAME are two different variables in Python.
- Python reserved keywords cannot be used naming the variable.
Example
Following are valid Python variable names:
counter = 100 _count = 100 name1 = "Zara" name2 = "Nuha" Age = 20 zara_salary = 100000 myvar = "John" my_var = "John" _my_var = "John" myVar = "John" MYVAR = "John" myvar2 = "John" print (counter) print (_count) print (name1) print (name2) print (Age) print (zara_salary)
This will produce the following result:
100 100 Zara Nuha 20 100000
Example
Following are invalid Python variable names:
1counter = 100 $_count = 100 zara-salary = 100000 print (1counter) print ($count) print (zara-salary)
This will produce the following result:
File "main.py", line 3 1counter = 100 ^ SyntaxError: invalid syntax
P
Multi Words Variable Names
Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"
Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"
Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"

Python Variables - Assign Multiple Values
print(x)
print(y)
print(z)
One Value to Multiple Variables
And you can assign the same value to multiple variables in one line:
x = y = z = "Orange"
print(x)
print(y)
print(z)
Python - Output Variables
Output Variables
The Python print()
function is often used to output variables.
x = "Python is awesome"
print(x)
In the print()
function, you output multiple variables, separated by a comma:
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
You can also use the +
operator to output multiple variables:
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
For numbers, the +
character works as a mathematical operator:
x = 5
y = 10
print(x + y)
In the print()
function, when you try to combine a string and a number with the +
operator, Python will give you an error:
y = "John"
print(x + y)
print()
function is to separate them with commas, which even support different data types:y = "John"
print(x, y)
Post a Comment