Python Data Types

JK1536 
Created at Jun 14, 2023 08:18:54
Updated at May 10, 2024 09:32:34 
  798   0   0  

In programming, data type is an important concept.

Variables can store data of different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:

Text Type:str
Numeric Types:int, float, complex
Sequence Types:list, tuple, range
Mapping Type:dict
Set Types:set, frozenset
Boolean Type:bool
Binary Types:bytes, bytearray, memoryview
None Type:NoneType

Getting the Data Type

You can get the data type of any object by using the type() function:

x = 5
print(type(x))

Setting the Data Type

In Python, the data type is set when you assign a value to a variable:

ExampleData Type
x = "Hello World"str
x = 20int
x = 20.5float
x = 1jcomplex
x = ["apple", "banana", "cherry"]list
x = ("apple", "banana", "cherry")tuple
x = range(6)range
x = {"name" : "John", "age" : 36}dict
x = {"apple", "banana", "cherry"}set
x = frozenset({"apple", "banana", "cherry"})frozenset
x = Truebool
x = b"Hello"bytes
x = bytearray(5)bytearray
x = memoryview(bytes(5))memoryview
x = NoneNoneType

 

Setting the Specific Data Type

If you want to specify the data type, you can use the following constructor functions:

ExampleData Type
x = str("Hello World")str
x = int(20)int
x = float(20.5)float
x = complex(1j)complex
x = list(("apple", "banana", "cherry"))list
x = tuple(("apple", "banana", "cherry"))tuple
x = range(6)range
x = dict(name="John", age=36)dict
x = set(("apple", "banana", "cherry"))set
x = frozenset(("apple", "banana", "cherry"))frozenset
x = bool(5)bool
x = bytes(5)bytes
x = bytearray(5)bytearray
x = memoryview(bytes(5))memoryview

Python Numbers

There are three numeric types in Python:

  • int
  • float
  • complex

Variables of numeric types are created when you assign a value to them:

x = 1    # int
y = 2.8  # float
z = 1j   # complex

To verify the type of any object in Python, use the type() function:

print(type(x))
print(type(y))
print(type(z))

 

Int

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.

x = 1
y = 35656222554887711
z = -3255522

print(type(x))
print(type(y))
print(type(z))

 

Float

Float, or "floating point number" is a number, positive or negative, containing one or more decimals.

x = 1.10
y = 1.0
z = -35.59

print(type(x))
print(type(y))
print(type(z))

Float can also be scientific numbers with an "e" to indicate the power of 10.

x = 35e3
y = 12E4
z = -87.7e100

print(type(x))
print(type(y))
print(type(z))

 

Complex

Complex numbers are written with a "j" as the imaginary part:

x = 3+5j
y = 5j
z = -5j

print(type(x))
print(type(y))
print(type(z))

 

Type Conversion

You can convert from one type to another with the int(), float(), and complex() methods:

x = 1    # int
y = 2.8  # float
z = 1j   # complex

#convert from int to float:
a = float(x)

#convert from float to int:
b = int(y)

#convert from int to complex:
c = complex(x)

print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))

 

Random Number

Python does not have a random() function to make a random number, but Python has a built-in module called random that can be used to make random numbers:

import random

print(random.randrange(1, 10))

Python Casting: Specify a Variable Type

There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.

Casting in python is therefore done using constructor functions:

  • int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number)
  • float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer)
  • str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals
x = int(1)   # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
x = float(1)     # x will be 1.0
y = float(2.8)   # y will be 2.8
z = float("3")   # z will be 3.0
w = float("4.2") # w will be 4.2
x = str("s1") # x will be 's1'
y = str(2)    # y will be '2'
z = str(3.0)  # z will be '3.0'

Python Strings

Strings in python are surrounded by either single quotation marks, or double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

print("Hello")
print('Hello')

 

Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal sign and the string:

a = "Hello"
print(a)

 

Multiline Strings

You can assign a multiline string to a variable by using three quotes:

a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

Strings are Arrays

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.

However, Python does not have a character data type, a single character is simply a string with a length of 1.

Square brackets can be used to access elements of the string.

a = "Hello, World!"
print(a[1])

Looping Through a String

Since strings are arrays, we can loop through the characters in a string, with a for loop.

for x in "banana":
  print(x)

String Length

To get the length of a string, use the len() function.

a = "Hello, World!"
print(len(a))

Check String

To check if a certain phrase or character is present in a string, we can use the keyword in.

txt = "The best things in life are free!"
print("free" in txt)
txt = "The best things in life are free!"
if "free" in txt:
  print("Yes, 'free' is present.")

Check if NOT

To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.

txt = "The best things in life are free!"
if "expensive" not in txt:
  print("No, 'expensive' is NOT present.")


Tags: Python Python Casting Python Data Types Python Numbers Share on Facebook Share on X

◀ PREVIOUS
Python Variables

▶ NEXT
Python String Operations

  Comments 0
OTHER POSTS IN THE SAME CATEGORY

Python Classes/Objects

(updated at May 09, 2024)

Python Arrays

(updated at May 09, 2024)

Python Lambda

(updated at May 09, 2024)

Python Functions

(updated at May 09, 2024)

Python While Loops/For Loops

(updated at May 09, 2024)

Python Conditions and If statements

(updated at May 09, 2024)

Python Dictionaries

(updated at May 09, 2024)

Python Sets

(updated at May 09, 2024)

Python Tuples

(updated at May 09, 2024)

Python Comparison Operators

(updated at May 10, 2024)

Python Arithmetic Operators

(created at Jun 14, 2023)

Printing string n times

(created at Jun 14, 2023)

String concatenation by join()

(created at Jun 14, 2023)

Python Lists

(updated at May 10, 2024)

Python String Operations

(updated at May 10, 2024)

Python Variables

(updated at May 10, 2024)

Python Comments

(updated at May 10, 2024)

Python Syntax

(updated at May 10, 2024)

Python Getting Started

(updated at May 10, 2024)

Python Introduction

(created at Jun 12, 2023)

What is Python?

(updated at Jan 04, 2024)

UPDATES

LoL Worldcup - Worlds 2024 Finals Opening Ceremony Presented by Mastercard ft. Linkin Park, Ashnikko and More!

(created at Nov 18, 2024)

The hippie perm of NewJeans' Danielle 

(updated at Nov 15, 2024)

Danielle was featured on the UK Fashion Pop Magazine cover

(updated at Nov 15, 2024)

IU Photos from her family trip

(updated at Nov 09, 2024)

Men vs. Women Taekwondo Sparring - Beautiful Taekwondo Star Tammy's Dazzling Roundhouse Kicks

(updated at Nov 09, 2024)

Legendary Taekwondo Match of the Korean National Sports Festival in High School Division

(updated at Nov 09, 2024)

Legendary Taekwondo 540 degree Kick - Champion Hyun-goo Noh

(created at Nov 09, 2024)

The difference between Equation and Formula

(created at Nov 08, 2024)

Lengendary Turkish Taekwondo player Tazegul at 2015 WTF World Taekwondo Championships

(updated at Nov 08, 2024)

World Rank #2 - Turkey TKD Legend Servet Tazegül

(created at Nov 07, 2024)

Irvine Restaurant American-Style Vietnamese Food Brodard (ft. Ultimate Spring Roll)

(updated at Nov 03, 2024)

Block unwanted URLs for comfortable web browsing with Chrome Addon - URL Blocker

(updated at Nov 01, 2024)

The Gigant Cowboys of Virginia City, Nevada 1889 - AI Generated Photos

(updated at Oct 28, 2024)

Sushi Koto: The "Ohtani" Sushi Spot in Irvine

(created at Oct 26, 2024)

Modern Web Indexing Technology - IndexNow

(updated at Oct 24, 2024)

Key Differences in Gen Z/Alpha/Zalpha based on Upbringing and Life Experiences

(updated at Oct 22, 2024)

Zalpha Generation: A New Term for the Children of Gen Z and Millennials

(updated at Oct 22, 2024)

Zalpha: A Global Trend, Not Just a Distant Concept

(updated at Oct 22, 2024)

The Generation Corona (+ Gen Z) is grappling with how to communicate and live alongside Gen Alpha

(updated at Oct 21, 2024)

Porto's Bakery in Buena Park: A Review from Irvine

(created at Oct 20, 2024)

Starship, Super Heavy, Successful Ground Landing

(updated at Oct 19, 2024)

Understanding Texas A&M - a leading research university, receiving significant funding from both the government and private sector

(updated at Oct 18, 2024)

Exploring UC Davis (aka UCD) - Schools and Majors

(updated at Oct 16, 2024)

AI Generated One-Punch Man with old school style TV shows

(updated at Oct 15, 2024)

One-Punch Man Analysis: The Bald Cape Hero

(updated at Oct 15, 2024)

Why One-Punch Man is a Great Action Anime?

(updated at Oct 15, 2024)

The War of Dogs and Cats - AI-Generated Video by AlgoContent

(updated at Oct 15, 2024)

Dreamy indie band Room402's song "Like the Moon in the Daytime" with AI-generated video

(updated at Oct 15, 2024)

One-Punch Man's Saitama: Motivational Quotes and the Hero's Story

(updated at Oct 13, 2024)

Cream Pan: A Must-Visit Japanese Bakery in Fountain Valley

(created at Oct 13, 2024)

NewJeans - Chicago Live at Lollapalooza 2023

(updated at Oct 12, 2024)

One-Punch Man: Saitama's Promotion Journey and the Final Goal as a Hero

(updated at Oct 12, 2024)

One-Punch Man Combat Power Rankings

(created at Oct 12, 2024)

Difference in HEAD and GET for HTTP Request - why HEAD Request could be used for DDoS Attack?

(updated at Oct 11, 2024)

AI Generated Sailor Moon Video - In the name of justice, I will not forgive you!

(updated at Oct 11, 2024)

Snack that makes my mouth happy when winter comes from the U.S - Hot Pockets

(updated at Oct 11, 2024)

One-Punch Man Crafted by AI - Witness the Limitless Power of Sora AI

(updated at Oct 11, 2024)

My chrome browser is annoying me by Language - How do I change the default language?

(updated at Oct 11, 2024)

AI-Generated Berserk: A Majestic Sight

(updated at Oct 11, 2024)

Global Electronic Medicine Trends and Market Outlook 

(updated at Oct 09, 2024)

What is Google Analytics?

(updated at Oct 09, 2024)

Understanding the Key Differences Between GIS and LBS: Purpose, Technology, and Applications

(updated at Oct 09, 2024)

The Evolution and Applications of Geographic Information Systems: From Thematic Mapping to Efficient Data Analysis and Management

(created at Oct 09, 2024)

Quantum computer and qubit generation method

(updated at Oct 08, 2024)

Green Premium, Eco-Certified Building

(updated at Oct 08, 2024)

Why Two Path Authentication is Essential - My Microsoft Account is Gone!

(updated at Oct 08, 2024)

Amazon's Return-to-Office Mandate: A Bold Move or a Step Backwards?

(updated at Oct 08, 2024)

Exploring UC Merced (aka UCM) - Schools and Majors

(updated at Oct 08, 2024)

Understanding Rose-Hulman Institute of Technology

(updated at Oct 08, 2024)

Understanding Rensselaer Polytechnic Institute based in New York

(updated at Oct 08, 2024)