Python variables

Python variables Variables are used as containers or boxes of real world in our Python program. Variable stores our data.

Rules to create variables in Python.
  • Name starts with lower or upper case chars or underscore _
  • Can’t start with number
  • Can contain number , underscore ,char
  • No length restriction
  • Can reassign to different types.
  • Case sensitive
  • Reserved words can’t be used ( What is reserved words ?)
  • Must assign before using
  • Operations within similar variables
  • Scope of Variables

Declaring variable

print ( Address,my_name,_mark,a )
World Raju 65 45
This will generate error SyntaxError: invalid syntax as varaiable name can't start with number.

reassigned to different types

The function type() returns the variable type ( integer, float, string etc )
If a variable is used as Integer, if subsequently we assign string value to it, then the variable type will change to string.

This feature is not allowed in may other programming languages
print(type(my_name)) # <class 'str'>
print(type(my_name)) # <class 'int'>

Case Sensitive

In the code below, 3rd line will generate error as varaible names are case sensitive.
print(my_2nd_Name) # Raju
print(my_2nd_name) # error 

Reserved words

Python has a list of reserved words. We can't use the reserved words as our variable name. Check this list of Reserved words and how to check words here.

Must assign before using

Check the code above, since we have not assigned or used the variable my_end_name before so the line print(my_2nd_name) generates error. ( Variables are case sensitive )

Operations within similar variables

This code will generate error as we can't add integer and a string.
TypeError: unsupported operand type(s) for +: 'int' and 'str'
If we un-comment the line saying b=5 , then output we will get is 50.

Scope of the variable

Can we use the variable in different programs? Answer is No , the variable is no more available after the program is terminated. Even within the program, there is a difference between availability of local variables and global variable. You can read more on local and global variables in python functions.
Download variables.ipynb ( zip ) file
Reserved Keywords in Python Built in Functions in Python

Post your comments , suggestion , error , requirements etc here

We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2020 All rights reserved worldwide Privacy Policy Disclaimer