Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Programming Articles
Page 627 of 2547
How to Convert Decimal to Binary, Octal, and Hexadecimal using Python?
Python provides built-in functions to convert decimal numbers to different number systems. These functions are bin() for binary, oct() for octal, and hex() for hexadecimal conversion. Syntax bin(number) # Returns binary representation oct(number) # Returns octal representation hex(number) # Returns hexadecimal representation Basic Conversion Example Here's how to convert a decimal number to different number systems ? decimal = 27 print(bin(decimal), "in binary.") print(oct(decimal), "in octal.") print(hex(decimal), "in hexadecimal.") 0b11011 in binary. 0o33 in octal. 0x1b in ...
Read MoreHow to generate statistical graphs using Python?
Python has an amazing graph plotting library called matplotlib. It is the most popular graphing and data visualization module for Python. You can start plotting graphs using just 3 lines of code! Basic Line Plot Here's how to create a simple line plot ? from matplotlib import pyplot as plt # Plot coordinates (1, 4), (2, 5), (3, 1) plt.plot([1, 2, 3], [4, 5, 1]) # Display the plot plt.show() Adding Labels and Title You can enhance your plot with descriptive labels and a title ? from matplotlib import ...
Read MoreHow to generate a random 128 bit strings using Python?
You can generate random 128-bit strings using Python's random module. The getrandbits() function accepts the number of bits as an argument and returns a random integer with that many bits. Using random.getrandbits() The getrandbits() method generates a random integer with exactly 128 bits ? import random hash_value = random.getrandbits(128) print(hex(hash_value)) The output of the above code is ? 0xa3fa6d97f4807e145b37451fc344e58c Converting to Different Formats You can format the 128-bit random number in various ways ? import random # Generate 128-bit random number random_bits = random.getrandbits(128) ...
Read MoreHow to find time difference using Python?
Finding time differences in Python is straightforward using the datetime module and timedelta objects. A timedelta represents a duration — the difference between two dates or times. Understanding timedelta The timedelta constructor accepts various time units as optional parameters ? import datetime # Creating a timedelta object delta = datetime.timedelta(days=7, hours=2, minutes=30, seconds=45) print(f"Duration: {delta}") print(f"Total seconds: {delta.total_seconds()}") Duration: 7 days, 2:30:45 Total seconds: 612645.0 Subtracting Time from Current Date You can subtract a timedelta from a datetime to get an earlier time ? import datetime ...
Read MoreHow to generate XML using Python?
Python provides multiple ways to generate XML documents. The most common approaches are using the dicttoxml package to convert dictionaries to XML, or using Python's built-in xml.etree.ElementTree module for more control. Method 1: Using dicttoxml Package First, install the dicttoxml package ? $ pip install dicttoxml Basic XML Generation Convert a dictionary to XML using the dicttoxml method ? import dicttoxml data = { 'foo': 45, 'bar': { 'baz': "Hello" ...
Read MoreHow to generate a 24bit hash using Python?
A 24-bit hash in Python is essentially a random 24-bit integer value. You can generate these using Python's built-in random module or other methods for different use cases. Using random.getrandbits() The simplest way to generate a 24-bit hash is using random.getrandbits() ? import random hash_value = random.getrandbits(24) print("Decimal:", hash_value) print("Hexadecimal:", hex(hash_value)) print("Binary:", bin(hash_value)) Decimal: 9763822 Hexadecimal: 0x94fbee Binary: 0b100101001111101111101110 Using secrets Module for Cryptographic Use For cryptographically secure random numbers, use the secrets module ? import secrets # Generate cryptographically secure 24-bit hash secure_hash = secrets.randbits(24) ...
Read MoreHow to generate sequences in Python?
A sequence is a positionally ordered collection of items, where each item can be accessed using its index number. The first element's index starts at 0. We use square brackets [] with the desired index to access an element in a sequence. If the sequence contains n items, the last item is accessed using the index n-1. In Python, there are built-in sequence types such as lists, strings, tuples, ranges, and bytes. These sequence types are classified into mutable and immutable. The mutable sequence types are those whose data can be changed after creation, such as list and byte ...
Read MoreWhy python for loops don't default to one iteration for single objects?
Python's for loop is designed to work only with iterable objects. When you try to use a for loop with a single non-iterable object, Python raises a TypeError instead of defaulting to one iteration. Understanding Iterables vs Non-Iterables An iterable is any Python object that implements the iterator protocol by defining the __iter__() method. Common iterables include lists, strings, tuples, and dictionaries. # These are iterable objects numbers = [1, 2, 3] text = "hello" coordinates = (10, 20) for item in numbers: print(item) 1 2 3 ...
Read MoreHow to handle exception inside a Python for loop?
You can handle exceptions inside a Python for loop using try-except blocks. There are two main approaches: handling exceptions for each iteration individually, or handling exceptions for the entire loop. Exception Handling Per Iteration Place the try-except block inside the loop to handle exceptions for each iteration separately ? for i in range(5): try: if i % 2 == 0: raise ValueError(f"Error at iteration {i}") ...
Read MoreWhat are the best practices for using if statements in Python?
Writing efficient and readable if statements is crucial for clean Python code. Following best practices improves performance and maintainability of your conditional logic. Order Conditions by Frequency Place the most likely conditions first to minimize unnecessary checks ? # Poor: rare condition checked first def process_user(user_type): if user_type == "admin": # Only 1% of users return "Admin access" elif user_type == "premium": # 30% of users return "Premium access" ...
Read More