Thursday 17 December 2020

Python: Variables

 

Variable is a named memory location that holds a value.

 

Syntax

variable_name = value

 

Example

message = "Hello World!!!"

 

In the above example, variable name is ‘message’ and it holds the value "Hello World!!!".

 

variables1.py

message = "Hello World!!!"

print(message)

 

Run above program using python interpreter.

 

 

$python3 variables1.py 
Hello World!!!


You can change the value of a variable at any time in the program.

 

variables2.py

message = "Hello World!!!"
print(message)

message = "Hello there, I changed the value"
print(message)


In the above example, message is reassigned with the value "Hello there, I changed the value".

$python3 variables2.py 
Hello World!!!
Hello there, I changed the value


Variable naming conventions

a.   Variables names can contain letters, numbers and underscore. (Ex: principle, rate_of_interest, _version)

b.   Variable name must start with a letter or _

c.    Variable name must not contain spaces.

d.   Do not use python keywords, function names as variable names.

 

 

Note

Always set a value to a variable before using it.

 





Previous                                                    Next                                                    Home

No comments:

Post a Comment