Home Videos Exercises MCQ Q&A Quiz E-Store Services Blog Sign in Appointment Payment

Python Variables

Python variable is a name that refers to a value stored in memory.


What is variable?

Variable is a name that refers to a value stored in memory.

Variables are used to store data that your program can manipulate.


Creating variables

python has no command for declaring variable.

A variable is created the moment you first assign a value to it.

Examples:
a=10
b="Kumar"
print(a)
print(b)

Variables do not need to be declared with any particular type, and can even change type after they have been set.

Examples:
x = 5 # x is of type int x = "Lovely" # x is now of type str print(x)


Type casting

if you want to specify the data type of a variable, this can be done with casting.

Example
x=str(3) #x will be '3'
y=int(3) #y will be 3
z=float(3)#z will be 3.0


Get the Type

You can get the data type of a variable with the type() function.

Example:
x = 7
y = "Raja"
print(type(x))
print(type(y))


Single or double quote

String variables can be declared either by using single or double quotes:
Example:
x = "Lovely"
# is the same as
x = 'Lovely'


Case Sensitive

Variables name are case sensitive
Example:
a = 6 A = "Lovely" #A will not overwrite a


Variable names

A variable can have a short name (like x and y) or a more descriptive name (age, carname, 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
  • 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) A variable name cannot be any of the Python keywords.

Many values to 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 to multiple variables

And you can assign the same value to multiple variables in one line:
Example:
x = y = z = "Grapes"
print(x)
print(y)
print(z)


Unpack a collection

Unpack a list:
cities = ["Noida", "Punjab", "Haryana"] a, b, c = cities print(a) print(b) print(c)


Python global variables

Variables that are created outside of a function (as in all of the examples in the previous pages) are known as global variables.

Global variables can be used by everyone, both inside of functions and outside.

Example: Create a variable outside of a function, and use it inside the function
x = "lightweight"
def myfunc():
print("Python is " + x)
myfunc()


The global keyword

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.
To create a global variable inside a function, you can use the global keyword.
Example:
def myfunc(): global x
x = "fantastic"
myfunc()
print("Python is " + x)