Python data types categorize data items, defining the kind of value they hold and determining applicable operations. Since Python treats everything as an object, its data types are classes, with variables as instances (objects) of these classes. Here are Python’s standard or built-in data types:
Numeric
Sequence
Boolean
Set
Dictionary
Binary Types (memoryview, bytearray, bytes)
What Are Python Data Types?
Python provides a function, type(), to determine the data type of any value. Below is an example that assigns various data types to the variable x and prints its type after each assignment.
x = "Hello World"
x = 50
x = 60.5
x = 3j
x = ["apple", "banana", "cherry"]
x = ("apple", "banana", "cherry")
x = range(5)
x = {"name": "John", "age": 30}
x = {"apple", "banana", "cherry"}
x = frozenset({"apple", "banana", "cherry"})
x = True
x = b"Hello"
x = bytearray(5)
x = memoryview(bytes(5))
x = None
1. Numeric Data Types in Python
Numeric types represent values with numerical data: integers, floating-point numbers, and complex numbers.
Integers: Represented by the int class. Holds positive or negative whole numbers, with no limit on size.
Float: Represented by the float class. Real numbers with decimal points or scientific notation (e.g., 3.5 or 4.2e3).
Complex: Represented by the complex class, comprising a real and an imaginary part (e.g., 2 + 3j).
Example
a = 10
print("Type of a:", type(a))
b = 12.34
print("Type of b:", type(b))
c = 2 + 3j
print("Type of c:", type(c))
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
2. Sequence Data Types
Sequences are collections of values stored in an ordered way. Python has several sequence data types:
Strings
Lists
Tuples
String Data Type: Strings in Python represent text data, using Unicode characters. A string can be created using single, double, or triple quotes. Example:
text1 = 'Welcome to Python'
text2 = "It's a powerful language"
text3 = '''Python supports
multiline strings'''
print(text1)
print(text2)
print(text3)
Output:
Welcome to Python
It's a powerful language
Python supports
multiline strings
Accessing String Elements: Strings can be indexed to access individual characters, with negative indexing for accessing elements from the end.
Tuples in Python: A tuple is an immutable sequence data type in Python that can store a collection of items. Once a tuple is created, its elements cannot be changed, added, or removed. Tuples are defined using parentheses () and can hold elements of different data types. Example:
Elements in the set: {'banana', 'apple', 'cherry'}
Is 'apple' in set? True
5. Dictionary Data Type in Python
Dictionaries are unordered, mutable collections of key-value pairs. Each key is unique and maps to a value.
Example:
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
print(person["name"]) # Output: Alice
Output:
Student Name: John
Student Age: 20
6. Binary Types in Python
Python includes three binary types: bytes, bytearray, and memoryview. These are used for low-level data manipulation and working with binary data.
Bytes: An immutable sequence of bytes.
Bytearray: A mutable sequence of bytes.
Memoryview: A memory view object that allows Python code to access the internal data of an object that supports the buffer protocol.
Example:
b = b"Hello"
print("Bytes:", b)
ba = bytearray(5)
print("Bytearray:", ba)
mv = memoryview(bytes(5))
print("Memoryview:", mv)
Output:
Bytes: b'Hello'
Bytearray: bytearray(b'\x00\x00\x00\x00\x00')
Memoryview: <memory at 0x7f1e982f1f40>
Practice examples
Q1. Code to implement basic list operations
# Define the list
fruits = ["mango", "kiwi", "papaya"]
print(fruits)
# Append a new fruit
fruits.append("pineapple")
print(fruits)
# Remove an item
fruits.remove("kiwi")
print(fruits)
# Define the tuple
coordinates = (7, 9)
print(coordinates)
# Access elements in the tuple
print("X-coordinate:", coordinates[0])
print("Y-coordinate:", coordinates[1])
Input and output operations are fundamental to Python programming, allowing programs to interact with users. The print() function displays information on the console, while the input() function captures user input.
Displaying Output in Python
The print() function in Python is the primary method to display output, including text, variables, and expressions.
Example:
print("Hello, World!")
Output:
Hello, World!
Printing Variables
You can print single or multiple variables, adding descriptive labels:
name = "Alice"
age = 30
print("Name:", name, "Age:", age)
Output:
Name: Alice Age: 30
Format Output Handling in Python
Python offers several ways to format output, including the format() method, the sep and end parameters in print(), f-strings, and the % operator. Each method provides control over data display for enhanced readability.
# Using 'end' to connect lines
print("Python", end='@')
print("Programming")
# Using 'sep' for separator
print('G', 'F', 'G', sep='')
# Date formatting example
print('09', '12', '2023', sep='-')
Output:
Python@Programming
GFG
09-12-2023
Using f-string:
name = 'Sam'
age = 25
print(f"Hello, My name is {name} and I'm {age} years old.")
Output:
Hello, My name is Sam and I'm 25 years old.
Using % operator for formatting:
num = int(input("Enter a value: "))
add = num + 5
print("The sum is %d" % add)
Output:
Enter a value: 10
The sum is 15
Taking Multiple Inputs
The split() method helps take multiple inputs in a single line, dividing the inputs into separate variables.
# Taking two inputs at a time
x, y = input("Enter two values: ").split()
print("Number of apples:", x)
print("Number of oranges:", y)
Output:
Enter two values: 3 5
Number of apples: 3
Number of oranges: 5
Conditional Input Handling
You can prompt users for input, convert it to a specific data type, and handle conditions based on that input.
age = int(input("Enter your age: "))
if age < 18:
print("You are a minor.")
elif age < 65:
print("You are an adult.")
else:
print("You are a senior citizen.")
Output:
Enter your age: 22
You are an adult.
Converting Input Types
By default, the input() function reads user input as a string. Convert it to other types like int or float if needed.
Example to take string input:
color = input("What color is the sky?: ")
print(color)
Example to take integer input:
count = int(input("How many stars?: "))
print(count)
Example to take floating-point input:
price = float(input("Enter the price: "))
print(price)
Finding Data Type of a Variable
To determine the data type of a variable, use type().
Exanple:
a = "Hello"
b = 10
c = 12.5
d = ["apple", "banana"]
print(type(a)) # str
print(type(b)) # int
print(type(c)) # float
print(type(d)) # list
In Python, the Console (also referred to as the Shell) is a command-line interpreter. It processes commands entered by the user, one at a time, and executes them. If the command is error-free, the console runs it and displays the result; otherwise, it returns an error message. The prompt in the Python Console appears as >>>, which indicates that it’s ready to accept a new command.
To start coding in Python, understanding how to work with the console is crucial. You can enter a command and press Enter to execute it. After a command has run, >>> will reappear, indicating that the console is ready for the next command.
Accepting Input from the Console
Users can enter values in the Console, which can then be used within the program as needed. The built-in input() function is used to capture user input.
You can convert this input to specific data types (integer, float, or string) by using typecasting.
1. Converting Input to an Integer : When you need to capture integer input from the console, you can convert the input to an integer using int(). This example captures two inputs as integers and displays their sum.
# Taking integer inputs
number1 = int(input("Enter first number: "))
number2 = int(input("Enter second number: "))
# Printing the sum as an integer
print("The sum is:", number1 + number2)
2. Converting Input to a Float : To treat the input as a floating-point number, use the float() function to cast the input.
# Taking float inputs
decimal1 = float(input("Enter first decimal number: "))
decimal2 = float(input("Enter second decimal number: "))
# Printing the sum as a float
print("The sum is:", decimal1 + decimal2)
3. Converting Input to a String: All inputs can be converted to strings, regardless of their original type. The str() function is used for this purpose, though it’s also optional since input() captures input as a string by default.
# Converting input to a string (optional)
text = str(input("Enter some text: "))
# Displaying the input as a string
print("You entered:", text)
# Or simply:
text_default = input("Enter more text: ")
print("You entered:", text_default)
Python Output using print() function
The print() Function in Python
The print() function in Python displays messages on the screen or any other standard output device. Let’s dive into the syntax, optional parameters, and examples that showcase various ways to use print() in Python.
1. value(s): Any number of values to print, which are converted to strings before display. 2. sep: Optional. Defines a separator between multiple values. Default is a space (‘ ‘). 3. end: Optional. Defines what to print at the end of the output. Default is a newline (‘\n’). 4. file: Optional. Specifies a file-like object to write the output to. Default is sys.stdout. 5. flush: Optional. A Boolean value indicating whether to forcibly flush the output. Default is False.
By calling print() without arguments, you can execute it with empty parentheses to print a blank line.
You can pass different data types like variables, strings, and numbers as arguments. print() converts each parameter to a string using str() and concatenates them with spaces.
first_name = "Mona"
age = 28
print("Hello, I am", first_name, "and I am", age, "years old.")
String Literals in print()
\n: Adds a new line.
"": Prints an empty line.
print("DataScienceHub \n is a great resource for learning.")
# Output:
# DataScienceHub
# is a great resource for learning.
Using the end Parameter
The end parameter lets you specify what appears after the output. By default, it’s set to \n, but you can customize it.
print("Data Science is a growing field", end=" ** ")
print("Stay curious!")
# Output:
# Data Science is a growing field ** Stay curious!
Concatenating Strings in print()
You can concatenate strings directly within print().
print("Python is a powerful " + "programming language.")
# Output:
# Python is a powerful programming language.
Output Formatting with str.format()
Using str.format() lets you format the output.
x, y = 5, 20
print("The values of x and y are {} and {}, respectively.".format(x, y))
# Output:
# The values of x and y are 5 and 20, respectively.
Combining print() with input()
You can take input from the user and print it.
number = input("Please enter a number: ")
print("The number you entered is:", number)
Output:
Please enter a number: 50
The number you entered is: 50
Using flush in print()
The flush argument forces Python to write each character immediately, useful in cases like a countdown timer.
import time
countdown = 5
for i in reversed(range(countdown + 1)):
if i > 0:
print(i, end="...", flush=True)
time.sleep(1)
else:
print("Go!")
Using the sep Parameter
The sep argument allows you to customize the separator for multiple values.
The file argument allows you to print to a file rather than the screen.
import io
# Create a virtual file
buffer = io.StringIO()
# Print to the buffer instead of standard output
print("Hello, Pythonistas!", file=buffer)
# Retrieve the contents of the buffer
print(buffer.getvalue())
Output:
Hello, Pythonistas!
In Python, presenting program output can take various forms: it can be printed in a readable format, written to a file, or customized based on user needs. Here’s an overview of Python’s formatting options:
Output Formatting in Python
Python offers several methods for string formatting:
The % operator can be used to format strings in a way similar to printf in C. Although Python doesn’t have a printf() function, the % operator is overloaded to allow printf-style formatting.
In %2d, 2 specifies the width (padded with spaces if shorter). %5.2f formats a float with width 5 and 2 decimal places.
Using the format() Method
Introduced in Python 2.6, the format() method offers flexibility in string formatting. {} placeholders mark where values should be inserted, with the option to specify formatting details.
Example:
print("I enjoy {} with '{}'.".format("coding", "Python"))
print("{0} is the best {1}".format("Python", "language"))
print("{1} is popular for {0}".format("programming", "Python"))
Output:
I enjoy coding with 'Python'.
Python is the best language
Python is popular for programming
Center aligned: *******Python*******
Left aligned: Python--------------
Right aligned: --------------Python
Conversion Codes in Python Formatting
Below is a table of some conversion specifiers:
Code
Meaning
d
Decimal integer
b
Binary format
o
Octal format
x/X
Hexadecimal format
e/E
Exponential notation
f/F
Floating-point decimal
s
String
%
Percentage
How to set an input time limit in Python?
In this article, we will explain how to set an input time limit in Python. Python is an easy-to-learn programming language that is dynamically typed and garbage collected. Here, we will explore different methods to set an input time limit.
Methods to Set an Input Time Limit in Python
Using the inputimeout module
Using the select module
Using the signal module
Using the threading module
Method 1: Set an Input Time Limit using the inputimeout module
The inputimeout module allows users to handle timed input across different platforms. To use this module, it must be installed first using the following command:
pip install inputimeout
Example:
from inputimeout import inputimeout, TimeoutOccurred
try:
# Take timed input using the inputimeout() function
response = inputimeout(prompt='What is your favorite color? ', timeout=5)
except TimeoutOccurred:
response = 'Time is up!'
print(response)
Method 2: Set an Input Time Limit using the select module
The select module provides a way to monitor input/output on multiple file descriptors. It is part of the Python standard library and doesn’t require installation. This method helps handle input with a timeout in a cross-platform way.
Example:
import sys
import select
print("What is your favorite color?")
print("You have 10 seconds to answer.")
# Wait for input with a 10-second timeout
ready, _, _ = select.select([sys.stdin], [], [], 10)
if ready:
print("Your favorite color is:", sys.stdin.readline().strip())
else:
print("Time's up!")
Method 3: Set an Input Time Limit using the signal module
The signal module in Python allows your program to handle asynchronous events such as timeouts. By setting an alarm signal, you can interrupt the input process after a specific time.
Example:
import signal
def timeout_handler(signum, frame):
print("\nTime's up!")
# Set the timeout signal handler
signal.signal(signal.SIGALRM, timeout_handler)
def get_input():
try:
print("What is your favorite color?")
print("You have 5 seconds to answer.")
signal.alarm(5) # Set a 5-second alarm
response = input()
signal.alarm(0) # Cancel the alarm if input is received
return response
except Exception:
return "No answer within time limit"
answer = get_input()
print("Your favorite color is:", answer)
Method 4: Set an Input Time Limit using the threading module
The threading module allows you to run multiple tasks simultaneously. By using a timer, you can create a time limit for input and interrupt it once the time has passed.
Example:
from threading import Timer
def time_up():
print("\nTime's up! You took too long to respond.")
def ask_question():
print("What is your favorite color?")
timer = Timer(5, time_up) # Set a 5-second timer
timer.start()
answer = input()
timer.cancel() # Cancel the timer if input is received on time
return answer
response = ask_question()
print("Your favorite color is:", response)
How to take integer input in Python?
In this article, we’ll cover how to take integer input in Python. By default, Python’s input() function returns a string. To work with integers, we need to convert these inputs to integers using the int() function.
Examples 1: Single Integer Input
# Take input from the user
value = input("Enter a number: ")
# Display data type before conversion
print("Type before conversion:", type(value))
# Convert to integer
value = int(value)
# Display data type after conversion
print("Type after conversion:", type(value))
Output:
Enter a number: 100
Type before conversion: <class 'str'>
Type after conversion: <class 'int'>
Example 2: Taking String and Integer Inputs Separately
# String input
string_value = input("Enter a word: ")
print("Type of string input:", type(string_value))
# Integer input
integer_value = int(input("Enter a number: "))
print("Type of integer input:", type(integer_value))
Output:
Enter the size of the list: 3
Enter list elements (space-separated): 8 16 24
The list is: [8, 16, 24]
Difference between input() and raw_input() functions in Python
Input Functions in Python
In Python, we can use two main functions to capture user input from the keyboard:
1. input ( prompt ) 2. raw_input ( prompt )
input() Function
The input() function allows the program to pause and wait for the user to enter data. It’s built into Python and available in both Python 2.x and 3.x. However, there’s a key difference:
InPython 3.x, input() always returns the user input as a string.
In Python 2.x, input() returns data in the type entered by the user (e.g., numbers are returned as integers). Because of this, it’s often recommended to use raw_input() instead in Python 2.x for better consistency and security.
Example in Python 3.x
# Python 3 example with input() function
name = input("Enter your name: ")
print("Data type:", type(name))
print("You entered:", name)
# Taking a number and converting it to an integer
number = input("Enter a number: ")
print("Data type before conversion:", type(number))
number = int(number)
print("Data type after conversion:", type(number))
print("You entered:", number)
Output:
Enter your name: Alice
Data type: <class 'str'>
You entered: Alice
Enter a number: 42
Data type before conversion: <class 'str'>
Data type after conversion: <class 'int'>
You entered: 42
raw_input() Function
In Python 2.x, raw_input() is used to take user input as a string, similar to the input() function in Python 3.x. It’s the recommended method for general input in Python 2.x due to security vulnerabilities with input().
Example in Python 2.x with raw_input()
# Python 2 example with raw_input() function
name = raw_input("Enter your name: ")
print("Data type:", type(name))
print("You entered:", name)
# Taking a number and converting it to integer
number = raw_input("Enter a number: ")
print("Data type before conversion:", type(number))
number = int(number)
print("Data type after conversion:", type(number))
print("You entered:", number)
Differences Between input() and raw_input() in Python 2.x
input()
raw_input()
Takes user input and tries to evaluate it.
Takes user input as a string.
Syntax: input(prompt)
Syntax: raw_input(prompt)
May execute arbitrary code if not handled correctly.
Python is a high-level, interpreted programming language known for its readability, simplicity, and versatility.
One of Python’s key strengths is its extensive standard library, which provides tools suited to many tasks, from web development to data analysis, artificial intelligence, scientific computing, automation, and more. Python’s dynamic typing and automatic memory management simplify the coding process, allowing developers to write clear, logical code for both small and large-scale projects.
History and Evolution of Python
Python, conceived in the late 1980s by Guido van Rossum at the Centrum Wiskunde & Informatica (CWI) in the Netherlands, was inspired by the ABC language. Van Rossum aimed to create a language emphasizing readability and simplicity.
Today, Python thrives with a vibrant community, regular updates, and strong industry presence. Its history reflects its adaptability, user-centric design, and collaborative development, ensuring it remains a powerful and accessible programming language.
Importance of Python
Python holds a significant position in the overall IT industry due to its versatility, simplicity, and wide range of applications. Here’s a detailed look at its importance:
Versatility
Python’s ability to serve multiple purposes across various domains makes it a highly versatile language. It is used in web development, data science, machine learning, artificial intelligence, automation, scientific computing, and more. This versatility ensures that Python is relevant across different sectors of IT.
Simplicity and Readability
Python’s clear and readable syntax makes it an excellent choice for beginners and experienced developers alike. The simplicity of the language reduces the learning curve, allowing new programmers to quickly become productive. This readability also facilitates collaboration among development teams and improves code maintainability.
Extensive Libraries and Frameworks
Python offers a vast ecosystem of libraries and frameworks that extend its capabilities.
Data Science and Machine Learning: Libraries like NumPy, pandas, Matplotlib, scikit-learn, TensorFlow, and PyTorch.
Web Development: Frameworks like Django and Flask.
Automation and Scripting: Libraries such as Selenium and PyAutoGUI.
Scientific Computing: Libraries like SciPy and SymPy. These resources save development time and effort by providing pre-built solutions for common tasks.
Community Support
Python has a large, active, and supportive community. This community contributes to the language’s development, maintains a wealth of resources, and provides assistance through forums, tutorials, and extensive documentation. This robust support network helps developers solve problems and keep up with best practices.
Cross-Platform Compatibility
Python is platform-independent, meaning it can run on various operating systems, including Windows, macOS, Linux, and Unix. This cross-platform compatibility ensures that Python applications can be developed and deployed across different environments without significant modifications.
Integration Capabilities
Python can easily integrate with other languages and technologies. It can serve as a glue language, connecting components written in C, C++, Java, or other languages. This integration capability makes Python an excellent choice for developing complex, multi-language systems.
Productivity and Rapid Development
Python’s concise syntax and extensive libraries enhance developer productivity by reducing the amount of code needed to implement functionalities. This enables rapid prototyping and faster development cycles, which is crucial in today’s fast-paced IT environment.
Industry Adoption
Python is widely adopted by major tech companies and organizations, including Google, Facebook, NASA, and CERN. Its use in real-world applications and large-scale systems underscores its reliability and effectiveness. The language’s adoption in academia also ensures a steady influx of skilled Python developers into the industry.
Automation and Scripting
Python is a popular choice for automating repetitive tasks and scripting. Its ease of use and powerful libraries enable the automation of a wide range of tasks, from simple file operations to complex workflows, thereby improving efficiency and productivity.
Future-Proofing
Python’s ongoing development and evolution ensure that it remains relevant in the face of emerging technologies. Its adaptability to new trends, such as machine learning and data science, positions Python as a future-proof language in the ever-evolving IT landscape.
Example:
a = 10
b = 3
# Addition
print(a + b) # Output: 13
# Subtraction
print(a - b) # Output: 7
# Multiplication
print(a * b) # Output: 30
# Division
print(a / b) # Output: 3.3333333333333335
# Integer Division
print(a // b) # Output: 3
# Modulus
print(a % b) # Output: 1
# Exponentiation
print(a ** b) # Output: 1000