Variables are created when we assign a value to it, variables are used to store values. When a variable is created the interpreter will automatically allocate memory based on the datatype. In python, we do not need to declare or define a variable before using them, In Python the variable declaration happens automatically when you assign a value to a variable
Example:
name = "Neural Beast"
Here “name” is the variable and “Neural Beast” is the value assigned to the variable “name”, the assignment is done with (=) equal sign.
Rules for variables name in python
- A variable names are case-sensitive.(eg: Hello and hello are different)
- The variable name must begin with an alphabet or underscore.
- The first character of a variable cannot be a digit.
- A variable name must not contain any special character like !, @, #, %, &, *, ^ and white-space.
- A variable name can contain an lower-case(a-z), upper-case(A-Z), digit(0-9) and underscore.
- A variable name cannot be a keyword.
In python we can use single quotes, double quotes and triple quotes to assign a string value to a variable.
Example:
A = 'Hello'
B = "Hello"
C = """Hello"""
print(A)
print(B)
print(C)
Output:
Hello
Hello
Hello
Keywords
Keywords have special meaning to the language compiler, keywords are reserved words. In python there are 33 reserved keywords in 3.7 version they are,
and | else | is | while |
as | except | lambda | with |
assert | finally | nonlocal | yield |
break | for | not | False |
class | from | or | def |
continue | global | pass | if |
try | elif | in | raise |
None | del | import | return |
True |
Global Variable
When a variable is created outside of a function, then it is a global variable.
Example:
A = "Neural Beast"
def myfun():
print(A, "Always Deliver More Than Expected")
myfun():
Output:
Neural Beast Always Deliver More Than Expected
We can also create Global variable inside a function using “global” keyword.
Example:
def myfun():
global a
a = "Neural Beast"
myfun()
print(a, "Always Deliver More Than Expected")
Output:
Neural Beast Always Deliver More Than Expected
Python provides type() function which returns the type of the variable passed.
Example:
A = 25
B = 12.3
C = "Neural Beast"
D = True
print(type(A))
print(type(B))
print(type(C))
print(type(D))
Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
Python provides id() function, which is used to identify the object identifier. Each object has its unique id.
A = "Neural Beast"
B = 12
print(id(A))
print(id(B))
Output:
6285416
1687025760
Hello there! Would you mind if I share your blog with my twitter group?
There’s a lot of people that I think would really appreciate your content.Please let me know.
Thanks!