Vipin | Sun, 07 Jun, 2020 | 161
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.
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.
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:
x = "Selfcode" # is the same as x = 'selfcode'
#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.
Python allows you to assign values to multiple variables in one line:
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:
x = y = z = "SelfCode" print(x) print(y) print(z) # In all variables x,y, and z same value will be assigned.
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.
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.
x = "SelfCode is awasome" # Created globally def my_function(): x = "Hello" # this is local variable print(x) # it will print Hello my_function()
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