Variable in Python
Variables definition
Variables are boxes for storing information values.
Creating Variables
Python has no command for putting forward a variable.
A variable is created the instant you first assign a cost to it.
Example:
x = 5
y = "John"
print(x)
print(y)
x is a variable ok.
Variable names
A variable can have a short name (like x and y) or a more descriptive name (age, autoname, total volume) Rules for Python variables: A variable name must start with a letter or the underscore character A Variable name cannot start with a number beginA variable name can only contain alphanumeric characters and underscores (A-z, 0-9 and _). Variable names are case sensitive (age, Age and AGE are three different variables)
Example:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
print(myvar)
print(my_var)
print(_my_var)
print(myVar)
print(MYVAR)
print(myvar2)
Many values for multiple variables
Python allows you to assign values to multiple variables in one line:
Example:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
One value for multiple variables
And you can assign the same value to multiple variables in one line:
Example:
x = y = z = "Orange"
print(x)
print(y)
print(z)
Unpacking a Collection
If you have a collection of values in a list, tuple, etc. Python allows you to extract the values into variables. This is called unpacking.
Example:
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
Print variables
Python's print() function is often used to print variables.
Example:
x = "Python is awesome"
print(x)
Global Variables
Variables created outside of a function (as in all the examples above) are called global variables. Global variables can be used by anyone, both inside and outside of functions.
Example:
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
Comments