Variables and datatypes in Python

Variables and datatypes are fundamental concepts in Python programming. They allow us to store, manipulate, and reference data effectively in our projects. This article provides a comprehensive guide about Python variables and datatypes

Variables and datatypes in Python

Variables can be thought of as containers with names that are used to hold different types of data.

Variables in Python are dynamic meaning you do not need to declare their type explicitly. Python has no syntax for declaring a variable. A variable is created when some value is assigned to it. 

Creating Variables

Variables are created by assigning a value to them using the assignment operator “=“. The value assigned to a variable determines the data type of that variable. For example:

x = 5
name = "Alice"
is_active = True

print("x:", x)
print("name:", name)
print("is_active:", is_active)
x: 5
name: Alice
is_active: True

Thus, the steps to declare a variable in Python are very simple:

  • Name the variable
  • Assign the required value to it

The variable’s data type will be automatically determined from the value assigned, so there is no need to define it explicitly.

Dynamic Typing

Python is dynamically typed or just dynamic, so the type of a variable can change based on the value assigned to it.

Dynamic typing is a programming language feature that assigns variable types at runtime based on the variable’s value. This means that types are associated with values and not variables. Type checking is performed at run-time as opposed to at compile-time. This offers greater flexibility (you can write code faster because you do not have to specify types every time ).

x = 5      # x is assigned an integer value
type(x)
int
x = "five" # Now x is a string
type(x)
str

Python Variable Naming Conventions

Variables are used everywhere in Python. The variable name should follow a set of naming conventions.

  • Variable names must start with a letter (a-z, A-Z) or an underscore (_).
  • The rest of the variable name can contain letters, digits (0-9), and underscores.
  • Variable names are case-sensitive (myVar and myvar are different variables).
  • Variable names cannot contain spaces 
  • Reserved words (keywords) cannot be used as variable names.
# note that python variable names are case sensitive
name = "Kavya" # valid variable name 
Name = "Bindu" # valid variable name
_name = "Sweety" # valid variable name
1name = "Laila" # Invalid variable name (starting with number)
&name = "Kitty" # Invalid variable name (contain characters other than the underscore)

name-person = "Hyma" # Invalid variable name (contain characters other than the underscore)
for = "something" # Invalid variable name ("for" is a reserved keyword)
and = "anything" # Invalid variable name ("and" is a reserved keyword)

Best Practices for Variable Naming

  • See, you can name the variables anything you want that abides by the naming conventions. But it is always advisable to use a name that is descriptable. That is instead of using some random variable, you can use a name that describes the purpose. For example, if the intent of the variable is to store the age, then name the variable as “age”.
age = 50
amount = 1050.75 
  • If the name of the variable is more than just one word, you cannot leave spaces between the different words when creating the variable. For Python, it is best practice to use snake case.

Snake case is a way of writing phrases without spaces, where spaces are replaced with underscores _ , and the words are all lower case.

total_amount = 150 # snake case
TotalAmount = 200 # pascal case
totalAmount = 250 #camel case

Multiple Assignments

  • Assign Values to Multiple Variables– Python allows you to assign values to multiple variables in one line
a, b, c = 1, 2, 3

#  it is also possible to assign values of different data types
name, age, is_student = "John", 10, True
print(name)
print(age)
print(is_student)
John
10
True
  • Assign the same value to multiple variables
a = b = c = 200
print(a)
print(b)
print(c)
200
200
200
  • Assigning values as a tuple
age = 20,25
print(age)
print(type(age))
(20, 25)
<class 'tuple'>
  • Assigning as a List
age = [20, 25, 30]
print(age)
print(type(age))
[20, 25, 30]
<class 'list'>
  • Unpack a Collection– If you have a collection of values in a list, tuple etc. Python allows you to unpack/extract the values from iterables into variables. This is called unpacking.
# Example tuple
person = ("Alice", 30, "Engineer")

# Unpacking the tuple
name, age, profession = person

print(name)        
print(age)         
print(profession)
Alice
30
Engineer

DataTypes in Python

We have learned about variables in Python. Now let us learn about data types the variables in Python can hold. Python offers several built-in data types. Here are some commonly used datatypes in Python:

Numeric Types

  • Integers (int): Whole numbers, both positive and negative, without a decimal point.
  • Floating-point numbers (float): Numbers with a decimal point.
  • Complex numbers (complex): Numbers with a real and an imaginary part.

String Type

  • String Type(str): Represents a sequence of characters enclosed in single quotes (‘ ‘) or double quotes (” “), such as words or sentences.

Boolean Type

  • Boolean Data Type (bool): Represents either True or False, used for logical operations and conditions.

Sequence Types

  • list: An ordered, mutable collection of items.
  • tuple: An ordered, immutable collection of items.
  • range: Represents an immutable sequence of numbers.

Mapping Type

  • dict: A collection of key-value pairs, where each key is unique.

Set Types

  • set: An unordered collection of unique items.
  • frozenset: An immutable version of a set.

None Type

  • NoneType: Represents the absence of a value.
# Numeric Types
x = 10                # int
y = -5                # int
a = 3.14              # float
b = -0.001            # float
z = 1 + 2j            # complex

# Sequence Types
name = "Alice"        # str
greeting = 'Hello!'   # str
fruits = ["apple", "banana", "cherry"]  # list
coordinates = (10.0, 20.0)              # tuple
numbers = range(1, 10)                  # range

# Mapping Type
person = {"name": "Alice", "age": 30}   # dict

# Set Types
unique_numbers = {1, 2, 3, 4, 5}        # set
frozen_numbers = frozenset([1, 2, 3, 4, 5])  # frozenset

# Boolean Type
is_active = True      # bool
is_logged_in = False  # bool

# None Type
result = None         # NoneType

# Printing values and their types
print("x:", x, "type:", type(x))
print("a:", a, "type:", type(a))
print("z:", z, "type:", type(z))
print("name:", name, "type:", type(name))
print("fruits:", fruits, "type:", type(fruits))
print("coordinates:", coordinates, "type:", type(coordinates))
print("numbers:", list(numbers), "type:", type(numbers))
print("person:", person, "type:", type(person))
print("unique_numbers:", unique_numbers, "type:", type(unique_numbers))
print("frozen_numbers:", frozen_numbers, "type:", type(frozen_numbers))
print("is_active:", is_active, "type:", type(is_active))
print("result:", result, "type:", type(result))

x: 10 type: <class 'int'>
a: 3.14 type: <class 'float'>
z: (1+2j) type: <class 'complex'>
name: Alice type: <class 'str'>
fruits: ['apple', 'banana', 'cherry'] type: <class 'list'>
coordinates: (10.0, 20.0) type: <class 'tuple'>
numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9] type: <class 'range'>
person: {'name': 'Alice', 'age': 30} type: <class 'dict'>
unique_numbers: {1, 2, 3, 4, 5} type: <class 'set'>
frozen_numbers: frozenset({1, 2, 3, 4, 5}) type: <class 'frozenset'>
is_active: True type: <class 'bool'>
result: None type: <class 'NoneType'>

Variables and datatypes are the fundamentals of Python programming. Knowing how to create and use variables, and the different datatypes available, you can write more efficient and effective Python code.

References

Similar Posts

Leave a Reply