Python Programming
Table of content:
- What Is Python? An Introduction
- What Is The History Of Python?
- Key Features Of The Python Programming Language
- Who Uses Python?
- Basic Characteristics Of Python Programming Syntax
- Why Should You Learn Python?
- Applications Of Python Language
- Advantages And Disadvantages Of Python
- Some Useful Python Tips & Tricks For Efficient Programming
- Python 2 Vs. Python 3: Which Should You Learn?
- Python Libraries
- Conclusion
- Frequently Asked Questions
- It's Python Basics Quiz Time!
Table of content:
- Python At A Glance
- Key Features of Python Programming
- Applications of Python
- Bonus: Interesting features of different programming languages
- Summing up...
- FAQs regarding Python
- Take A Quiz To Rehash Python's Features!
Table of content:
- What Is Python IDLE?
- What Is Python Shell & Its Uses?
- Primary Features Of Python IDLE
- How To Use Python IDLE Shell? Setting Up Your Python Environment
- How To Work With Files In Python IDLE?
- How To Execute A File In Python IDLE?
- Improving Workflow In Python IDLE Software
- Debugging In Python IDLE
- Customizing Python IDLE
- Code Examples
- Conclusion
- Frequently Asked Questions (FAQs)
- How Well Do You Know IDLE? Take A Quiz!
Table of content:
- What Is A Variable In Python?
- Creating And Declaring Python Variables
- Rules For Naming Python Variables
- How To Print Python Variables?
- How To Delete A Python Variable?
- Various Methods Of Variables Assignment In Python
- Python Variable Types
- Python Variable Scope
- Concatenating Python Variables
- Object Identity & Object References Of Python Variables
- Reserved Words/ Keywords & Python Variable Names
- Conclusion
- Frequently Asked Questions
- Rehash Python Variables Basics With A Quiz!
Table of content:
- What Is A String In Python?
- Creating String In Python
- How To Create Multiline Python Strings?
- Reassigning Python Strings
- Accessing Characters Of Python Strings
- How To Update Or Delete A Python String?
- Reversing A Python String
- Formatting Python Strings
- Concatenation & Comparison Of Python Strings
- Python String Operators
- Python String Functions
- Escape Sequences In Python Strings
- Conclusion
- Frequently Asked Questions
- Rehash Python Strings Basics With A Quiz!
Table of content:
- What Is Python Namespace?
- Lifetime Of Python Namespace
- Types Of Python Namespace
- The Built-In Namespace In Python
- The Global Namespace In Python
- The Local Namespace In Python
- The Enclosing Namespace In Python
- Variable Scope & Namespace In Python
- Python Namespace Dictionaries
- Changing Variables Out Of Their Scope & Python Namespace
- Best Practices Of Python Namespace
- Conclusion
- Frequently Asked Questions
- Test Your Knowledge Of Python Namespaces!
Table of content:
- What Are Logical Operators In Python?
- The AND Python Logical Operator
- The OR Python Logical Operator
- The NOT Python Logical Operator
- Short-Circuiting Evaluation Of Python Logical Operators
- Precedence of Logical Operators In Python
- How Does Python Calculate Truth Value?
- Final Note On How AND & OR Python Logical Operators Work
- Conclusion
- Frequently Asked Questions
- Python Logical Operators Quiz– Test Your Knowledge!
Table of content:
- What Are Bitwise Operators In Python?
- List Of Python Bitwise Operators
- AND Python Bitwise Operator
- OR Python Bitwise Operator
- NOT Python Bitwise Operator
- XOR Python Bitwise Operator
- Right Shift Python Bitwise Operator
- Left Shift Python Bitwise Operator
- Python Bitwise Operations And Negative Integers
- The Binary Number System
- Application of Python Bitwise Operators
- Python Bitwise Operator Overloading
- Conclusion
- Frequently Asked Questions
- Test Your Knowledge Of Python Bitwise Operators!
Table of content:
- What Is The Print() Function In Python?
- How Does The print() Function Work In Python?
- How To Print Single & Multi-line Strings In Python?
- How To Print Built-in Data Types In Python?
- Print() Function In Python For Values Stored In Variables
- Print() Function In Python With sep Parameter
- Print() Function In Python With end Parameter
- Print() Function In Python With flush Parameter
- Print() Function In Python With file Parameter
- How To Remove Newline From print() Function In Python?
- Use Cases Of The print() Function In Python
- Understanding Print Statement In Python 2 Vs. Python 3
- Conclusion
- Frequently Asked Questions
- Know The print() Function In Python? Take A Quiz!
Table of content:
- Working Of Normal Print() Function
- The New Line Character In Python
- How To Print Without Newline In Python | Using The End Parameter
- How To Print Without Newline In Python 2.x? | Using Comma Operator
- How To Print Without Newline In Python 3.x?
- How To Print Without Newline In Python With Module Sys
- The Star Pattern(*) | How To Print Without Newline & Space In Python
- How To Print A List Without Newline In Python?
- How To Remove New Lines In Python?
- Conclusion
- Frequently Asked Questions
- Think You Can Print Without a Newline in Python? Prove It!
Table of content:
- What Is A Python For Loop?
- How Does Python For Loop Work?
- When & Why To Use Python For Loops?
- Python For Loop Examples
- What Is Rrange() Function In Python?
- Nested For Loops In Python
- Python For Loop With Continue & Break Statements
- Python For Loop With Pass Statement
- Else Statement In Python For Loop
- Conclusion
- Frequently Asked Questions
- Think You Know Python's For Loop? Prove It!
Table of content:
- What Is Python While Loop?
- How Does The Python While Loop Work?
- How To Use Python While Loops For Iterations?
- Control Statements In Python While Loop With Examples
- Python While Loop With Python List
- Infinite Python While Loop in Python
- Python While Loop Multiple Conditions
- Nested Python While Loops
- Conclusion
- Frequently Asked Questions
- Mastered Python While Loop? Let’s Find Out!
Table of content:
- What Are Conditional If-Else Statements In Python?
- Types Of If-Else Statements In Python
- If Statement In Python
- If-Else Statement In Python
- Nested If-Else Statement In Python
- Elif Statement In Python
- Ladder If-Elif-Else Statement In Python
- Short Hand If-Statement In Python
- Short Hand If-Else Statement In Python
- Operators & If-Esle Statement In Python
- Other Statements With If-Else In Python
- Conclusion
- Frequently Asked Questions
- Quick If-Else Statement Quiz– Let’s Go!
Table of content:
- What Is Control Structure In Python?
- Types Of Control Structures In Python
- Sequential Control Structures In Python
- Decision-Making Control Structures In Python
- Repetition Control Structures In Python
- Benefits Of Using Control Structures In Python
- Conclusion
- Frequently Asked Questions
- Control Structures in Python – Are You the Master? Take A Quiz!
Table of content:
- What Are Python Libraries?
- How Do Python Libraries Work?
- Standard Python Libraries (With List)
- Important Python Libraries For Data Science
- Important Python Libraries For Machine & Deep Learning
- Other Important Python Libraries You Must Know
- Working With Third-Party Python Libraries
- Troubleshooting Common Issues For Python Libraries
- Python Libraries In Larger Projects
- Importance Of Python Libraries
- Conclusion
- Frequently Asked Questions
- Quick Quiz On Python Libraries – Let’s Go!
Table of content:
- What Are Python Functions?
- How To Create/ Define Functions In Python?
- How To Call A Python Function?
- Types Of Python Functions Based On Parameters & Return Statement
- Rules & Best Practices For Naming Python Functions
- Basic Types of Python Functions
- The Return Statement In Python Functions
- Types Of Arguments In Python Functions
- Docstring In Python Functions
- Passing Parameters In Python Functions
- Python Function Variables | Scope & Lifetime
- Advantages Of Using Python Functions
- Recursive Python Function
- Anonymous/ Lambda Function In Python
- Nested Functions In Python
- Conclusion
- Frequently Asked Questions
- Python Functions – Test Your Knowledge With A Quiz!
Table of content:
- What Are Python Built-In Functions?
- Mathematical Python Built-In Functions
- Python Built-In Functions For Strings
- Input/ Output Built-In Functions In Python
- List & Tuple Python Built-In Functions
- File Handling Python Built-In Functions
- Python Built-In Functions For Dictionary
- Type Conversion Python Built-In Functions
- Basic Python Built-In Functions
- List Of Python Built-In Functions (Alphabetical)
- Conclusion
- Frequently Asked Questions
- Think You Know Python Built-in Functions? Prove It!
Table of content:
- What Is A round() Function In Python?
- How Does Python round() Function Work?
- Python round() Function If The Second Parameter Is Missing
- Python round() Function If The Second Parameter Is Present
- Python round() Function With Negative Integers
- Python round() Function With Math Library
- Python round() Function With Numpy Module
- Round Up And Round Down Numbers In Python
- Truncation Vs Rounding In Python
- Practical Applications Of Python round() Function
- Conclusion
- Frequently Asked Questions
- Revisit Python’s round() Function – Take The Quiz!
Table of content:
- What Is Python pow() Function?
- Python pow() Function Example
- Python pow() Function With Modulus (Three Parameters)
- Python pow() Function With Complex Numbers
- Python pow() Function With Floating-Point Arguments And Modulus
- Python pow() Function Implementation Cases
- Difference Between Inbuilt-pow() And math.pow() Function
- Conclusion
- Frequently Asked Questions
- Test Your Knowledge Of Python’s pow() Function!
Table of content:
- Python max() Function With Objects
- Examples Of Python max() Function With Objects
- Python max() Function With Iterable
- Examples Of Python max() Function With Iterables
- Potential Errors With The Python max() Function
- Python max() Function Vs. Python min() Functions
- Conclusion
- Frequently Asked Questions
- Think You Know Python max() Function? Take A Quiz!
Table of content:
- What Are Strings In Python?
- What Are Python String Methods?
- List Of Python String Methods For Manipulating Case
- List Of Python String Methods For Searching & Finding
- List Of Python String Methods For Modifying & Transforming
- List Of Python String Methods For Checking Conditions
- List Of Python String Methods For Encoding & Decoding
- List Of Python String Methods For Stripping & Trimming
- List Of Python String Methods For Formatting
- Miscellaneous Python String Methods
- List Of Other Python String Operations
- Conclusion
- Frequently Asked Questions
- Mastered Python String Methods? Take A Quiz!
Table of content:
- What Is Python String?
- The Need For Python String Replacement
- The Python String replace() Method
- Multiple Replacements With Python String.replace() Method
- Replace A Character In String Using For Loop In Python
- Python String Replacement Using Slicing Method
- Replace A Character At a Given Position In Python String
- Replace Multiple Substrings With The Same String In Python
- Python String Replacement Using Regex Pattern
- Python String Replacement Using List Comprehension & Join() Method
- Python String Replacement Using Callback With re.sub() Method
- Python String Replacement With re.subn() Method
- Conclusion
- Frequently Asked Questions
- Know How To Replace Python Strings? Prove It!
Table of content:
- What Is String Slicing In Python?
- How Indexing & String Slicing Works In Python
- Extracting All Characters Using String Slicing In Python
- Extracting Characters Before & After Specific Position Using String Slicing In Python
- Extracting Characters Between Two Intervals Using String Slicing In Python
- Extracting Characters At Specific Intervals (Step) Using String Slicing In Python
- Negative Indexing & String Slicing In Python
- Handling Out-of-Bounds Indices In String Slicing In Python
- The slice() Method For String Slicing In Python
- Common Pitfalls Of String Slicing In Python
- Real-World Applications Of String Slicing
- Conclusion
- Frequently Asked Questions
- Quick Python String Slicing Quiz– Let’s Go!
Table of content:
- Introduction To Python List
- How To Create A Python List?
- How To Access Elements Of Python List?
- Accessing Multiple Elements From A Python List (Slicing)
- Access List Elements From Nested Python Lists
- How To Change Elements In Python Lists?
- How To Add Elements To Python Lists?
- Delete/ Remove Elements From Python Lists
- How To Create Copies Of Python Lists?
- Repeating Python Lists
- Ways To Iterate Over Python Lists
- How To Reverse A Python List?
- How To Sort Items Of Python Lists?
- Built-in Functions For Operations On Python Lists
- Conclusion
- Frequently Asked Questions
- Revisit Python Lists Basics With A Quick Quiz!
Table of content:
- What Is List Comprehension In Python?
- Incorporating Conditional Statements With List Comprehension In Python
- List Comprehension In Python With range()
- Filtering Lists Effectively With List Comprehension In Python
- Nested Loops With List Comprehension In Python
- Flattening Nested Lists With List Comprehension In Python
- Handling Exceptions In List Comprehension In Python
- Common Use Cases For List Comprehensions
- Advantages & Disadvantages Of List Comprehension In Python
- Best Practices For Using List Comprehension In Python
- Performance Considerations For List Comprehension In Python
- For Loops & List Comprehension In Python: A Comparison
- Difference Between Generator Expression & List Comprehension In Python
- Conclusion
- Frequently Asked Questions
- Rehash Python List Comprehension Basics With A Quiz!
Table of content:
- What Is A List In Python?
- How To Find Length Of List In Python?
- For Loop To Get Python List Length (Naive Approach)
- The len() Function To Get Length Of List In Python
- The length_hint() Function To Find Length Of List In Python
- The sum() Function To Find The Length Of List In Python
- The enumerate() Function To Find Python List Length
- The Counter Class From collections To Find Python List Length
- The List Comprehension To Find Python List Length
- Find The Length Of List In Python Using Recursion
- Comparison Between Ways To Find Python List Length
- Conclusion
- Frequently Asked Questions
- Know How To Get Python List Length? Prove it!
Table of content:
- List of Methods To Reverse A Python List
- Python Reverse List Using reverse() Method
- Python Reverse List Using the Slice Operator ([::-1])
- Python Reverse List By Swapping Elements
- Python Reverse List Using The reversed() Function
- Python Reverse List Using A for Loop
- Python Reverse List Using While Loop
- Python Reverse List Using List Comprehension
- Python Reverse List Using List Indexing
- Python Reverse List Using The range() Function
- Python Reverse List Using NumPy
- Comparison Of Ways To Reverse A Python List
- Conclusion
- Frequently Asked Questions
- Time To Test Your Python List Reversal Skills!
Table of content:
- What Is Indexing In Python?
- The Python List index() Function
- How To Use Python List index() To Find Index Of A List Element
- The Python List index() Method With Single Parameter (Start)
- The Python List index() Method With Start & Stop Parameters
- What Happens When We Use Python List index() For An Element That Doesn't Exist
- Python List index() With Nested Lists
- Fixing IndexError Using The Python List index() Method
- Python List index() With Enumerate()
- Real-world Examples Of Python List index() Method
- Difference Between find() And index() Method In Python
- Conclusion
- Frequently Asked Questions
- Think You Know Python List Indexing? Take A Quiz!
Table of content:
- How To Remove Elements From List In Python?
- The remove() Method To Remove Element From Python List
- The pop() Method To Remove Element From List In Python
- The del Keyword To Remove Element From List In Python
- The clear() Method To Remove Elements From Python List
- List Comprehensions To Conditionally Remove Element From List In Python
- Key Considerations For Removing Elements From Python Lists
- Why We Need to Remove Elements From Python List
- Performance Comparison Of Methods To Remove Element From List In Python
- Conclusion
- Frequently Asked Questions
- Quiz– Prove You Know How To Remove Item From Python Lists!
Table of content:
- How To Remove Duplicates From A List In Python?
- The set() Function To Remove Duplicates From Python List
- Remove Duplicates From Python List Using For Loop
- Using List Comprehension Remove Duplicates From Python List
- Remove Duplicates From Python List Using enumerate() With List Comprehension
- Dictionary & fromkeys() Method To Remove Duplicates From Python List
- Remove Duplicates From Python List Using in, not in Operators
- Remove Duplicates From Python List Using collections.OrderedDict.fromkeys()
- Remove Duplicates From Python List Using Counter with freq.dist() Method
- The del Keyword Remove Duplicates From Python List
- Remove Duplicates From Python List Using DataFrame
- Remove Duplicates From Python List Using pd.unique and np.unipue
- Remove Duplicates From Python List Using reduce() function
- Comparative Analysis Of Ways To Remove Duplicates From Python List
- Conclusion
- Frequently Asked Questions
- Think You Know How to Remove Duplicates? Take A Quiz!
Table of content:
- What Is Python List & How To Access Elements?
- What Is IndexError: List Index Out Of Range & Its Causes In Python?
- Understanding Indexing Behavior In Python Lists
- How to Prevent/ Fix IndexError: List Index Out Of Range In Python
- Handling IndexError Gracefully Using Try-Except
- Debugging Tips For IndexError: List Index Out Of Range Python
- Conclusion
- Frequently Asked Questions
- Avoiding ‘List Index Out of Range’ Errors? Take A Quiz!
Table of content:
- What Is the Python sort() List Method?
- Sorting In Ascending Order Using The Python sort() List Method
- How To Sort Items In Descending Order Using Python sort() List Method
- Custom Sorting Using The Key Parameter Of Python sort() List Method
- Examples Of Python sort() List Method
- What Is The sorted() List Method In Python
- Differences Between sorted() And sort() List Methods In Python
- When To Use sorted() & When To Use sort() List Method In Python
- Conclusion
- Frequently Asked Questions
- Take A Quick Python's sort() Quiz!
Table of content:
- What Is A List In Python?
- What Is A String In Python?
- Why Convert Python List To String?
- How To Convert List To String In Python?
- The join() Method To Convert Python List To String
- Convert Python List To String Through Iteration
- Convert Python List To String With List Comprehension
- The map() Function To Convert Python List To String
- Convert Python List to String Using format() Function
- Convert Python List To String Using Recursion
- Enumeration Function To Convert Python List To String
- Convert Python List To String Using Operator Module
- Python Program To Convert String To List
- Conclusion
- Frequently Asked Questions
- Convert Lists To Strings Like A Pro! Take A Quiz
Table of content:
- What Is Inheritance In Python?
- Python Inheritance Syntax
- Parent Class In Python Inheritance
- Child Class In Python Inheritance
- The __init__() Method In Python Inheritance
- The super() Function In Python Inheritance
- Method Overriding In Python Inheritance
- Types Of Inheritance In Python
- Special Functions In Python Inheritance
- Advantages & Disadvantages Of Inheritance In Python
- Common Use Cases For Inheritance In Python
- Best Practices for Implementing Inheritance in Python
- Avoiding Common Pitfalls in Python Inheritance
- Conclusion
- Frequently Asked Questions
- 💡 Python Inheritance Quiz – Are You Ready?
Table of content:
- What Is The Python List append() Method?
- Adding Elements To A Python List Using append()
- Populate A Python List Using append()
- Adding Different Data Types To Python List Using append()
- Adding A List To Python List Using append()
- Nested Lists With Python List append() Method
- Practical Use Cases Of Python List append() Method
- How append() Method Affects List Performance
- Avoiding Common Mistakes When Using Python List append()
- Comparing extend() With append() Python List Method
- Conclusion
- Frequently Asked Questions
- 🧠 Think You Know Python List append()? Take A Quiz!
Table of content:
- What Is A Linked List In Python?
- Types Of Linked Lists In Python
- How To Create A Linked List In Python
- How To Traverse A Linked List In Python & Retrieve Elements
- Inserting Elements In A Linked List In Python
- Deleting Elements From A Linked List In Python
- Update A Node Of Linked List In Python
- Reversing A Linked List In Python
- Calculating Length Of A Linked List In Python
- Comparing Arrays And Linked Lists In Python
- Advantages & Disadvantages Of Linked List In Python
- When To Use Linked Lists Over Other Data Structures
- Practical Applications Of Linked Lists In Python
- Conclusion
- Frequently Asked Questions
- 🔗 Linked List Logic: Can You Ace This Quiz?
Table of content:
- What Is Extend In Python?
- Extend In Python With List
- Extend In Python With String
- Extend In Python With Tuple
- Extend In Python With Set
- Extend In Python With Dictionary
- Other Methods To Extend A List In Python
- Difference Between append() and extend() In Python
- Conclusion
- Frequently Asked Questions
- Think You Know extend() In Python? Prove It!
Table of content:
- What Is Recursion In Python?
- Key Components Of Recursive Functions In Python
- Implementing Recursion In Python
- Recursion Vs. Iteration In Python
- Tail Recursion In Python
- Infinite Recursion In Python
- Advantages Of Recursion In Python
- Disadvantages Of Recursion In Python
- Best Practices For Using Recursion In Python
- Conclusion
- Frequently Asked Questions
- Recursive Thinking In Python: Test Your Skills!
Table of content:
- What Is Type Conversion In Python?
- Types Of Type Conversion In Python
- Implicit Type Conversion In Python
- Explicit Type Conversion In Python
- Functions Used For Explicit Data Type Conversion In Python
- Important Type Conversion Tips In Python
- Benefits Of Type Conversion In Python
- Conclusion
- Frequently Asked Questions
- Think You Know Type Conversion? Take A Quiz!
Table of content:
- What Is Scope In Python?
- Local Scope In Python
- Global Scope In Python
- Nonlocal (Enclosing) Scope In Python
- Built-In Scope In Python
- The LEGB Rule For Python Scope
- Python Scope And Variable Lifetime
- Best Practices For Managing Python Scope
- Conclusion
- Frequently Asked Questions
- Think You Know Python Scope? Test Yourself!
Table of content:
- Understanding The Continue Statement In Python
- How Does Continue Statement Work In Python?
- Python Continue Statement With For Loops
- Python Continue Statement With While Loops
- Python Continue Statement With Nested Loops
- Python Continue With If-Else Statement
- Difference Between Pass and Continue Statement In Python
- Practical Applications Of Continue Statement In Python
- Conclusion
- Frequently Asked Questions
- Python 'continue' Statement Quiz: Can You Ace It?
Table of content:
- What Are Control Statements In Python?
- Types Of Control Statements In Python
- Conditional Control Statements In Python
- Loop Control Statements In Python
- Control Flow Altering Statements In Python
- Exception Handling Control Statements In Python
- Conclusion
- Frequently Asked Questions
- Mastering Control Statements In Python – Take the Quiz!
Table of content:
- Difference Between Mutable And Immutable Data Types in Python
- What Is Mutable Data Type In Python?
- Types Of Mutable Data Types In Python
- What Are Immutable Data Types In Python?
- Types Of Immutable Data Types In Python
- Key Similarities Between Mutable And Immutable Data Types In Python
- When To Use Mutable Vs Immutable In Python?
- Conclusion
- Frequently Asked Questions
- Quiz Time: Mutable vs. Immutable In Python!
Table of content:
- What Is A List?
- What Is A Tuple?
- Difference Between List And Tuple In Python (Comparison Table)
- Syntax Difference Between List And Tuple In Python
- Mutability Difference Between List And Tuple In Python
- Other Difference Between List And Tuple In Python
- List Vs. Tuple In Python | Methods
- When To Use Tuples Over Lists?
- Key Similarities Between Tuples And Lists In Python
- Conclusion
- Frequently Asked Questions
- 🧐 Lists vs. Tuples Quiz: Test Your Python Knowledge!
Table of content:
- Introduction to Python
- Downloading & Installing Python, IDLE, Tkinter, NumPy & PyGame
- Creating A New Python Project
- How To Write Python Hello World Program In Python?
- Way To Write The Hello, World! Program In Python
- The Hello, World! Program In Python Using Class
- The Hello, World! Program In Python Using Function
- Print Hello World 5 Times Using A For Loop
- Conclusion
- Frequently Asked Questions
- 👋 Python's 'Hello, World!'—How Well Do You Know It?
Table of content:
- Algorithm Of Python Program To Add To Numbers
- Standard Program To Add Two Numbers In Python
- Python Program To Add Two Numbers With User-defined Input
- The add() Method In Python Program To Add Two Numbers
- Python Program To Add Two Numbers Using Lambda
- Python Program To Add Two Numbers Using Function
- Python Program To Add Two Numbers Using Recursion
- Python Program To Add Two Numbers Using Class
- How To Add Multiple Numbers In Python?
- Add Multiple Numbers In Python With User Input
- Time Complexities Of Python Programs To Add Two Numbers
- Conclusion
- Frequently Asked Questions
- 💡 Quiz Time: Python Addition Basics!
Table of content:
- Swapping in Python
- Swapping Two Variables Using A Temporary Variable
- Swapping Two Variables Using The Comma Operator In Python
- Swapping Two Variables Using The Arithmetic Operators (+,-)
- Swapping Two Variables Using The Arithmetic Operators (*,/)
- Swapping Two Variables Using The XOR(^) Operator
- Swapping Two Variables Using Bitwise Addition and Subtraction
- Swap Variables In A List
- Conclusion
- Frequently Asked Questions (FAQs)
- Quiz To Test Your Variable Swapping Knowledge
Table of content:
- What Is A Quadratic Equation? How To Solve It?
- How To Write A Python Program To Solve Quadratic Equations?
- Python Program To Solve Quadratic Equations Directly Using The Formula
- Python Program To Solve Quadratic Equations Using The Complex Math Module
- Python Program To Solve Quadratic Equations Using Functions
- Python Program To Solve Quadratic Equations & Find Number Of Solutions
- Python Program To Plot Quadratic Functions
- Conclusion
- Frequently Asked Questions
- Quadratic Equations In Python Quiz: Test Your Knowledge!
Table of content:
- What Is Decimal Number System?
- What Is Binary Number System?
- What Is Octal Number System?
- What Is Hexadecimal Number System?
- Python Program to Convert Decimal to Binary, Octal, And Hexadecimal Using Built-In Function
- Python Program To Convert Decimal To Binary Using Recursion
- Python Program To Convert Decimal To Octal Using Recursion
- Python Program To Convert Decimal To Hexadecimal Using Recursion
- Python Program To Convert Decimal To Binary Using While Loop
- Python Program To Convert Decimal To Octal Using While Loop
- Python Program To Convert Decimal To Hexadecimal Using While Loop
- Convert Decimal To Binary, Octal, And Hexadecimal Using String Formatting
- Python Program To Convert Binary, Octal, And Hexadecimal String To A Number
- Complexity Comparison Of Python Programs To Convert Decimal To Binary, Octal, And Hexadecimal
- Conclusion
- Frequently Asked Questions
- 💡 Decimal To Binary, Octal & Hex: Quiz Time!
Table of content:
- What Is A Square Root?
- Python Program To Find The Square Root Of A Number
- The pow() Function In Python Program To Find The Square Root Of Given Number
- Python Program To Find Square Root Using The sqrt() Function
- The cmath Module & Python Program To Find The Square Root Of A Number
- Python Program To Find Square Root Using The Exponent Operator (**)
- Python Program To Find Square Root With A User-Defined Function
- Python Program To Find Square Root Using A Class
- Python Program To Find Square Root Using Binary Search
- Python Program To Find Square Root Using NumPy Module
- Conclusion
- Frequently Asked Questions
- 🤓 Think You Know Square Roots In Python? Take A Quiz!
Table of content:
- Understanding the Logic Behind the Conversion of Kilometers to Miles
- Steps To Write Python Program To Convert Kilometers To Miles
- Python Program To Convert Kilometer To Miles Without Function
- Python Program To Convert Kilometer To Miles Using Function
- Python Program to Convert Kilometer To Miles Using Class
- Tips For Writing Python Program To Convert Kilometer To Miles
- Conclusion
- Frequently Asked Questions
- 🧐 Mastered Kilometer To Mile Conversion? Prove It!
Table of content:
- Why Build A Calculator Program In Python?
- Prerequisites To Writing A Calculator Program In Python
- Approach For Writing A Calculator Program In Python
- Simple Calculator Program In Python
- Calculator Program In Python Using Functions
- Creating GUI Calculator Program In Python Using Tkinter
- Conclusion
- Frequently Asked Questions
- 🧮 Calculator Program In Python Quiz!
Table of content:
- The Calendar Module In Python
- Prerequisites For Writing A Calendar Program In Python
- How To Write And Print A Calendar Program In Python
- Calendar Program In Python To Display A Month
- Calendar Program In Python To Display A Year
- Conclusion
- Frequently Asked Questions
- Calendar Program In Python – Quiz Time!
Table of content:
- What Is The Fibonacci Series?
- Pseudocode Code For Fibonacci Series Program In Python
- Generating Fibonacci Series In Python Using Naive Approach (While Loop)
- Fibonacci Series Program In Python Using The Direct Formula
- How To Generate Fibonacci Series In Python Using Recursion?
- Generating Fibonacci Series In Python With Dynamic Programming
- Fibonacci Series Program In Python Using For Loop
- Generating Fibonacci Series In Python Using If-Else Statement
- Generating Fibonacci Series In Python Using Arrays
- Generating Fibonacci Series In Python Using Cache
- Generating Fibonacci Series In Python Using Backtracking
- Fibonacci Series In Python Using Power Of Matix
- Complexity Analysis For Fibonacci Series Programs In Python
- Applications Of Fibonacci Series In Python & Programming
- Conclusion
- Frequently Asked Questions
- 🤔 Think You Know Fibonacci Series? Take A Quiz!
Table of content:
- Different Ways To Write Random Number Generator Python Programs
- Random Module To Write Random Number Generator Python Programs
- The Numpy Module To Write Random Number Generator Python Programs
- The Secrets Module To Write Random Number Generator Python Programs
- Understanding Randomness and Pseudo-Randomness In Python
- Common Issues and Solutions in Random Number Generation
- Applications of Random Number Generator Python
- Conclusion
- Frequently Asked Questions
- Think You Know Python's Random Module? Prove It!
Table of content:
- What Is A Factorial?
- Algorithm Of Program To Find Factorial Of A Number In Python
- Pseudocode For Factorial Program in Python
- Factorial Program In Python Using For Loop
- Factorial Program In Python Using Recursion
- Factorial Program In Python Using While Loop
- Factorial Program In Python Using If-Else Statement
- The math Module | Factorial Program In Python Using Built-In Factorial() Function
- Python Program to Find Factorial of a Number Using Ternary Operator(One Line Solution)
- Python Program For Factorial Using Prime Factorization Method
- NumPy Module | Factorial Program In Python Using numpy.prod() Function
- Complexity Analysis Of Factorial Programs In Python
- Conclusion
- Frequently Asked Questions
- Think You Know Factorials In Python? Take A Quiz!
Table of content:
- What Is Palindrome In Python?
- Check Palindrome In Python Using While Loop (Iterative Approach)
- Check Palindrome In Python Using For Loop And Character Matching
- Check Palindrome In Python Using The Reverse And Compare Method (Python Slicing)
- Check Palindrome In Python Using The In-built reversed() And join() Methods
- Check Palindrome In Python Using Recursion Method
- Check Palindrome In Python Using Flag
- Check Palindrome In Python Using One Extra Variable
- Check Palindrome In Python By Building Reverse, One Character At A Time
- Complexity Analysis For Palindrome Programs In Python
- Real-World Applications Of Palindrome In Python
- Conclusion
- Frequently Asked Questions
- Think You Know Palindromes? Take A Quiz!
Table of content:
- Best Python Books For Beginners
- Best Python Books For Intermediate Level
- Best Python Books For Experts
- Best Python Books To Learn Algorithms
- Audiobooks of Python
- Best Books To Learn Python And Code Like A Pro
- To Learn Python Libraries
- Books To Provide Extra Edge In Python
- Python Project Ideas - Reference
- Quiz To Rehash Your Knowledge Of Python Books!
Python Program To Convert Decimal To Binary, Octal And Hexadecimal

Decimal, binary, octal, and hexadecimal are different ways to represent numbers, making them an integral part of the number system/ digital system. They are used in computing to represent numeric values. While decimal is the base-10 numeral system we're most familiar with (0-9), binary is base-2 (0-1), octal is base-8 (0-7), and hexadecimal is base-16 (0-9, A-F). In this article, we'll explore various techniques for writing a Python program to convert decimal to binary, octal, and hexadecimal. But first, let's look at a few basics.
What Is Decimal Number System?
The decimal number system has a base of 10, and it contains 10 digits from 0 to 9. That is, these digits are used to represent numbers in this number system. Each digit in a decimal number has a value according to its position. Every subsequent digit is 10 times greater than the previous digit while moving from right to left. For example, (257)10 is represented as:
(257)10 = 102 .2 + 101 .5 + 100 .7 = 200 + 50 + 7 = 257
What Is Binary Number System?
The binary number system has a base 2, and it contains only two digits, i.e., 0 and 1. These two digits are known as bits. The group of 4 bits is called a nibble, and the group of 8 bits is called a byte. For example, (1011)2 is represented in decimal as:
(1011)2 = 23 .1 + 22 .0 + 21 .1 + 20 .1 = 8 + 0 + 2 + 1 = (11)10
The process to convert decimal to binary is as follows (example 8):
Divide the decimal number by 2 |
0 |
Use the quotient obtained in the previous step as a dividend and divide by 2 |
0 |
Repeat the second step until the quotient becomes 0 |
0 |
1/2 = 0 |
1 |
Write the remainder in reverse chronological order (bottom to top) |
|
What Is Octal Number System?
The octal number system has a base 8, and it contains 8 digits from 0 to 7. In the octal number system, each place is a power of 8. For example, (713)8 is represented in decimal as:
(713)8 = 82 .7 + 81 .1 + 80 .3 = 448 + 8 + 3 = (459)10
The steps to convert decimal to octal are as follows (example 356):
Divide the decimal number by 8 |
4 |
Use the quotient obtained in the previous step as a dividend and repeat |
4 |
Repeat the second step until the quotient becomes 0 |
5 |
Write the remainder in reverse chronological order (bottom to top) |
|
What Is Hexadecimal Number System?
The hexadecimal is an alphanumeric number system that has base 16, and it contains 10 digits from 0 to 9 and 6 alphabets from A to F. Here, the alphabets A to F represent the values from 10 to 15, where A represents 10, B represents 11 and so on. For example, (13B)16 is represented in decimal as:
(13B)16 = 162 .1 + 161 .3 + 160 .B = 144 + 48 + 11 = (203)10
The steps to convert decimal to hexadecimal numbers are given below (example 974).
Divide the decimal number by 16 |
14 (=E) (Remainder) |
Use the quotient obtained in the previous step as a dividend and continue dividing by 16 until the quotient becomes 0. |
6 |
Write remainders in reverse chronological order (bottom to top) |
|
Python Program to Convert Decimal to Binary, Octal, And Hexadecimal Using Built-In Function
We can create a Python program to convert decimal to binary, octal, and hexadecimal by using built-in functions provided in Python. The built-in functions used for this purpose are (where n is the decimal number we want to convert):
- bin(): This function converts a decimal number to its equivalent binary number.
- oct(): This function converts a decimal number to its equivalent octal number.
- hex(): This function converts a decimal number to its equivalent hexadecimal number.
The approach for this conversion is as follows:
- First of all, we start by taking a decimal number as input from the user and storing it in a variable number.
- Then, we convert num into its equivalent binary number by passing num as a parameter of the built-in function bin(). We print the obtained binary number as output.
- After that, we pass num as a parameter in the built-in function oct() to convert num into an octal number and print it as output.
- Again, we pass num as a parameter in the built-in function hex() to obtain a hexadecimal representation of num and print it on the screen.
In this way, we can convert decimal to other number formats using built-in functions. Below is a simple Python program to convert decimal to binary, octal, and hexadecimal.
Code Example:
# Input a decimal number
x = int(input("Enter a number: "))
# Convert the decimal number to binary, octal, and hexadecimal
binary_representation = bin(x)
octal_representation = oct(x)
hexadecimal_representation = hex(x)
# Print the original decimal number and its representations
print("The decimal number:", x)
print("The binary representation:", binary_representation)
print("The octal representation:", octal_representation)
print("The hexadecimal representation:", hexadecimal_representation)
Output:
Enter a number: 46
The decimal number: 46
The binary representation: 0b101110
The octal representation: 0o56
The hexadecimal representation: 0x2e
Explanation:
In the Python code example-
- We create a variable x and prompt the user to input a decimal number using the input() function, which we then convert to integer data type using int() function.
- Next, we utilize built-in Python functions bin(), oct(), and hex() to convert the decimal number x into its binary, octal, and hexadecimal representations, respectively.
- The binary representation of x is stored in the variable binary_representation.
- The octal representation of x is stored in the variable octal_representation.
- The hexadecimal representation of x is stored in the variable hexadecimal_representation.
- Finally, we print the original decimal number x, along with its binary, octal, and hexadecimal representations, using a set of print() statements.
Time Complexity: O(1)
Space Complexity: O(1)
Python Program To Convert Decimal To Binary Using Recursion
A function that repeatedly calls itself is called recursion or recursive function. In recursion, the function breaks the original problem into smaller subproblems and solves those subproblems until the base case is reached. Then, the recursion returns its result without further calling itself.
A decimal number can be converted to a binary number by using recursion. The steps for this approach are as follows:
- Firstly, define a function conversion(), which takes a decimal number n as an argument.
- Then, define the condition that if n is greater than 1, then apply recursion. Within this, call the conversion() function and pass the floor division of n by 2, which provides an integer quotient as an argument.
- After the if condition is executed, print the remainder of the division of n by 2. By this, the binary digits will be printed in reverse order due to the recursive call.
Syntax:
def conversion(n):
if n > 1:
conversion(n//2)
print(n % 2,end = '')
Here,
- conversion(): Function to convert decimal to binary
- n: Decimal number to be converted to binary
- print(): Function to print the binary digits
Look at the Python program example to convert decimal to binary given below, for a better understanding of how to use this approach.
Code Example:
#Define function convertTobinary()
def convertToBinary(n):
if n > 1: #If condition
convertToBinary(n//2) #Recursive call
print(n % 2,end = '') #Print remainder of n/2
#Creating a variable and asking for user input
x = int(input("Enter a number: "))
#Calling the custom function to convert the number
convertToBinary(x)
#Printing the converted equivalent
print()
Output:
Enter a number: 13
1101
Explanation:
In the sample Python code-
- We begin by defining a function convertToBinary() that takes an integer n as input.
- Inside the function, there's a recursive call to convertToBinary(n // 2) to convert the quotient of n divided by 2 recursively to binary.
- We use an if-statement for the base case to check if n is less than or equal to 1. If the condition is true, then the recursion stops.
- If the condition is false, we move forward with recursion, during which the remainder of the divisions are printed in reverse order to get the binary representation. (We use the modulo arithmetic operator here)
- The end='' parameter in print() ensures that the output is printed without a newline character.
- Outside the function, we prompt the user to input a decimal number using input(), convert it to an integer and store it in the variable x.
- Next, we call the convertToBinary() function to convert the decimal number x to binary.
- Finally, we print a newline character to ensure subsequent output appears on a new line.
Time Complexity: O(log n)
Space Complexity: O(log n)
Python Program To Convert Decimal To Octal Using Recursion
The decimal number can be converted to an octal number with the help of recursion. To achieve this, the decimal number is divided by 8, and the remainder obtained is stored temporarily. This step is followed until the number becomes 0. After that, the remainders obtained throughout the process are combined in reverse order to get the desired octal number.
Syntax:
def conversion(n):
if n>0:
conversion(n//8)
print(n%8, end='')
Here,
- conversion(): Function to convert decimal to octal
- n: Decimal number to be converted to octal
- print(): Function to print the octal digits
Look at the sample Python program to convert decimal to octal below, to understand how we can use recursion.
Code Example:
#Defining a function to convert decimal to octal
def convertToOct(n):
if n > 0: #If condition or base case
convertToOct(n // 8) #Recursive call
print(n % 8, end='') #Print remainder of n/8
#Input a number
x = int(input("Enter a decimal number: "))Â
#Invoke convertToOct()
convertToOct(x)Â
print()
Output:
Enter a decimal number: 34
042
Explanation:
In the example Python code-
- We define a function convertToOct(), which takes a decimal number and converts it to its octal representation.
- Inside the function, there's a recursive call to convertToOct(n // 8), which recursively divides n by 8 to convert the quotient to octal.
- The base case is when n becomes less than or equal to 0, terminating the recursion.
- During the recursion, the remainders of the divisions by 8 are printed in reverse order to obtain the octal representation.
- The end='' parameter in print() ensures that the output is printed without a newline character.
- Outside the function, we prompt the user to input a decimal number using input(), and convert it and store it in variable x.
- After that, we call the convertToOct() function by passing variable x to it as an argument. The function converts x to an octal representation and prints the same.
- Finally, we print a newline character to ensure subsequent output appears on a new line.
Time Complexity: O(log n)
Space Complexity: O(log n)
Python Program To Convert Decimal To Hexadecimal Using Recursion
To convert a decimal number to hexadecimal using the recursive approach, we must divide the input decimal value by 16 and temporarily store the remainder obtained. This step is followed until the number becomes 0. After that, the remainders obtained throughout the process are combined in reverse order to get the desired hexadecimal number.
Syntax:
conversion_table = {0: '0', 1: '1', 2: '2', 3: '3',
4: '4', 5: '5', 6: '6', 7: '7',
8: '8', 9: '9', 10: 'A', 11: 'B',
12: 'C', 13: 'D', 14: 'E', 15: 'F'}def conversion(n):
if(n <= 0):
return ''
r = n % 16
return conversion(n//16) + conversion_table[r]
Here,
- conversion_table: Dictionary that maps decimal values to hexadecimal values
- conversion(): Function to convert decimal to hexadecimal
- n: Decimal number to be converted to hexadecimal
Look at the example Python program to convert decimal to hexadecimal using the recursive approach.
Code Example:
# Dictionary to map decimal values to hexadecimal digits
conversion_table = {
0: '0', 1: '1', 2: '2', 3: '3',
4: '4', 5: '5', 6: '6', 7: '7',
8: '8', 9: '9', 10: 'A', 11: 'B',
12: 'C', 13: 'D', 14: 'E', 15: 'F'
}
# Recursive function to convert decimal to hexadecimal
def convertToHex(n):
if n <= 0: # Base case: if n is less than or equal to 0
return '' # Return an empty string
else:
remainder = n % 16 # Calculate the remainder when n is divided by 16
return convertToHex(n // 16) + conversion_table[remainder] # Recursive call
# Input a number from the user
x = int(input("Enter a number: "))
# Call convertToHex() function and print the result
print("Hexadecimal representation:", convertToHex(x))
Output:
Enter a number: 48
Hexadecimal representation: 30
Explanation:
In the Python code sample-
- We define a dictionary conversion_table, which maps decimal values to their corresponding hexadecimal digits.
- Next, the convertToHex() function is defined to convert a decimal number to its hexadecimal representation.
- Inside the function, there's a recursive call to convertToHex(n // 16), which recursively divides n by 16 to convert the quotient to hexadecimal.
- The base case is when n becomes less than or equal to 0, terminating the recursion. In this case, an empty string is returned.
- During the recursion, the remainder of n divided by 16 is calculated, and the corresponding hexadecimal digit is retrieved from the conversion_table.
- The result of the recursive call concatenated with the hexadecimal digit is returned.
- Outside the function, we prompt the user to input a decimal number using input() and convert it to an integer variable x.
- We call the convertToHex() function to convert the decimal number x to hexadecimal.
Finally, we print the hexadecimal representation obtained from the function call.
Time Complexity: O(log n)
Space Complexity: O(log n)
Python Program To Convert Decimal To Binary Using While Loop
The decimal number can be converted into its equivalent binary number using a while loop. In this, we divide the decimal number by 2 until the number becomes zero. Then, we combine the remainder of these divisions in a bottom-up manner to get the resultant binary number.
The procedure to use a while loop in a Python program to convert decimal to binary is as follows:
- Take a decimal number as input n and initialize a variable binary, in which the resultant binary number will be stored as 0.
- Initialize variable i to 1 and variable r, which is used to store the current remainder, as 0.
- Then, apply a while loop with the condition that n does not equal 0. This loop will run till n is not equal to 0.
- After that, we divide n by 2, and store the remainder in r and then update n to the integer quotient of n/2.
- Update the variable binary by multiplying r with i and then add this result to the binary.
- After that, update i by multiplying it with 10. Here, i will be working as a variable to ensure the correct position of the digits.
- At the end, when the while loop terminates, print the resultant binary number.
Code Example:
def convertBinary(n):
binary = 0 # Initialize binary representation to 0
i = 1 # Initialize multiplier to 1
while n != 0: # Loop until n becomes 0
r = n % 2 # Calculate remainder when n is divided by 2
n = n // 2 # Update n to the integer quotient of n divided by 2
binary += r * i # Add current binary digit to the binary representation
i *= 10 # Move to the next position in the binary representation
return binary # Return the binary representation
# Prompt the user to enter a number
x = int(input("Enter a number: "))
# Call the convertBinary function and print the result
print("Binary representation:", convertBinary(x))
Output:
Enter a number: 67
Binary representation: 1000011
Explanation:
In the Python code-
- We define the function convertBinary(n) to convert a decimal number to its binary representation.
- Inside the function, we initialize a variable binary to 0, which will store the binary representation, and variable i to 1, which is used as a multiplier to place binary digits correctly.
- We then enter a while loop that continues until n becomes 0. Inside the loop:
- We calculate the remainder r when n is divided by 2, representing the current binary digit.
- We update n to the integer quotient of n divided by 2, effectively shifting the binary digits to the right.
- We add the current binary digit multiplied by the multiplier i to binary, effectively adding the binary digit to the binary representation.
- We multiply i by 10 to move to the next position in the binary representation.
- Once the loop terminates, the function returns the binary representation stored in the variable binary.
- Outside the function, we prompt the user to input a decimal number using input() and convert it to an integer variable x.
- We then pass this variable to call the convertBinary() function to convert the decimal number x to binary.
- Finally, we print the binary representation obtained from the function call using a print() statement with a string message.
Time Complexity: O(log n)
Space Complexity: O(1)
Python Program To Convert Decimal To Octal Using While Loop
The decimal number can be converted into its equivalent octal number using a while loop. In this, we divide the decimal number by 8 until the number becomes zero. Then, we combine the remainder of these divisions in a bottom-up manner to get the resultant octal number. The Python program sample below provides an implementation of the same.
Code Example:
def convertOctal(n):
octal = 0 # Initialize octal representation to 0
i = 1 # Initialize multiplier to 1
while n != 0: # Loop until n becomes 0
r = n % 8 # Calculate remainder when n is divided by 8
n = n // 8 # Update n to the integer quotient of n divided by 8
octal += r * i # Add current octal digit to the octal representation
i *= 10 # Move to the next position in the octal representation
return octal # Return the octal representation
# Prompt the user to enter a number
x = int(input("Enter a number: "))
# Call the convertOctal function and print the result
print("Octal representation:", convertOctal(x))
Output:
Enter a number: 67
Octal representation: 103
Explanation:
In the code-
- We define the function convertOctal(n) to convert a decimal number to its octal representation.
- Inside the function, we initialize variable octal to 0, which will store the octal representation, and variable i to 1, which is used as a multiplier to place octal digits correctly.
- We enter a while loop that continues until n becomes 0. Inside the loop:
- We calculate the remainder r when n is divided by 8, representing the current octal digit.
- We update n to the integer quotient of n divided by 8, effectively shifting the octal digits to the right.
- We add the current octal digit multiplied by the multiplier i to octal, effectively adding the octal digit to the octal representation.
- We multiply i by 10 to move to the next position in the octal representation.
- Once the loop terminates, we return the octal representation stored in the variable octal.
- Outside the function, we prompt the user to input a decimal number using input() and convert it to an integer variable x.
- We call the convertOctal(x) function to convert the decimal number x to octal.
- Finally, we print the octal representation obtained from the function call using the print() function.
Time Complexity: O(log n)
Space Complexity: O(1)
Python Program To Convert Decimal To Hexadecimal Using While Loop
The decimal number can be converted into its equivalent hexadecimal number using a while loop. In this, we divide the decimal number by 16 until the number becomes zero. Then, we combine the remainder of these divisions in a bottom-up manner to get the resultant hexadecimal number.
Code Example:
def convertHexadecimal(n):
hexadecimal = "" # Initialize hexadecimal representation to an empty string
hex_digits = "0123456789ABCDEF" # Define a string containing all hexadecimal digits
r = 0 # Initialize remainder to 0
while n > 0: # Loop until n becomes 0
r = n % 16 # Calculate remainder when n is divided by 16
n = n // 16 # Update n to the integer quotient of n divided by 16
hexadecimal += hex_digits[r] # Concatenate the hexadecimal digit corresponding to r
# position from hex_digits to hexadecimal
return hexadecimal[::-1] # Reverse the hexadecimal representation and return
# Prompt the user to enter a number
x = int(input("Enter a number: "))
# Call the convertHexadecimal function and print the result
print("Hexadecimal representation:", convertHexadecimal(x))
Output:
Enter a number: 58
Hexadecimal representation: 3A
Explanation:
In the above code,
- We define the function convertHexadecimal() to convert a decimal number to its hexadecimal representation.
- Inside the function, we initialize a variable hexadecimal to an empty string, which will store the hexadecimal representation.
- After that, we define a string variable hex_digits containing all hexadecimal digits for later reference and initialize variable r to 0, which will store the remainder when n is divided by 16.
- Next, we enter a while loop that continues until n becomes 0. Inside the loop:
- We calculate the remainder r when n is divided by 16, representing the current hexadecimal digit.
- Then, we update n to the integer quotient of n divided by 16, effectively shifting the hexadecimal digits to the right.
- Next, we concatenate the hexadecimal digit corresponding to r position from hex_digits to hexadecimal.
- Once the loop terminates, we reverse the hexadecimal representation using [::-1] and return it.
- Outside the function, we prompt the user to input a decimal number using input() and convert it to an integer variable x.
- We call the convertHexadecimal(x) function to convert the decimal number x to hexadecimal.
- Finally, we print the hexadecimal representation obtained from the function call.
Time Complexity: O(log n)
Space Complexity: O(1)
Convert Decimal To Binary, Octal, And Hexadecimal Using String Formatting
The decimal number can be converted into other bases like binary, octal, and hexadecimal using string formatting. It can be accomplished using format() method, str.format() method, and f-strings. We will discuss each of these methods of writing a Python program to convert decimal to binary, octal, and hexadecimal in detail below.
Python Program Convert Decimal To Binary, Octal, And Hexadecimal Using Format() Method
The format() function is used to perform string formatting in order to convert decimals to other bases, and different format specifiers are used for different bases. The approach for this procedure can be described as:
- Take a decimal number n as user input.
- Then, we apply the format() function by passing n and the format specifier as argument.
- Store the result of the function in a variable and then print the value.
Syntax:
new_num = format(decimal, 'f')
Here,
- new_num: Resultant new number after string formatting.
- format(): Function to perform string formatting.
- decimal: Decimal number you want to convert.
- f: Format specifier for the desired base like b for binary, o for octal and x for hexadecimal.
Code Example:
#Define convertToBases() function
def convertToBases(n):
binary = format(n, 'b') #string formatting for converting into binary number
octal = format(n, 'o') #string formatting for converting into octal number
hexadecimal = format(n, 'x') #string formatting for converting into hexadecimal number
print(n,"in binary: ",binary)#Print value of binary
print(n,"in octal: ",octal) #Print value of octal
print(n,"in hexadecimal: ",hexadecimal) #Print value of hexadecimal
#Input a number
x = int(input("Enter a number: "))Â
#Call convertToBases() function
convertToBases(x)Â
Output:
Enter a number: 562
562 in binary: 1000110010
562 in octal: 1062
562 in hexadecimal: 232
Explanation:
In the Python code-
- We define the function convertToBases(), which takes an input decimal number n and converts it to its binary, octal, and hexadecimal representations simultaneously.
- Inside the function, we use string formatting with the format() method (format(n, 'b'), format(n, 'o'), format(n, 'x')) to convert the decimal number n into its binary, octal, and hexadecimal representations respectively.
- In the format() function, the second argument indicates the number system/ format we want to convert to, i.e., b stands for binary, o for octal, and x for hexadecimal.
- We then use a series of print() statements to display the original decimal number n along with its binary, octal, and hexadecimal representations.
- Outside the function, we declare a variable x, prompt the user to input a decimal number using input() and convert it to an integer to store in x using the int() function.
- After that, we call the convertToBases() function by passing x as an argument. It converts the input number from decimal to binary, octal, and hexadecimal and prints the respective value to the console.
Time Complexity: O(1)
Space Complexity: O(1)
Python Program Convert Decimal To Binary, Octal, And Hexadecimal Using Str.format() Method
The str.format() function is another method to perform string formatting in order to convert numbers from decimal to other bases. We use different format specifiers for different bases inside the strings. The approach for this procedure can be described as:
- Take a decimal number n as user input.
- Then, apply the str.format() function by passing n as an argument and specify the format specifier for the desired base in the string placeholder.
- Store the result of the function in a variable and then print the value.
Syntax:
new_num = "{0:f}".format(decimal)
Here,
- new_num: Resultant new number after string formatting.
- "{0:f}": It is the string placeholder where 0 is the positional argument and f is the format specifier for the desired base. For example, b is for binary, o is for octal, and x is for hexadecimal.
- format(): Function to perform string formatting.
- decimal: Decimal number you want to convert.
Code Example:
#Define convertToBases() function
def convertToBases(n):
binary = "{0:b}".format(n) #string formatting for converting into binary number
octal = "{0:o}".format(n) #string formatting for converting into octal number
hexadecimal = "{0:x}".format(n) #string formatting for converting into hexadecimal number
print(n,"in binary: ",binary)#Print value of binary
print(n,"in octal: ",octal) #Print value of octal
print(n,"in hexadecimal: ",hexadecimal) #Print value of hexadecimal
#Input a number
x = int(input("Enter a number: "))Â
#Call convertToBases() function
convertToBases(x)Â
Output:
Enter a number: 83
83 in binary: 1010011
83 in octal: 123
83 in hexadecimal: 53
Explanation:
In the above code-
- We define the convertToBases() function, which takes a decimal input and converts it to binary, octal, and hexadecimal representations simultaneously.
- Inside the function, we use string formatting with the .format() method ("{0:b}".format(n), "{0:o}".format(n), "{0:x}".format(n)) to convert the decimal number n into its binary, octal, and hexadecimal representations respectively.
- In the format strings, {0:b}, {0:o}, and {0:x} indicate that n should be formatted as binary, octal, and hexadecimal, respectively.
- Then, we use the print() function to display the original decimal number n along with its binary, octal, and hexadecimal representations.
- Outside the function, we prompt the user to input a decimal number using input() and convert it to an integer x.
- We call the convertToBases(x) function to convert the decimal number x to binary, octal, and hexadecimal.
- Finally, the function calculates and prints the representations obtained from the string formatting.
Time Complexity: O(1)
Space Complexity: O(1)
Python Program Convert Decimal To Binary, Octal, And Hexadecimal Using F-strings
The f-strings are also used to perform string formatting in order to convert numbers from decimal to other bases. The approach for this procedure can be described as:
- Take a decimal number n as user input.
- Then, create f-string by passing n and the format specifier in the string placeholder.
- Store the resultant string in a variable and then print the value.
Syntax:
new_num = f"{decimal:format_specifier}"
Here,
- new_num: Resultant new number after string formatting.
- f: Representation of f-string.
- "{decimal:format_specifier}": String placeholder where the decimal is the number you want to convert and format_specifier is the format specifier for the targeted base like b for binary, o for octal and x for hexadecimal.
Code Example:
#Define convertToBases() function
def convertToBases(n):Â
binary = f"{n:b}" #f-string for converting into binary number
octal = f"{n:o}" #f-string for converting into octal number
hexadecimal = f"{n:x}" #f-string for converting into hexadecimal number
print(n,"in binary: ",binary)#Print value of binary
print(n,"in octal: ",octal) #Print value of octal
print(n,"in hexadecimal: ",hexadecimal) #Print value of hexadecimal
#Input a number
x = int(input("Enter a number: "))Â
#Call convertToBases() function
convertToBases(x)Â
Output:
Enter a number: 35
35 in binary: 100011
35 in octal: 43
35 in hexadecimal: 23
Explanation:
In this example Python code-
- We define the function convertToBases() to convert a decimal number to its binary, octal, and hexadecimal representations simultaneously.
- Inside the function, we use f-strings (f"{n:b}", f"{n:o}", f"{n:x}") to directly convert the decimal number n into its binary, octal, and hexadecimal representations respectively.
- These f-strings format the integer n into a string representation using the specified base (binary, octal, hexadecimal).
- We print the original decimal number n along with its binary, octal, and hexadecimal representations using print() function.
- Outside the function, we prompt the user to input a decimal number using input() and convert it to an integer x.
- We call the convertToBases(x) function to convert the decimal number x to binary, octal, and hexadecimal.
- The invoked function converts and prints the representations obtained from the f-strings.
Time Complexity: O(1)
Space Complexity: O(1)
Python Program To Convert Binary, Octal, And Hexadecimal String To A Number
Now, we will discuss how to convert a given binary, octal, or hexadecimal string to a number. The function used for this purpose is the int() function. It is a built-in function that takes a string and a base as an argument to convert the string into an integer.
The default value of base is 10, i.e., decimal. If the base is set to 0, then the base is decided according to the prefix of the string. For example, the 0b prefix is for binary, 0o for octal and 0x for hexadecimal. We can also use capital letters in prefixes.
Syntax:
int('0pXX', 0)
OR
int('XX', b)
Here,
- int(): Function to convert a binary, octal and hexadecimal string to a number.
- 0p: Prefix to identify the base of the number.
- XX: Numerical value in the string.
- b: Base of numerical string.
Code Example:
#Initializing string variables
binary_str = '1010'
octal_str = '35'
hexadecimal_str = '5C'
# Convert binary string to decimal
binary_to_decimal = int(binary_str, 2)
# Convert octal string to decimal
octal_to_decimal = int(octal_str, 8)
# Convert hexadecimal string to decimal
hexadecimal_to_decimal = int(hexadecimal_str, 16)
print("Binary to Decimal:", binary_to_decimal)
print("Octal to Decimal:", octal_to_decimal)
print("Hexadecimal to Decimal:", hexadecimal_to_decimal)
Output:
Binary to Decimal: 10
Octal to Decimal: 29
Hexadecimal to Decimal: 92
Explanation:
In the above code,
- We begin by assigning string values to three variables, i.e., binary_str, octal_str, and hexadeciaml_str.
- We then use the int() function to convert these values to decimal representations. Within the function the second argument represents the base of the number represented by the string.
- Here, int(binary_str, 2) function, where binary_str is the binary string and 2 indicates the base of the number system (binary). It converts the binary string to its equivalent decimal value.
- Similarly, we employ the int(octal_str, 8) function, where octal_str is the octal string, and 8 denotes the base of the number system (octal). This converts the octal string to its equivalent decimal value.
- The int(hexadecimal_str, 16) function, where hexadecimal_str is the hexadecimal string, and 16 signifies the base of the number system (hexadecimal). It converts the hexadecimal string to its equivalent decimal value.
- Finally, we print the converted decimal values using print() function, along with appropriate labels for clarity.
Time Complexity: O(n)
Space Complexity: O(1)
Complexity Comparison Of Python Programs To Convert Decimal To Binary, Octal, And Hexadecimal
The comparison table provided below comprises the time and space complexities of all the methods used to convert decimals to other bases.
Method Name |
Time Complexity |
Space Complexity |
Using in-built function |
O(1) |
O(1) |
Using recursion |
O(log n) |
O(log n) |
Using while loop |
O(log n) |
O(1) |
Using string formatting |
O(1) |
O(1) |
Conclusion
The ability to convert numbers from decimal and other number systems/ bases is a valuable skill in your programming toolkit. In this article, we have explored various methods to write a Python program to convert decimal to binary, octal, and hexadecimal. These methods include using inbuilt functions (bin(), oct(), hex()), recursion, string formatting, and manual calculation with while loops.
Python's built-in functions provide simplicity and efficiency, while manual calculation offers insight into number systems. Mastering these conversion methods equips programmers with versatile skills for working with different data formats, enhancing their proficiency in Python programming and computer science applications.
Frequently Asked Questions
Q. Why do we need to convert decimal numbers to binary, octal, or hexadecimal?
Converting decimal numbers to other numeral systems is essential for various computing tasks, including low-level programming, bitwise operations, data representation, and cryptography. Different numeral systems offer advantages in different contexts, and understanding how to perform conversions provides flexibility in programming.
Q. What is the hexadecimal number system?
The hexadecimal number system is a number system with a base of 16. It contains 10 digits from 0 to 9 and 6 alphabets from A to F. Here, the alphabets A to F represent the values from 10 to 15, where A represents 10, B represents 11 and so on. Therefore, this number system is also called an alphanumeric number system.
For example, (13A)16 is represented in decimal as:
(13A)16 = 162 .1 + 161 .3 + 160 .A = 144 + 48 + 10 = (202)10
Q. What are the built-in functions available in Python for converting decimal numbers?
Python provides built-in functions bin(), oct(), and hex() for converting decimal numbers to binary, octal, and hexadecimal representations, respectively. These functions simplify the conversion process and are efficient for everyday programming tasks.
Q. Are there any limitations to using built-in functions for conversion?
While built-in functions like bin(), oct(), and hex() offer simplicity and efficiency, they may have limitations when dealing with large numbers or requiring specific formatting. In such cases, you must use manual conversion methods like using loops or custom formatting when writing a Python program to convert decimal to binary, octal, and hexadecimal.
Q. How to convert octal string to decimal in Python?
You can use the in-built int() function is used to convert from octal to decimal in Python. It takes a string and a base as an argument to convert the string into an integer. The default value of base is 10, i.e., decimal and is optional. However, since we are converting a string that represents an octal number, we must specify the base 8 as an argument and convert it to a corresponding decimal number. If the base is set to 0, then the base is decided according to the prefix of the string.
Code Example:
#Assign a string value to variable x
x = "67"Â
#Call int() function with x and base 8 as argument
y = int(x, 8)Â
#Print value of y
print(y)Â
Output:
55
Explanation:
- In this code, a variable x is assigned octal string 67.
- Then, the int() function is invoked with x as an argument and base as 8. This function converts x into a decimal number, and the result is stored in y.
- At last, y is printed as output.
Q. How can I handle errors or invalid inputs during conversion?
When converting decimal numbers to other bases, it's essential to handle errors or invalid inputs gracefully. You can use exception-handling techniques to catch and handle errors, such as ValueError for invalid inputs or OverflowError for large numbers. Additionally, validating inputs before the conversion can prevent unexpected behaviour and improve the robustness of your program.
💡 Decimal To Binary, Octal & Hex: Quiz Time!
We have discussed various ways you can write a Python program to convert decimal to binary, octal, and hexadecimal bases. Here are a few other topics you must know:
- Python For Loop | Syntax & Application (With Multiple Examples)
- Convert Int To String In Python | Learn 6 Methods With Examples
- How To Reverse A String In Python? 10 Easy Ways With Examples
- Swap Two Variables In Python- Different Ways | Codes + Explanation
- Python IDLE | The Ultimate Beginner's Guide With Images & Codes!
An economics graduate with a passion for storytelling, I thrive on crafting content that blends creativity with technical insight. At Unstop, I create in-depth, SEO-driven content that simplifies complex tech topics and covers a wide array of subjects, all designed to inform, engage, and inspire our readers. My goal is to empower others to truly #BeUnstoppable through content that resonates. When I’m not writing, you’ll find me immersed in art, food, or lost in a good book—constantly drawing inspiration from the world around me.
Comments
Add commentLogin to continue reading
And access exclusive content, personalized recommendations, and career-boosting opportunities.

Subscribe
to our newsletter
Ujjwal Sharma 1 day ago
Vishwajeet Singh 3 weeks ago
niyati m singh 3 weeks ago
Shradha Manure 3 weeks ago
Pardha Venkata Sai Patnam 3 weeks ago
PUJALA JYOTHIRMAYE 3 weeks ago