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 are reserved words ?)
  • Must assign before using
  • Operations within similar variables
  • Scope of Variables

Python variables declaration and naming conventions with rules with sample code using google colab.

Data type of Python variables

Each variable we create or use, belongs to one data type. In Python we can say all data types are Classes and variables are objects of these classes.
i=5
In above line we are saying variable i is an integer variable or i is an object of integer class.
Different Data types in Python

identifiers

Identifiers are name given to python objects like variables, functions, class , modules etc. ( Variables are one type of identifiers )
There are rules for the identifiers.
  • Only lower or upper case chars , digits and underscore are allowed.
  • We can't start identifier name with digit.
  • $ , # , @, !, %,special chars and space can't be used with identifiers
  • We can't use reserved keywords as identifiers.
We can check an identifier by using string method isidentifier().

Declaring Python variables

a=45
my_name="Raju"
_mark=65
Address="World"
print ( Address,my_name,_mark,a )
Output
World Raju 65 45
This code ( below ) will generate error SyntaxError: invalid syntax as variable name can't start with number.
4t=56
Assigning values to multiple variables
width,height=710,710 # assigning multiple variables
x1,y1,x2,y2=5,5,width-5,height-5

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
my_name="Raju"
print(type(my_name)) # <class 'str'>
my_name=420
print(type(my_name)) # <class 'int'>

Case Sensitive

In the code below, 3rd line will generate error as variable names are case sensitive.
my_2nd_Name="Raju"
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. We can't use local, nonlocal, global as variable names as these are reserved keywords in Python.

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.
a=45
b="Hello"
#b=5
print(a+b)
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.
We can convert string to integer by using int() function and use str() to convert integer to string variable.
a='45' # a is a string variable , it is not an integer 
b=42
#print(a+b) # error, as we can't add one string with integer variable 
print(a+str(b)) # this is fine 
print(int(a)+b) # this is fine
Swap the values of variables x and y without using a temporary variable.
x=5
y=10
x,y=y,x
print(x,y) # 10  5 
Choose clear and descriptive variable names to instantly understand their purpose while reading the code.
mark_math=50
mark_english=80
student_name='plus2net'
student_age=25

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 and in global local & nonlocal variables .

packing and unpacking variables

Unpacking allows us to extract elements from iterable objects (like lists, tuples, dictionaries) and assign them to individual variables.
my_list=[1,2,3]
print(*my_list) # unpack and print, output  1 2 3
We are using list and tuple here.
my_list=[1,2,3]
#print(*my_list) # unpack and print, output  1 2 3
def func(*my_var): 
    return sum(my_var) # return / Output 6
print(func(*my_list)) #unpacking 
#print(func(1,2,3))
Using string
my_name='plus2net'# String variable 
x,y,*z = my_name  
print(x) # p
print(y) # l
print(z) # ['u', 's', '2', 'n', 'e', 't']

Example of List Packing

Packing can also be applied to lists. In this example, we'll pack several values into a single list variable.
# Packing multiple values into a single list variable
name, age, country = 'Alice', 30, 'India'
profile = [name, age, country]
print(profile)  # Output: ['Alice', 30, 'India']
Here, the variables name, age, and country are packed into a single list named profile. This demonstrates how you can efficiently group related information into a list structure, facilitating the management and manipulation of data in Python.

deleting variable

In python all are objects only. Here is one integer object a ( variable ) . We will delete the object by using del and again try to print the value.
a=6
print(a) # 6
del a
print(a) # error
The last line will generate error. We can use try except error handling to manage the error.
a=6
try:
  print(a) # 6
  del a
  print(a) # error 
except NameError as my_msg:
    print ("This is a NameError")
    print(my_msg)
except:
    print ("Some other error has occured")
Output
6
This is a NameError
name 'a' is not defined

Checking if variable is defined or not in Python

In PHP we have isset() function to check if variable is defined or not. Here is a way to check variable in Python ( Python isset() ). We used try except error handling code blocks here.
try:
    my_var # variable to check 
except NameError:
    print("Not defined !")
else:
    print("Yes, it was defined.")

Constants

There is no declaration of constant in Python, ( constant is NOT included as a reserved word in Python ) we can reassign the value of such variables after declaring.
constant=9 # No error 
print(constant) # 9
By convention, we declare variables that should not be reassigned with values in uppercase.
SCHOOL_NAME='Name of school'
Usually we keep these constant in a separate .py file and import to main script. This way different files can use the same values.

my_constants.py
MY_NAME='plus2net'
MY_LANGUAGE='Python'
test-1.py
import my_constants
print(my_constants.MY_NAME) # plus2net
print(my_constants.MY_LANGUAGE) # Python
Here are some constants we declare in our script.
PI = 3.1416
MAX_SPEED = 500
WIDTH = 200
HEIGHT =100
API_TOKEN = "1234586987"
DEFAULT_TIMEOUT = 50
BASE_URL = "https://www.plus2net.com"

Questions


  • Python Variables #python #variables
    11-Feb-2024 quixote
Check all our Live sessions on basics of Python

Download variables.ipynb ( zip ) file
Reserved Keywords in Python Operators Identity
Built in Functions in Python Global local and non-local variables in Python

View and Download variables_v1 ipynb file ( .html format )


Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer