❌

Reading view

There are new articles available, click to refresh the page.

Python variable

This blog explores Python variable usage and functionalities.

Store All Data Types

First, let’s list the data types supported in Python.

Python Supported Data Types

  • Primitive Data Types:
    • Integer
    • Float
    • String
    • Boolean
    • None
  • Non-Primitive Data Types:
    • List
    • Tuple
    • Set
    • Bytes and ByteArray
    • Complex
    • Class Object

Store and Experiment with All Data Types

phone = 1234567890
pi    = 3.14
name  = "python programming"
using_python   = True
example_none   = None
simple_list    = [1,2,3]
simple_dict    = {"name":"python"}
simple_set     = {1,1,1,1,1.0}
simple_tuple   = (1,2,3)
complex_number = 3+5j

print("number     = ",phone)
print("float      = ",pi)
print("boolean    = ",using_python)
print("None       = ",example_none)
print("list       = ",simple_list)
print("dictionary = ",simple_dict)
print("set        = ",simple_set)
print("tuple      = ",simple_tuple)
print("complex    = ",complex_number)

Output

number     =  1234567890
float      =  3.14
boolean    =  True
None       =  None
list       =  [1, 2, 3]
dictionary =  {'name': 'python'}
set        =  {1}
tuple      =  (1, 2, 3)
complex    =  (3+5j)

Type Function

This function is used to print the data type of a variable.

print(type(phone))
print(type(pi))
print(type(using_python))
print(type(simple_list))
print(type(simple_dict))
print(type(simple_set))
print(type(simple_tuple))
print(type(complex_number))
print(type(example_none))

Output

<class 'int'>
<class 'float'>
<class 'bool'>
<class 'list'>
<class 'dict'>
<class 'set'>
<class 'tuple'>
<class 'complex'>
<class 'NoneType'>

Bytes and ByteArray

These data types help modify large binary datasets like audio and image processing.

The memoryview() function allows modifying this data without zero-copy access to memory.

bytes is immutable, where as bytearray is mutable.

bytes

b1 = bytes([1,2,3,4])
bo = memoryview(b1)
print("byte example :",bo[0])

Output

byte example : 1

bytearray

b2 = bytearray(b"aaaa")
bo = memoryview(b2)
print("byte array :",b2)
bo[1] = 98
bo[2] = 99
bo[3] = 100
print("byte array :",b2)

Output

byte array : bytearray(b'aaaa')
byte array : bytearray(b'abcd')

Other Data Types

Frozenset

A frozenset is similar to a normal set, but it is immutable.

test_frozenset = frozenset([1,2,1])
for i in test_frozenset:
    print("frozen set item :",i)

Output

frozen set item : 1
frozen set item : 2

Range

The range data type specifies a number range (e.g., 1-10).

It is mostly used in loops and mathematical operations.

a = range(3)
print("a = ",a)
print("type = ",type(a))

Output

a =  range(0, 3)
type =  <class 'range'>

Type Casting

Type casting is converting a data type into another. Try explicit type casting to change data types.

value = 1
numbers = [1,2,3]
print("type casting int     : ",type(int(value)))
print("type casting float   : ",type(float(value)))
print("type casting string  : ",type(str(value)))
print("type casting boolean : ",type(bool("True")))
print("type casting list    : ",type(list(numbers)))
print("type casting set     : ",type(set(numbers)))
print("type casting tuple   : ",type(tuple(numbers)))

Output

type casting int     :  <class 'int'>
type casting float   :  <class 'float'>
type casting string  :  <class 'str'>
type casting boolean :  <class 'bool'>
type casting list    :  <class 'list'>
type casting set     :  <class 'set'>
type casting tuple   :  <class 'tuple'>

Delete Variable

Delete an existing variable using Python’s del keyword.

temp = 1
print("temp variable is : ",temp)
del temp
# print(temp)  => throw NameError : temp not defined

Output

temp variable is :  1

Find Variable Memory Address

Use the id() function to find the memory address of a variable.

temp = "hi"
print("address of temp variable : ",id(temp))

Output

address of temp variable :  140710894284672

Constants

Python does not have a direct keyword for constants, but namedtuple can be used to create constants.

from collections import namedtuple
const = namedtuple("const",["PI"])
math = const(3.14)

print("namedtuple PI = ",math.PI)
print("namedtuple type =",type(math))

Output

namedtuple PI =  3.14
namedtuple type = <class '__main__.const'>

Global Keyword

Before understanding global keyword, understand function-scoped variables.

  • Function inside variable are stored in stack memory.
  • A function cannot modify an outside (global) variable directly, but it can access it.
  • To create a reference to a global variable inside a function, use the global keyword.
message = "Hi"
def dummy():
    global message 
    message = message+" all"

dummy()
print(message)

Output

Hi all

Explicit Type Hint

Type hints are mostly used in function parameters and arguments.

They improve code readability and help developers understand variable types.

-> float : It indicates the return data type.

def area_of_circle(radius :float) -> float:
    PI :float = 3.14
    return PI * (radius * radius)

print("calculate area of circle = ",area_of_circle(2))

Output

calculate area of circle =  12.56

The Magic Photo Album – Python Tuple

Morning: Creating Snapshots

One sunny morning, the adventurous family decides to document their recent trips. They open their magical photo album and start adding new snapshots.

Let’s create snapshots:


# Snapshots of the family's adventures
ooty_adventure = ("Ooty", "2024-07-01", "Visited Botanical Garden")
munnar_adventure = ("Munnar", "2023-12-15", "Saw Nilgiri Tahr in Eravikulam national park")
manjolai_adventure = ("Manjolai", "2023-05-21", "Enjoyed hill stations")

photo_album = [ooty_adventure, munnar_adventure, manjolai_adventure]

Noon: Recalling Memories

At noon, the family gathers around the table and starts recalling details of their Ooty trip.

Accessing Elements:


# Accessing elements in a tuple
location = ooty_adventure[0]
date = ooty_adventure[1]
description = ooty_adventure[2]

print(f"Location: {location}, Date: {date}, Description: {description}")

# output: Location: Ooty, Date: 2024-07-01, Description: Visited Botanical Garden

Afternoon: Sharing Stories

In the afternoon, they decide to share the details of their Munnar trip by unpacking the snapshot into separate parts.

Unpacking Tuples:


# Unpacking tuple
location, date, description = munnar_adventure
print(f"Location: {location}, Date: {date}, Description: {description}")

After some time, They decided to change the values of an ooty adventure


ooty_adventure[2] = "Visited Doddabeta Peak"

Tuples in Python are immutable, meaning that once a tuple is created, its elements cannot be changed.

However, there are some workarounds to β€œchange” values within a tuple by converting it to a mutable data type, such as a list, making the change, and then converting it back to a tuple.

Evening: Combining Adventures

As evening approaches, the family feels nostalgic and decides to combine the Paris and Kenya adventures into one big story.

Concatenating Tuples:


# Concatenating tuples
combined_adventure = ooty_adventure + munnar_adventure
print(combined_adventure)

Night: Reliving Special Moments

Before going to bed, they want to relive the Japan adventure over and over again, emphasizing how special it was.

Repeating Tuples:


# Repeating tuples
repeated_adventure = manjolai_adventure * 2
print(repeated_adventure)

Midnight: Checking the Album

Late at night, they decide to check if their favorite adventures are still part of their magical photo album.

Checking Membership:


# Checking membership
is_ooty_in_album = ooty_adventure in photo_album
is_munnar_in_album = munnar_adventure in photo_album

print(f"Is the Ooty adventure in the album? {is_ooty_in_album}")
print(f"Is the Munnar adventure in the album? {is_munnar_in_album}")

Counting Their Adventures

They also count the number of adventures they have documented in the album so far.


# Finding length of the tuple
number_of_adventures = len(photo_album)
print(f"Number of adventures in the album: {number_of_adventures}")
# Output: Number of adventures in the album: 3

And then they had a good sleep …

❌