Python Variables and Data Types

By:   |   Updated: 2024-04-11   |   Comments   |   Related: > Python


Problem

Just like any other programming language, Python supports many different data types as well as the ability to use variables to make the code more dynamic. In this article, we look at how to use data types and variables in Python.

Solution

Let's take a look at how to use data types and variables in Python.

Variables in Python

Variables are containers that store data values. Usually, in a programming language, you must declare a variable with its data type. However, Python does not have a command for variable declaration. It is created at the moment a value is assigned to it.

Example: x= 5

This statement is interpreted as the "Value 5 is assigned to variable x."

After you declare a variable, you can use this variable in further statements or expressions. For example, you can print this value like this:

x = 5
print(f"My Variable value is {x}")
print the value

A variable stores data values of a specific data type. We can perform several operations on a variable like the one below.

Mathematical Operations

We can perform addition, subtraction, multiplication, and division on variables.

x = 10
y = 2
 
sum = x + y
difference = x - y
product = x * y
quotient = x / y
remainder = x % y
power = x ** y
 
print(sum, difference, product, quotient,remainder,power ) 
mathematical operation

Concatenate Strings

As shown below, Python uses the plus (+) operator for string concatenation.

first_name = "Rajendra"
last_name = "Gupta"
fullname = first_name + " " + last_name
print(fullname)  
Concatenate Strings

Python Data Types

Data types classify or categorize data objects according to their characteristics. For example, we can have different kinds of data, such as integers, strings, and Booleans. Python has built-in data types that do not require additional libraries or modules. These data types are detailed below.

Numeric

The Numeric data type represents the numerical values. These can be subcategorized into the following categories:

  • Integer (or int): Positive or negative numbers without decimal points. Example: 1, 2.
  • Floating (or float): Positive or negative numbers with decimal points. Example: 1.1, 2.4.

You can check the data type of any variable using the TYPE() function, as shown below.

#create a variable with an integer value.
a=50
print("The type of variable having value", a, " is ", type(a))
 
#create a variable with a float value.
b=9.6589
print("The type of variable having value", b, " is ", type(b))
Numeric data type

String (str)

Strings are sequences of characters. These strings are enclosed in single or double quotes. For example, "Hi!" and "Python".

a = "string in a double quote"
b= 'string in a single quote'
print("The type of variable having value", a, " is ", type(a))
print("The type of variable having value", b, " is ", type(b))
String data type

Boolean

The Boolean data type represents TRUE and FALSE values.

# Data type (bool)
x = True
y = False
print(x)            
print(y)            
Boolean data type

Collection

These data types store multiple values in a single entity in Python.

Python has the following collection data types:

Lists (list). The list in Python is similar to the array in C\C++ language. It is an ordered sequence of values enclosed in square brackets and separated by commas (,). A list can have all values of similar or different data types. For example, it can have all integer values or a combination of integers and strings.

#list of having only integers
a= [10,20,30]
print(a)
 
#list of having only strings
b=["hi","hello","mssqltips"]
print(b)
 
#list of having both integers and strings
c= ["hi","list",1,2,3,"example"]
print(c)
Collection, list

Lists use indexing to represent the item's position. The first element of a list has an index value of 0. You can access a specific element based on its indexing position.

For example, suppose you have the following list:

b=["hi","hello","mssqltips"]

If we use b[0], this returns the first element whereas b[2] returns the third element from the list as shown below.

Element positioning

List Operations.  Let's look at a few useful operations in a list.

  • plus (+) or Concatenation: Joins two lists. As shown below, the concatenated list has the elements of both lists (list1 and list2).
list1=["A","B",111,234]
list2 = ["Python","language"]
list1 + list2
plus (+) or Concatenation operation
  • Multiply (*) or Repetition: Repeat elements of an array n number of times. As shown below, we repeated the list of elements three times with multiply (*) operators.
list = ["Python","language"]
list*3
Multiple (*) or Repetition operation
  • In or Not In: If you want to check the existence of an element in a list, you can do it with the operator - in and not in. It returns TRUE or FALSE based on the operator.

For example, if we use an operator and an element exists in the list, you get TRUE in return; otherwise, it returns FALSE. The Not In operator is reverse from the In operator. It returns TRUE if an element does not exist in the list.

In or Not In operation
  • append(): Adds an element at the end of the list. This new element can be an integer, string, or list.
list1=["A","B",111,234]
list1.append('Hi')
list1
Append() operation
list1=["A","B",111,234]
list1.append(["Python"
,"language"])
list1
append() operation
  • insert(): Adds an element to a particular index position.

The following code inserts the element at position 1 (indexing 0):

list1=["A","B",111,234]
list1.insert(0,"Python")
list1
insert() operation

Similarly, the code below inserts the element in the third place (indexing 2):

list1=["A","B",111,234]
list1.insert(2,"Python")
list1
insert() operation
  • Sort(): Sorts elements in ascending or descending order. To sort a list, all elements must be of the same data type, i.e., integer or string.

Sorting elements in ascending order:

list1=[1,5,9,6]
list1.sort()
list1
sort() operation - ascending
list1=["Apple","Orange","Strawberry","Banana"]
list1.sort()
list1
sort() operation - ascending

Sort in the descending order:

list1=["Apple","Orange","Strawberry","Banana"]
list1.sort(reverse = True)
list1
sort() operation - descending

If we try to use a list with mixed data types for sort, it gives the following error.

List sort() error message
  • reverse(): Reverse the order of elements in a given list.
list1=["Apple","Orange","Strawberry","Banana"]
list1.reverse()
list1
reverse() operation
  • count(): Check the number of times an element exists in a list.
list = ["A","B","C","A","A","C"]
list.count("A")
count() operation

Tuple. The Tuple stores values similar to a list but is immutable. Once created, its elements cannot be modified. To create a tuple, use the parentheses() with comma-separated values. Like the list, we can access the tuple element with its indexing position.

#tuple of having only integers
a= (10,20,30)
print(a)
 
#tuple of having only strings
b=("hi","hello","mssqltips")
print(b)
 
#tuple of having both integers and strings
c= ("hi","list",1,2,3,"example")
print(c)
Tuple

Dictionary. Python dictionary uses the key-value pairs to store the ordered collection of items. These key-value pairs are enclosed in the curly brackets separated by a comma.

a = {1:"John",2:"SN", "age":33}
a
Dictionary

In the above example, we can find the following keys and values:

Keys: 1, 2, 'age'

Values: 'John', 'SN', 33

You can retrieve the keys' corresponding value in a dictionary, as shown below.

Dictionary

Dictionary Operations.  Here are some useful operations of a dictionary in Python.

  • items() - Retrieve the list of key-value pairs.
a = {1:"John",2:"SN", "age":33}
a.items()
items() operation
  • keys - Retrieve all keys of a dictionary.
a = {1:"John",2:"SN", "age":33}
a.keys()
keys() operation
  • values() - Retrieves only the values of a dictionary.
a = {1:"John",2:"SN", "age":33}
a.values()
values() operation
  • update () - Merge or append the key-value pairs of a dictionary in a given dictionary.

The following code appends dictionary b into dictionary a using the update() function.

a = {1:"John",2:"SN", "age":33}
b = {"x":"Raj","y":"A"}
a.update(b)
a
update() operation
Next Steps


sql server categories

sql server webinars

subscribe to mssqltips

sql server tutorials

sql server white papers

next tip



About the author
MSSQLTips author Rajendra Gupta Rajendra Gupta is a Consultant DBA with 14+ years of extensive experience in database administration including large critical OLAP, OLTP, Reporting and SharePoint databases.

This author pledges the content of this article is based on professional experience and not AI generated.

View all my tips


Article Last Updated: 2024-04-11

Comments For This Article

















get free sql tips
agree to terms