DEV Community

manav shah
manav shah

Posted on

Introduction to Python variables.

What is Python variable :-

First of all, Variable is some byte of memory where any value or character is store in memory, the variable for storing data value, python has no data type, Python has no command for variable declaration, For create a variable just give a name of a variable and assign value like below,

a = 10
b = 19.8
c = "SWAGBLOGGER"
print(a)
print(b)
print(c)
10 19.8 SWAGBLOGGER

The variable doesn't need to declare with any type, also if you want to change the datatype then you can.

a = 10 #a is a int type
b = 19.8 #b is a float type
c = "SWAGBLOGGER" #c is a character type
print(a)
print(b)
print(c)

Variable Names :-
A variable naming has particular no rules, but in programming, we are declared as a small name like x, y, a, b, etc... Else we are declaring a variable with meaning full name.

Rules for python variable
The name started with the letter or underscore character.
Name can't start with numbers.
Name can only start with the alpha-numerical characters and underscores.

Names are case-sensitive.

Legal variable name:-

var = "SWAGBLOGGER" #legal variable name
mvar = "PYTHON" # Legal variable name
Illegal variable name:-

9var = "Jay" #Illegal variable name
m-var = "Manav" #Illegal variable name
hi var = "Riya" #Illegal variable name

Assign a value for multiple variables:-
In python allow values to multiple variable in one line. like below,

a, b, c ="SWAGBLOGGER" , "jay" , "manav"
print(a)
print(b)
print(c)

SWAGBLOGGER jay manav

Output variable:-

The output variable is used to print a statement.

a = "SWAGBLOGGER"
b = ", simple solution for a complex problem"
z = x + y
print(z)

SWAGBLOGGER, simple solution for a complex problem.

What is the global variable:-

What is the global variable?
Variables that are created outside of a function are known as global variables. It can be used by, both inside and outside functions.

how to create variable outside the function.

`x = "superb"

def func():
print("Python is " + x)

func()`

python is superb

How to create variable inside the function.

`x = "superb"

def function():
x = "awesome"
print("Python is " + x)

function()

print("Python is " + x)`

python is awesome. python is superb

Global keyword:-

To create a global variable in function, you can use the global keyword.

use of global keyword

`def myfun():
global a
a = "fabulous"

myfun()

print("SWAGBLOGGER is " + a)`

SWAGBLOGGER is fabulous
Use global keyword inside the function

`x = "awesome"

def fun():
global x
x = "superb"

fun()

print("Python is " + x)`

python is superb

Top comments (0)