Python Variables

Vipin | Sun, 07 Jun, 2020 | 161

Creating Python Variables

Variables are created for storing data values.

Unlike other programming languages, Python has no command for declaring a variable.

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

Example

x = 10
y = "SelfCode"
print(x)
print(y)

 

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

Example

x = 10 # x is of type int
x = "Selfcode" # x is now of type str
print(x)

You can check the type if data using type() , it return the data type.

In python string variables can be declared either by using single or double quotes:

Example

x = "Selfcode"
# is the same as
x = 'selfcode'

Naming convention (Rules) of Pyhton 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)

Example

#Legal variable names:
myvar = "SelfCode"
my_var = "SelfCode"
_my_var = "SelfCode"
myVar = "SelfCode"
MYVAR = "SelfCode"
myvar2 = "SelfCode"

#Illegal variable names:
2myvar = "SelfCode"   # can't start with a number
my-var = "SelfCode"   # can't use '-'
my var = "SelfCode"   # can't have space

Remember that variable names are case-sensitive.


Assign Value to Multiple Variables

Python allows you to assign values to multiple variables in one line:

Example

x, y, z = "Mumbai", "Delhi", "Chennai"
print(x)
print(y)
print(z)

And you can assign the same value to multiple variables in one line:

Example

x = y = z = "SelfCode"
print(x)
print(y)
print(z)

# In all variables x,y, and z same value will be assigned.

Global Variables

Global variables are the variables which are created outside of all functions scopes.

Gloable variables are accessible from any part of the code throughout the program.

Example

x = "SelfCode is awasome"   # Created globally

def my_function():
    print(x)

my_function()

If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.

Example

x = "SelfCode is awasome"   # Created globally

def my_function():
    x = "Hello"     # this is local variable
    print(x)        # it will print Hello

my_function()

The global Keyword

global keyword is used to create gloabal variable inside a function.

x = "SelfCode is awasome"   # Created globally

def my_function():
    global x = "Hello"     # this is now referring to global variable
    print(x)        # it will print Hello

my_function()

print(x)   # it will also print Hello as it is global variable

0 comments
Leave a comment