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 Built-in Functions | A Detailed Explanation (+Code Examples)

Functions are building blocks of a program. That is, they allow you to break a complеx program into small, mеaningful, and rеusablе blocks of codе. It only runs when it is called, can take arguments, and can return data as a result. There are two types of functions - built-in and user-defined functions.
In this article, we will discuss Python built-in functions, all its subdivisions, dеfinition, use-case, and modules in which they are present. You will get a list of all Python built-in functions with a description and code examples. So, let’s start by understanding what Python built-in functions are.
What Are Python Built-In Functions?
Built-in functions in Python arе prе-dеfinеd functions that are readily available and accеssiblе without rеquiring any import statеmеnts or additional sеtups.
- Thеsе functions arе part of thе Python standard library and offеr a widе rangе of functionalitiеs to perform various mathematical tasks.
- The Python built-in functions offer a sеt of opеrations to perform common tasks such as data manipulation, mathеmatical opеrations, string manipulation, and filе opеrations.
- In some cases, you might have to import specific modules or libraries to use the functions. We will discuss these in the respective sections below.
For example, the built-in library functions like len(), max(), min(), str(), etc. Let’s consider a few short examples illustrating the use of these built-in functions.
Code Example 1:
numbers = [7, 2, 9, 4, 5]
print(max(numbers)) # Output: 9
print(min(numbers)) # Output: 2
Here, max() and min() Functions:
- max() returns the maximum value in an iterable. (which is 9)
- min() returns the minimum value in an iterable. (which is 2)
Code Example 2:
my_list = [1, 2, 3, 4, 5]
#Checking the length of the list
print(len(my_list)) # Output: 5
Here, lеn() function rеturns thе lеngth of an objеct (numbеr of itеms in an itеrablе, lеngth of a string, еtc.), which is 5.
Now that you have a brief overview of what Python built-in functions are let’s move on to discussing each sub-division of built-in functions separately.
Mathematical Python Built-In Functions
Python language offers a robust set of built-in functions specifically to carry out mathematical operations. This makes it easier for the programmers to perform calculations in their code.
- These functions are a part of Python's core language and do not require any module to be imported. Common examples of this type of Python built-in functions are sum(), max(), min(), abs(), and pow()
- However, there is a built-in math module in the Python standard library that can be imported to utilise some additional functionalities/ utilities.
- This module provides a wide range of mathematical constants and functions that allow users to perform logarithmic, trigonometric, exponential, numeric, and hyperbolic functions from basic to advanced.
However, in this section, we will cover only the more commonly used mathematical Python built-in functions. Listed in the table below are some of these functions, with the syntax and a short description.
Function Name |
Syntax |
Description |
abs() |
abs(num) |
Returns the absolute value of a number num. |
max() |
max(iterable) |
Returns the largest of two or more arguments or the largest item in an iterable |
min() |
min(iterable) |
Returns the smallest of two or more arguments or the smallest item in an iterable |
pow() |
pow(x, y[, z]) |
Returns x to the power of y, optionally with a modulus z. |
sum() |
sum(iterable[, start]) |
Returns the aggregate of all elements in an iterable. Optionally, start can be provided as the initial value. |
divmod() |
divmod(a, b) |
Takes two numbers and returns a pair of numbers (a // b, a % b). |
round() |
round(number[, ndigits]) |
Rounds a number to a given precision in decimal digits. |
Note: In the above table, the square brackets [ ] denote an optional syntax argument.
Now, let’s discuss these Python built-in functions individually with the help of examples.
Python abs() Function
The abs() function is a built-in function that is always available to the Python interpreter. Meaning there is no need to import any module to use it.
- It takes a number as an argument and returns its absolute value (magnitude).
- We use this function in scenarios where the magnitude of a value is needed, such as distance calculations or error handling.
The simple Python program example below illustrates the use of this function to calculate the absolute difference between two numbers.
Code Example:
#Declaring and initializing two variables
x = 5
y = 12
#Using abs() to get the absolute value of the difference which is negative
difference = abs(x - y)
print("Difference:", difference)
Output:
Difference: 7
In the simple Python code example,
- We first declare two variables, x and y, and assign them values 5 and 12, respectively.
- Then, we pass the difference of two variables/ numbers, x and y (x-y = -7), as an argument in the abs() function.
- The function returns the absolute value (magnitude) of the difference, as seen in the output window.
Python max() Function
The max() function is a built-in function is always available to the Python interpreter and does not require you to import any module to use it.
- The Python built-in max() function returns the largest of two or more arguments or the largest item in an iterable.
- It is useful for finding the maximum value within a collection of numbers or determining the maximum among multiple values.
Look at the Python program example below, which illustrates how this function works.
Code Example:
#Creating a list
num = [3, 7, 1, 9, 4]
#Using max() function to find the maximum number in the list
max_value = max(num)
print("Maximum value:", max_value)
Output:
Maximum value: 9
In the Python code example, we first create a list called num, containing five integer values.
- Then, we pass the list of numbers to the max() function as an argument.
- The function finds the greatest value present in the list and stores it in the max_value variable.
- We then print the value using the print() function.
Python min() Function
This Python built-in function is also always available to the interpreter without the need to import any module.
- The min() function returns the smallest of two or more arguments or the smallest item in an iterable.
- It is commonly used to find the minimum value within a collection or identify the minimum among several values.
Code Example:
x = 10
y = 25
z = 18
min_value = min(x, y, z)
print("Minimum value:", min_value)
Output:
Minimum value: 10
In the example Python code, we create three integer variables: x, y, and z.
- Then, we call the min() function, passing these variables as arguments to determine the smallest value.
- The function finds the minimum value and stores it in the min_value object, which we then print to the console.
Python pow() Function
Another Python built-in function that is available for use without any module importation.
- The pow() function returns the value of x to the power of y, optionally with a modulus z.
- It is a versatile function used for exponentiation operations, including calculating squares, cubes, and modular exponentiation.
Code Example:
base = 2
exponent = 3
modulus = 5
result = pow(base, exponent, modulus)
print("Result of modular exponentiation:", result)
Output:
Result of modular exponentiation: 3
In the example Python program, we create three variables, base, exponent, and modulus, and assign them integer values.
- Note that here, we include the third variable, z = 5 (from syntax).
- Then, we pass the variables as arguments to the pow() function.
- The function calculates the exponent 23 and then performs the modulo (%) operation by the third variable.
- It returns the remainder after dividing the exponent 23 by 5, which is 3.
Note: Modulo (%) operation between two numbers a & b is the remainder when b divides a.
Python sum() Function
As the name suggests, this Python built-in function returns the aggregate of all elements in an iterable, such as a list, tuple, or set. It is convenient for calculating the total of numerical values within a collection. Consider the example to calculate the sum of numbers in a list.
Code Example:
numbers = [1, 2, 3, 4, 5]
#Using sum() to find the aggregate of all elements of a list
total = sum(numbers)
print("Total:", total)
Output:
Total: 15
In the sample Python program,
- We pass the list numbers to the sum() function as an argument.
- The function calculates the sum of all the numbers in the list and stores them in the total object.
- The outcome is 15, which we print to the console using the print() function.
Python round() Function
This Python built-in function, which is always available to the interpreter (without needing a specific module), rounds a number to a specified precision in terms of decimal places. This is especially useful in financial calculations or whenever you need controlled precision.
Code Example:
#Passing a decimal number and the number of decimal places we need to the round() function
result = round(3.14159, 2)
#Printing the output to the console
print(result)
Output:
3.14
In the sample Python code, we call the round() function, passing the numbers 3.14159 and 2 (to specify the decimal places to be rounded) as arguments. The function rounds the first argument and returns the value 3.14, which we print to the console.
Python divmod() Function
This Python built-in function is used when you need both the quotient and the remainder from dividing two numbers. The function is also always available to the Python interpreter and is more efficient than using the division and modulo operators separately.
Code Example:
#Passing two integer to divmod() function
result = divmod(10, 3)
print(result)
Output:
(3, 1)
In the Python example program,
- We pass two numbers, 10 and 3, to the divmod() function and store the outcome in the result variable.
- The function divides the number 10 by 3, then returns the quotient (3) and the remainder (1) in the form of a tuple (3, 1).
Next, we will discuss those mathematical Python built-in functions that can only be used after we have imported the in-built math module. Listed in the table below are all such functions, with a brief description and the syntax.
Method Name |
Syntax |
Description |
cos() |
math.cos(x) |
It returns the cosine value of x, where x is in radians. |
sin() |
math.sin(x) |
It returns the sine value of x, where x is in radians. |
tan() |
math.tan(x) |
It returns the tangent value of x, where x is in radians. |
cosh() |
math.cosh(x) |
It returns the hyperbolic cosine value of x. |
sinh() |
math.sinh(x) |
It returns the hyperbolic sine value of x. |
tanh() |
math.tanh(x) |
It returns the hyperbolic tangent value of x. |
acos() |
math.acos(x) |
It returns the arc cosine value of x, in radians. |
asin() |
math.asin(x) |
It returns the arc sine value of x, in radians. |
atan() |
math.atan(x) |
It returns the arc tangent value of x, in radians. |
acosh() |
math.acosh(x) |
It returns the inverse hyperbolic cosine value of x. |
asinh() |
math.asinh(x) |
It returns the inverse hyperbolic sine value of x. |
atanh() |
math.atanh(x) |
It returns the inverse hyperbolic tangent value of x. |
ceil() |
math.ceil(x) |
It returns the ceiling value of x, the smallest integer greater than or equal to x. |
degrees() |
math.degrees(x) |
It converts angle x from radians to degrees. |
dist() |
math.dist(a,b) |
It returns the Euclidean distance between two points (a and b), where a and b are the coordinates of that point. |
exp() |
math.exp(x) |
It returns the exponential value of x, i.e., ex, where e is Euler's number. |
expm1() |
math.expm1(x) |
It returns the value of ex−1, where e is Euler's number. |
fabs() |
math.fabs(x) |
It returns the absolute value of x. |
factorial() |
math.factorial(x) |
It returns the factorial of x. |
floor() |
math.floor(x) |
It returns the floor value of x, the largest integer less than or equal to x. |
gamma() |
math.gamma(x) |
It returns the gamma function value at x. |
gcd() |
math.gcd(a,b) |
It returns the greatest common factor between a and b. |
isfinite() |
math.isfinite(x) |
It returns True if x is a finite number. |
isinf() |
math.isinf(x) |
It returns True if x is positive or negative infinity. |
lgamma()
|
math.lgamma(x)
|
It returns the natural logarithm of the absolute value of the Gamma function of x. |
log() |
math.log(x [, base]) |
It returns the natural logarithm value of x. If the optional base is specified, return the logarithm of x to that base. |
log10() |
math.log10(x) |
It returns the value of base-10 logarithm of x |
log1p() |
math.log1p(x) |
It returns the natural logarithm value of 1+x |
log2() |
math.log2(x) |
It returns the base-2 logarithm value of x |
perm() |
math.perm(n,k) |
It returns the number of ways to choose k items from n items in order and without repetition. |
prod() |
math.prod(iterable [, start]) |
It calculates the product of all values in an iterable. Optional start value of the product (default = 1) |
radians() |
math.radians(x) |
It converts the value of angle x from degrees to radians. |
remainder() |
math.remainder(a,b) |
It returns the remainder when b divides a. |
sqrt() |
math.sqrt(x) |
It returns the square root value of x. |
trunc() |
math.trunc(x) |
It returns the truncated integer value of x. |
Note: In the above table, [ ] in the syntax denotes an optional argument.
The Python built-in functions in the table above can further be categorised based on the nature of the operations they perform. In the following sections, we will discuss these subcategories and the functions, along with examples.
- As seen in the table above, the syntax for these functions includes the term “math” followed by a dot operator to indicate that we are using a function from the math module.
- In addition to mentioning this in the syntax, we will also have to import the module at the beginning of the code every time we use any of these functions.
Numeric Functions | Math Python Built-in Functions
This subcategory of math Python built-in functions includes those that enable users to perform basic to advanced numeric operations. It includes methods like ceil(), floor(), fabs(), trunc(), remainder(), gcd(), perm(), and factorial(). Let’s discuss some of the most commonly used functions in more detail.
Python math.ceil() Method
The Python built-in function takes a numeric value (integer or floating-point) as argument and returns the smallest integer greater than or equal to the given number. It is commonly used in situations where you need to ensure that a value is rounded up to the next whole number.
Code Example:
import math
ceil_num = math.ceil(4.3)
print("Ceil of 4.3:", ceil_num)
Output:
Ceil of 4.3: 5
In the code example, we first import the math module.
- Then call the math.ceil() method, passing the number 4.3 as an argument.
- The function calculates and returns the ceil value of 4.3 and stores it in the ceil_num variable.
Python math.floor() Method
This Python built-in function takes a numeric value (integer or floating-point) as argument and returns the greatest integer smaller than or equal to the given number. It is commonly used in situations where you need to ensure that a value is rounded up to the previous whole number.
Code Example:
import math
floor_num = math.floor(-3.2)
print("Floor of -3.2:", floor_num)
Output:
Floor of -3.2: -4
In the code example, we call the math.floor() method, passing the negative number -3.2 as an argument. The function calculates and returns the floor value of -3.2 and stores it in the floor_num variable.
Python math.fabs() Method
The Python built-in function takes a numeric value (integer or floating-point) as an argument and returns the absolute value of the given number as a floating-point number. It is commonly used in situations where you require the magnitude of the number without considering its sign.
Code Example:
#Using abs() function to find an absolute value
abs_val = math.fabs(-3.8)
print("Absolute value of -3.8:", abs_val)
Output:
Absolute value of -3.8: 3.8
In the code example, we call the math.fabs() method, passing the number -3.8 as an argument. The function calculates and returns the absolute value of -3.8 and stores it in the abs_val variable.
Python math.gcd() Method
The Python built-in function takes two integers as arguments and returns the greatest common divisor of the two given numbers.
Code Example:
#Calculating the GCD using the in-built function
gcd_val = math.gcd(12, 18)
#Printing the gcd
print("GCD of 12 and 18:", gcd_val)
Output:
GCD of 12 and 18: 6
In the code example, we pass two numbers 12 and 18 to the math.gcd() method. The function calculates and returns the gcd value of 12 and 18 and stores it in the gcd_val variable.
Python math.perm() Method
The Python built-in function takes two integers (say, k and n) as arguments and returns the number of permutations of choosing k items from n items without replacement.
Code Example:
import math
#Calculating the permutations of two numbers and printing the outcome
perm_val = math.perm(10, 3)
print("Permutations of 10 choose 3:", perm_val)
Output:
Permutations of 10 choose 3: 720
In the code example, we pass numbers 10 and 3 to the math.perm() method. It calculates and returns the number of permutations of 10 choose 3, and stores it in the perm_val variable.
Python math.factorial() Method
The Python built-in function takes a non-negative integer as an argument and returns the factorial of the given number, which is the product of all positive integers less than or equal to the given number.
Code Example:
import math
factorial_val = math.factorial(10)
print("Factorial of 10:", factorial_val)
Output:
Factorial of 10: 3628800
In the code example, we use the math.factorial() method to calculate the factorial of 10. The method returns the factorial of 10 and stores it in the factorial_val variable.
Python math.remainder() Method
The Python built-in function takes two numeric values (integer or floating-point) as arguments (say, x and y), performs division x/y and returns the remainder of the division.
Code Example:
import math
remainder_val = math.remainder(-10, 3)
print("Remainder of -10 / 3:", remainder_val)
Output:
Remainder of -10 / 3: -1.0
In the code example, we use the math.remainder() method to calculate the remainder when -10 divided by 3. The method returns the remainder of -10/3 and stores it in the remainder_val variable which we then print to the console.
Python math.trunc() Method
The Python built-in function takes a numeric value (integer or floating-point) and returns the integer part of the given number by removing the fractional part.
Code Example:
import math
trunc_num = math.trunc(-3.2)
print("Truncated value of -3.2:", trunc_num)Â # Output: -3
Output:
Truncated value of -3.2: -3
In the code example, we use the math.trunc() method to calculate the integer part of -3.2. The method returns the truncated value of -3.2 and stores it in the trunc_num variable.
Python math.sqrt() Method
The Python built-in function takes a non-negative numeric value (integer or floating-point) and returns the non-negative square root of the given number.
Code Example:
import math
sqrt_val = math.sqrt(2.25)
print("Square root of 2.25:", sqrt_val)
Output:
Square root of 2.25: 1.5
In the code example, we use the math.sqrt() method to calculate the square root of 2.25. The method calculates and returns the square root storing it in the sqrt_val variable.
Angular Conversion Functions | Math Python Built-in Functions
This includes methods like math.radian() and math.degrees() for efficient inter-conversion of angular value among radian and degrees. These functions are particularly useful when dealing with trigonometric calculations, where angles are commonly expressed in both degrees and radians.
Python math.radians() Method
The Python built-in function maps an angle in degrees to the corresponding radians. Radians are a unit of measurement for angles, generally we use in mathematical and trigonometric calculations.
Code Example:
import math
radians_val = math.radians(45)
print("45 degrees in radians:", f'{radians_val:.4f}')
Output:
45 degrees in radians: 0.7854
In the code example, we convert 45 degrees to radians using the math.radians() method and print the result. This outputs the result 0.7854 (truncated to 4 decimal places) which is stored in the radians_val variable.
Python math.degrees() Method
The Python built-in function maps an angle in radians to the corresponding degrees. Degrees are a unit of measurement for angles that we commonly use in everyday contexts and graphical representations.
Code Example:
import math
degrees_val = math.degrees(1)
print("1 radian in degrees:", f'{degrees_val:.4f}')
Output:
1 radian in degrees: 57.2958
In the code example, we convert 1 radian to degrees using the math.degrees() method and print the result. This outputs the result 57.2958 (truncated to 4 decimal places), stored in the degrees_val variable.
Check out this amazing course to become the best version of the Python programmer you can be.
Exponential Functions | Math Python Built-in Functions
The Python built-in functions in this subcategory are particularly useful in scenarios where precise exponential calculations are required, especially when dealing with small values of x to avoid loss of precision. It includes methods like exp() and expm1() to calculate ex and ex-1, respectively.
Python math.exp() and math.expm1() Methods
The exp() and expm1() methods take a numeric value as exponent (say, x) and return the exponential value of the given number.
- The math.exp() returns ex while, math.expm1() returns ex-1.
- It is particularly useful in scenarios involving exponential growth or decay, such as financial modelling, population growth calculations, or scientific computations.
The basic Python code example below illustrates the use of these built-in functions to calculate the exponential value of 2.
Code Example:
import math
#Using the exponential functions
exp_val = math.exp(2)
expm1_val = math.expm1(2)
#Printing the outcomes of the operations
print("Exponential value of 2:", exp_val)
print("Exponential value of 2 minus 1:", expm1_val)
Output:
Exponential value of 2: 7.38905609893065
Exponential value of 2 minus 1: 6.38905609893065
In the code example, we compute the e2 and e2-1 using the math.exp() and math.expm1() methods respectively and print the results. These functions return the exponential value of 2 with high precision.
Logarithmic Functions | Math Python Built-in Functions
This includes the log(), log10(), log2() and log1p() functions which provide various options for calculating logarithms in Python, catering to different use cases and requirements.
- Python math.log() Method : Returns the logarithm of a given number, say x to the given base. If base is not specified, it defaults to e (natural logarithm), i.e., loge(x).
- Python math.log10() Method: Returns the base-10 logarithm of x, i.e., log10(x).
- Python math.log1p() Method: Returns the natural logarithm of (1 + x), i.e., ln(1+x).
- Python math.log2() Method: Returns the base-2 logarithm of x, i.e., log2(x).
The example below illustrates the use of these built-in functions in Python.
Code Example:
import math
log_val = math.log(10)
log10_val = math.log10(1000)
log1p_val = math.log1p(0.5)
log2_val = math.log2(16)
print("Natural logarithm of 10:", log_val)
print("Base-10 logarithm of 1000:", log10_val)
print("Natural logarithm of (1 + 0.5):", log1p_val)
print("Base-2 logarithm of 16:", log2_val)
Output:
Natural logarithm of 10: 2.302585092994046
Base-10 logarithm of 1000: 3.0
Natural logarithm of (1 + 0.5): 0.4054651081081644
Base-2 logarithm of 16: 4.0
In the code example we calculate the value of loge10 using the math.log() method, the value of log101000 using the math.log10() method, the value of loge(1+0.5) using the math.log1p() method, and the value of loge16 using the math.log2() method and print the results.
Trigonometric Functions | Math Python Built-in Functions
This includes functions like sin(), cos() and tan() to perform trigonometric computations in engineering and scientific applications where we analyse waveforms and periodic phenomena.
1. Python math.sin() Method: The Python built-in function from the math mdoule returns the sine of angle given in radians.
Code Example:
import math
sin_val = math.sin(math.pi / 2)
print("Sine of Ï/2 radians:", sin_val)
Output:
Sine of π/2 radians: 1.0
In the code example, we calculate the sin of π/2 radians using the math.sin() method, passing π/2 as input, which yields 1.0 as output.
2. Python math.cos() Method: This built-in function returns the cosine of angle given in radians.
Code Example:
import math
cos_val = math.cos(math.pi)
print("Cosine of Ï radians:", cos_val)
Output:
Cosine of π radians: -1.0
In the example, we calculate the cosine of π radians using the math.cos() method, passing π as input, which yields -1.0 as cosine of π.
3. Python math.tan() Method: This Python built-in function returns the cosine of angle given in radians.
Code Example:
import math
tan_val = math.tan(math.pi / 3)
print("Tangent of Ï/3 radians:", f'{tan_val:.4f}')
Output:
Tangent of π/3 radians: 1.7321
In the example, we calculate the tangent of π/3 radians using math.tan() method, passing π/3 as input, which yields 1.7321 as output.
Inverse Trigonometric Functions | Math Python Built-in Functions
The Python built-in functions in this subcategory have their use-case in engineering and scientific applications for calculating the angle in radians or degrees. It includes functions like:
- Python math.asin() Function: Calculates the inverse sine value of a given number.
- Python math.acos() Function: Calculates the inverse cosine value of a given number.
- Python math.atan() Function: Calculates the inverse tangent value of a given number.
The Python example code below illustrates the use of all these functions.
Code Example:
import math
#Using inverse trig functions inside print statements to calculate and print the values
print("Arc sine of 1:",math.asin(1))
print("Arc cosine of -1:",math.acos(-1))
print("Arc tangent of 1:",math.atan(1))
Output
Arc sine of 1: 1.5707963267948966
Arc cosine of -1: 3.141592653589793
Arc tangent of 1: 0.7853981633974483
In the code example, we print the inverse sine, cosine, and tangent values of the 1, -1, and 1, respectively. Which yields the respective angle value as output (in radians).
Hyperbolic Functions | Math Python Built-in Functions
These Python built-in functions are somewhat similar to trigonometric functions, but with a key difference. They help in hyperbolic calculation in scientific applications.
- Python math.sinh() Method: Returns the hyperbolic sine of a given number.
- Python math.cosh() Method: Returns the hyperbolic cosine of a given number.
- Python math.tanh() Method: Returns the hyperbolic tangent of a given number.
- Python math.asinh() Method: Returns the inverse hyperbolic sine (area hyperbolic sine) of a given number.
- Python math.acosh() Method: Returns the inverse hyperbolic cosine (area hyperbolic cosine) of a given number.
- Python math.atanh() Method: Returns the inverse hyperbolic tangent (area hyperbolic tangent) of a given number.
Code Example:
import math
print("Hyperbolic sine of 1:", math.sinh(1))
print("Hyperbolic cosine of 1:", math.cosh(1))
print("Hyperbolic tangent of 1:", math.tanh(1))
print("Inverse hyperbolic sine of 1:", math.asinh(1))
print("Inverse hyperbolic cosine of 1:", math.acosh(1))
print("Inverse hyperbolic tangent of 0.5:", math.atanh(0.5))
Output:
Hyperbolic sine of 1: 1.1752011936438014
Hyperbolic cosine of 1: 1.5430806348152437
Hyperbolic tangent of 1: 0.7615941559557649
Inverse hyperbolic sine of 1: 0.881373587019543
Inverse hyperbolic cosine of 1: 0.0
Inverse hyperbolic tangent of 0.5: 0.5493061443340548
In the code example, we use the hyperbolic sine, cosine, and tangent functions, as well as inverse hyperbolic sine, cosine, and tangent functions, to calculate their respective hyperbolic values.
Python Built-In Functions For Strings
In Python, there are several built-in functions for handling strings. They help us perform various manipulations, calculations, conversions, etc. on Python strings. Some examples are len() and str(), as well as functions from the string module like str.upper(), str.lower(), str.join(), str.split(), str.capitalize(), etc.
In the table below, we have listed some of the most commonly used Python built-in functions with respect to string, along with a description and syntax.
Function/Method Name |
Syntax |
Description |
len() |
len(s) |
Returns the length of the string or sequence s. |
str() |
str(object) |
Returns a string representation of an object. |
upper() |
s.upper() |
Returns a copy of the string s converted to uppercase. |
lower() |
s.lower() |
Returns a copy of the string s converted to lowercase. |
split() |
s.split(del [, n]) |
Returns a list of words in the string s separated by the delimiter del. Optional value n, number of times to split the string. |
join() |
del.join(itr) |
Joins all the elements of an iterable itr into a single string with del as the delimiter. |
capitalize() |
s.capitalize() |
Capitalise the string s (convert first character to uppercase) |
center() |
s.center(len [,char]) |
Center align the string s, with specified length len and optional filler character char (space is default) |
count() |
s.count(value [, start, end]) |
Count the number of times a specified value occurs in a string s with optional start and end position specificity. |
endswith() |
s.endswith(value [, start, end]) |
Returns true if the string s ends with the specified value. Optional start and end positions of string. |
find() |
s.find(value [, start, end]) |
Searches the string s for a specified value and returns the position of where it was found. Optional start and end positions of string. |
isalnum() |
s.isalnum() |
If all characters in the string s are alphanumeric, it returns true, otherwise false. |
isalpha() |
s.isalpha() |
If all characters in the string s are in the alphabet, it returns true, otherwise false. |
isascii() |
s.isascii() |
If all characters in the string s are ascii characters, it returns true, otherwise false. |
isdecimal() |
s.isdecimal() |
If all characters in the string s are decimals, it returns true, otherwise false. |
isdigit() |
s.isdigit() |
If all characters in the string s are digits, it returns true, otherwise false. |
islower() |
s.islower() |
If all characters in the string s are lower case, it returns true, otherwise false. |
isnumeric() |
s.isnumeric() |
If all characters in the string s are numeric, it returns true, otherwise false. |
isprintable() |
s.isprintable() |
If all characters in the string s are printable, it returns true, otherwise false. |
isspace() |
s.isspace() |
If all characters in the string s are whitespaces, it returns true, otherwise false. |
isupper() |
s.isupper() |
If all characters in the string s are upper case, it returns true, otherwise false. |
ljust() |
s.ljust(len [, char]) |
Left align the string s with specified length len of final string. Optional filler character char. |
lstrip() |
s.lstrip([char]) |
Removes leading spaces of the string s. Optional characters char to trim. |
replace() |
s.replace(oldvalue, newvalue [, count]) |
Returns a string where a specified newvalue is replaced with a specified oldvalue with optional number of occurrences to replace. |
startswith() |
s.startswith(value [, start, end]) |
If the string s starts with the specified value, it returns true. Optional start and end position of the search string. |
strip() |
s.strip([chars]) |
Returns a trimmed version of the string s. Optional the characters chars to trim. |
swapcase() |
s.swapcase() |
Returns a string with all lower case becomes upper case and vice versa. |
title() |
s.title() |
Converts the first character of each word to uppercase in the string s. |
translate() |
s.translate() |
Returns a translated version of the string s |
zfill() |
s.zfill(len) |
Fills the 0’s at the beginning of the string s, until it reaches the specified length len. |
Now that you have an overview of all relevant Python built-in functions for strings, let’s discuss some key function in more detail.
Level up your coding skills with the 100-Day Coding Sprint at Unstop and claim the bragging rights, now!
Python len() function
The Python built-in function is used to determine the length of a sequence, such as a string, list, or tuple. It commonly returns the number of characters present in a string or how many elements are in a list or tuple.
Code Example:
#Creating a string
S = "Hello, World!"
#Using len() function to calculate the length of a string
length = len(S)
print("Length of the string:", length)
Output:
Length of the string: 13
In the example above, we calculate the length of a string using the len() function by passing the string S to the len() function. The function calculates and returns the length of the string as output, stored in the variable length.
Python str() function
The Python built-in function converts an object to a string representation. This is useful when you need to ensure that an object is in string format for concatenation, printing, or other string operations. It takes an object as input and returns the string version of the object.
Code Example:
#Creating an integer variable
number = 123
#Converting the variable to string
string_number = str(number)
print("String representation:", string_number)
Output:
String representation: 123
In the example above, we use the str() function to convert an integer to a string. We pass the integer 123 to the str() function, which returns its string form as output.
Python upper() Method
The Python built-in function converts all characters in a string to uppercase. This is useful when you need to standardize or normalize text to a single case for comparison, storage, or display. It returns a new string with all characters converted to uppercase.
Code Example:
#Creating a string all in lowercase
text = "hello"
#Converting it to upper case
upper_text = text.upper()
print("Uppercase text:", upper_text)
Output:
Uppercase text: HELLO
In the code example, we call the upper() method by passing the string text as input. The function converts the string “hello” to uppercase and stores the output in the upper_text variable.
Python lower() Method
The Python built-in function converts all characters in a string to lowercase. This is useful when you need to standardize or normalize text to a single case for comparison, storage, or display. It returns a new string with all characters converted to lowercase.
Code Example:
#Creating a string all in uppercase
text = "HELLO"
#Converting it to lower case
lower_text = text.lower()
print("Lowercase text:", lower_text)
Output:
Lowercase text: hello
Here, we call the lower() method to the string “HELLO”, which converts the complete string to lowercase.
Python split() Method
The Python built-in function converts a string into a list of substrings based on a specified separator. It is useful for parsing strings, extracting data, or breaking down text into manageable parts. It returns a list of substrings.
Code Example:
#Creating a string
text = "Hello World"
#Splitting the string into a list of words
words = text.split()
print("List of words:", words)
Output:
List of words: ['Hello', 'World']
In the code example, we call the split() method by passing the string “Hello World” as an argument. It returns the list of substrings separated by whitespace.
Python join() Method
The Python built-in function concatenates the elements of an iterable (such as a list or tuple) into a single string, with each element separated by a specified delimiter. It is useful for constructing strings from collections of substrings.
Code Example:
#Creating a list
words = ["Hello", "World"]
#Converting it to a string/ concatenating the elements
sentence = " ".join(words)
print("Joined sentence:", sentence)
Output:
Joined sentence: Hello World
In the example, we join a list of words with a space using the join() method. We pass the list as an iterable and space(“ ”) as a delimiter.
Python capitalize() Method
The Python built-in function converts only the first character of a string to uppercase and the remaining characters to lowercase. It is useful for formatting text to ensure proper capitalization at the start of sentences or titles.
Code Example:
#Creating a string
text = "hello world"
#Converting the first character from lower to uppercase
capitalized_text = text.capitalize()
print("Capitalized text:", capitalized_text)
Output:
Capitalized text: Hello world
In the example above, we capitalise a lowercase string using the capitalize() method. We call the capitalize() method to the string named text (“hello world”). It converts the string and returns the outcome to the capitalized_text variable.
Python count() Method
The Python built-in function converts the number of occurrences of a substring within a string. Generally, we use it to determine the frequency of a substring in a text, such as counting words, characters, or patterns.
Code Example:
text = "banana"
substring = "a"
count = text.count(substring)
print("Count of 'a' in 'banana':", count)
Output:
Count of 'a' in 'banana': 3
In the code example, we count the occurrences of the substring "a" in the string "banana". For this, we call the count() method by passing the substring (“a”) as an argument and print the same stored in the count variable.
Python find() Method
The Python built-in function locates the position of a substring within a string. It returns the index of the first occurrence of the substring, or -1 if the substring is not found. Generally, we use it for searching substrings within a text.
Code Example:
text = "hello world"
substring = "world"
index = text.find(substring)
print("Index of 'world':", index)
Output:
Index of 'world': 6
In the code example, we find the position of the substring "world" in the string "hello world" using the find() method.
Python replace() Method
The Python built-in function helps replace occurrences of a specified substring with another substring.
- This method accepts the substring to be replaced and the substring to replace the old one and returns a new string with the specified replacements.
- Generally, we use it to modify text by replacing words, phrases, or characters.
Code Example:
text = "hello world"
replaced_text = text.replace("world", "Python")
print("Replaced text:", replaced_text)
Output:
Replaced text: hello Python
In the code example, we replace all occurrences of the substring "world" with "Python" using the replace() method.
Input/ Output Built-In Functions In Python
Input/output (I/O) operations are essential in any programming language for interacting with the user and handling file operations. Python has built-in functions for performing various input/output tasks efficiently, such as input(), open(), print(), etc. We have listed these Python built-in functions in the table below, along with the syntax and a description.
Function Name |
Syntax |
Description |
input() |
input(prompt) |
Reads a line from input and returns it as a string. |
print() |
print(value, ...) |
Prints the given values to the standard output. |
open() |
open(file, mode) |
Opens a file and returns a file object. |
read() |
file.read(size=-1) |
Reads and returns a string from the file. |
write() |
file.write(string) |
Writes the string string to the file. |
Now, let’s discuss these Python built-in functions in slightly more detail and with a code example.
Python input() Function
The Python built-in function is used to take input from the user.
- It displays an optional prompt message and waits for the user to type some input and press Enter.
- We generally use this for interactive programs where user input is needed.
Code Example:
#Using the input() function to read input from user
user_input = input()
#Printing the input provided
print("You entered:", user_input)
Input:
Unstop
Output:
You entered: Unstop
Here, we use the input() function to get input from the user without a prompt. Assuming that the user enters the string/ word Unstop, we then print the same to show the functionality of the input() function.
Python print() Function
The Python built-in function is used to output text or other data to the console or another output stream.
- We generally use this function to display information to the user, debug, and log.
- This function, by default, contains a newline character, which means that if more than one print statement is used one after another, it will print the subsequent output in the next/ new line.
You have already seen this function in all the examples above, but let’s look at a short example.
Code Example:
#Using the print library function to output a string
print("Hello, World!")
Output:
Hello, World!
Python open() Function
The Python built-in function is used to open a file and return a corresponding file object.
- It is essential to use this function whenever we want to perform any operations on a file, i.e., to read from and write to files.
- The function is generally used with a mode to specify the purpose for opening the file, for example “r” for reading, “w” for writing, and so on.
Code Example:
#Using open() to access a file names example.txt in the read mode
file = open("example.txt", "r")
#Once the file is open we can perform other operations on it, like read as done below
content = file.read()
#Printing the content we read from the file
print("File content:", content)
#Closing the file is essential to avoid any unexpected behavior
file.close()
Output:
File content: Unstop is best!
In the code example above, we open a file for reading using the open() function, read its content, and print it.
Note: This will throw an error as the directory or file should be available and should be accessible. Since, it was just a demonstration, “example.txt” was a local file created for it, and its content was printed above.
Python read() Method
The Python built-in functio method is used to read the contents of a file. It can read a specified number of bytes or the entire file.
Code Example:
file = open("unstop.txt", "r")
#Using the read() function to read content from a file
content = file.read()
#Printing the content and then closing it
print("File content:", content)
file.close()
Output:
File content: Unstop is best!
In the code example above, we read the entire content of a file using the read() method.
Note: This will throw an error as the directory or file should be available and should be accessible. SInce, it was just a demonstration, “example.txt” was a local file created for it and its content was read and printed above.
Python write() Function
The Python built-in function is used to write a string to a file. It is commonly used for creating or modifying files. As you will see in the example below, when opening the file for writing, we must specify that in the mode when opening the file.
Code Example:
#Opening the file in write mode
file = open("example.txt", "w")
#Writing content to the file using the write() function
characters_written = file.write("Hello, World!")
#Printing the number of charracters before closing the file
print("Characters written:", characters_written)
file.close()
Output:
Characters written: 13
In the code example above, we use the write() method to write "Hello, World!" to a file and print the number of characters written.
List & Tuple Python Built-In Functions
In Python there are a number of built-in functions to let us manipulate and handle the lists and tuples easily and efficiently. Lists and tuples are versatile and immutable data structures in Python that play a crucial role in data handling. Listed in the table below are all relevant built-in functions in Python, used in conjunction with lists and tuples.
Function Name |
Syntax |
Description |
len() |
len(s) |
Returns the length of the list or tuple s. |
sorted() |
sorted(iterable) |
Returns a new sorted list from the elements of the iterable. |
append() |
list.append(x) |
Appends an item x to the end of the list. |
extend() |
list.extend(iterable) |
Extends the list by appending elements from the iterable. |
index() |
list.index(x) |
Returns the index of the first occurrence of item x in the list. |
Python len() Function
The Python built-in function is used to determine the length of a sequence, such as a string, list, or tuple. It takes a sequence as input and returns the number of characters present in a string or how many elements are in a list or tuple.
Code Example:
#Creating a list
my_list = [1, 2, 3, 4, 5]
#Using the len() function to find the number of characters
length = len(my_list)
print("Length of the list:", length)
Output:
Length of the list: 5
In the example, we calculate the length of a list using the len() function. We pass the list my_list to the len() function, which returns the length of the list as output.
Python sorted() Function
The sorted() function is used to return a sorted list from the elements of any iterable.
- By default the function sorts the elments in an ascending order, however you can specify a sequence by adding an optional argument key.
- It is often used to sort lists, tuples, or any iterable based on a specific key or in reverse order.
Code Example:
#Creating a list
numbers = [5, 2, 9, 1, 5, 6]
#Sorting the list in default order
sorted_numbers = sorted(numbers)
print("Sorted list:", sorted_numbers)
Output:
Sorted list: [1, 2, 5, 5, 6, 9]
In the code example above, we call the sorted() function to sort a list of six integers, called numbers, in the default ascending order.
Python append() Method
The Python built-in function is used to add a single item to the end of a list. Using it, conveniently, we can add new elements to an existing list.
Code Example:
#Creating a list
numbers = [1, 2, 3, 4]
#Using append() to add an element
numbers.append(5)
print("Updated list:", numbers)
Output:
Updated list: [1, 2, 3, 4, 5]
In the code example, we add the number 5 to the end of a list of four integer values called numbers. The append() method modifies the original list in place and hence does not return a new list.
File Handling Python Built-In Functions
File handling is a crucial part of programming. It allows you to read and write to a file on the disk. Python offers many built-in functions for performing various file operations easily and efficiently. We have listed these Python built-in functions in the table below with the syntax and description.
Function Name |
Syntax |
Description |
close() |
file.close() |
Closes the file. |
flush() |
file.flush() |
Flushes the internal buffer. |
seek() |
file.seek(offset[, whence]) |
Moves the file pointer to a specified position. |
tell() |
file.tell() |
Returns the current file position. |
truncate() |
file.truncate(size=None) |
Resizes the file to a specified size |
As you can see in the syntax column above, we have used the term “file” followed by a dot operator, before all the function names. This is common practice to indicate that we are using Python built-in function from the file object or for the purpose of carrying out file handling operations.
Python close() Method
The Python built-in function is used to close an open file. It is important to close a file after it has been used to free up system resources and to ensure that all buffered data is written to the file. Failing to close a file can lead to data loss or corruption.
Code Example:
#Opening a file for writing
file = open("example.txt", "w")
#Using write() from file object to add content to the file
file.write("Hello, World!")
file.close()
Output: In example.txt
Hello, World!
In the code example above, we open a file for writing and use the write() function to write the string/ content "Hello, World!" to it.
Python tell() Method
The Python built-in function is used to determine the current position of the file pointer within the file. It returns the byte offset from the beginning of the file, which allows you to keep track of where you are within the file.
Code Example:
#Opening a file and writing a text to it
file = open("example.txt", "w")
file.write("Hello, World!")
#Using tell() to check the poisiton of the cursor after writing
position = file.tell()
print("File pointer position:", position)
file.close()
Output:
File pointer position: 13
In the code example, we open a file for writing and write "Hello, World!" to it. Then, we use the tell() function to the position of the file pointer, which should be at the end of the string. As shown in the output, this is 13, equivalent to the length of the text written.
Python truncate() Method
The Python built-in function is used to resize the file to a specified size.
- If the specified size is larger than the current size, the file is extended with null bytes.
- If the size is smaller, the file is truncated and any excess data is lost.
- It comes in handy when we want to control the size of a file.
Code Example:
#Opening a file and writing a text the length of 13 characters to it
file = open("example.txt", "w+")
file.write("Hello, World!")
#Using truncate to resize the content to 5 bytes
file.truncate(5)
# Moving the cursor to the start of the file and reading content to check if truncated
file.seek(0)
content = file.read()
print("Truncated content:", content)
file.close()
Output:
Truncated content: Hello
In the code example, we open a file for writing and reading and write "Hello, World!" to it. Then, we use the truncate() function to truncate the file to 5 bytes. We then read the truncated content, which results in "Hello".
Python Built-In Functions For Dictionary
Dictionaries are powerful data structures in Python that hold and retrieve data in the form of key-value pairs. Python provides many built-in functions for working with dictionaries, enabling developers to manipulate and process data effectively.
Listed in the table below are the commonly used Python built-in functions for working with dictionaries, with a description and the syntax.
Function Name |
Syntax |
Description |
len() |
len(d) |
Returns the number of items in the dictionary d. |
keys() |
d.keys() |
Returns a view of the dictionary's keys. |
values() |
d.values() |
Returns a view of the dictionary's values. |
items() |
d.items() |
Returns a view of the dictionary's key-value pairs. |
get() |
d.get(key[, default]) |
Returns the value for key if key is in the dictionary, else default. |
Like in other categories, here, we also use a character and dot operator before the function name. Here, the character “d” indicates that the function belongs to the dict class and that we are working with dictionary operations.
Python len() Function
The Python built-in function has already been featured in some other sections. In the case of dictionaries, it is used to determine the number of key-value pairs in a dictionary. We generally use it to check the size of the dictionary, which can be helpful in loops, conditions, or simply to understand the amount of data stored.
Code Example:
#Creating a dictionary representing students and their ages
student_ages = {"Srish": 21, "Shreeya": 22, "Shivi": 23}
#Using the len() function to find the number of pairs in the dictionary
length = len(student_ages)
print("Number of students:", length)
Output:
Number of students: 3
In the code example, we create a dictionary with three key-value paris and then use the len() function on it to find the number of these value pairs.
Python keys() Method
The Python built-in function is used to obtain all the keys in a dictionary. This can be useful when you need to iterate over keys or check if a certain key exists in the dictionary.
Code Example:
student_ages = {"Srish": 21, "Shreeya": 22, "Shivi": 23}
#Extracting just the keys from pairs
keys = student_ages.keys()
print("Keys:", keys)
Output:
Keys: dict_keys([Srish, Shreeya, Shivi])
Just like in the previous example, we have the same dictionary on which we use the keys() function to get all the keys. The function returns the keys in the form of a special view object.
Python values() Method
In contrast to the keys() function, this Python built-in function is used to obtain all the values in a dictionary. This can be useful when you need to process or analyze the values stored in the dictionary.
Code Example:
student_ages = {"Srish": 21, "Shreeya": 22, "Shivi": 23}
#Using values() to get the value from the pairs
values = student_ages.values()
print("Values:", values)
Output:
Values: dict_values([21, 22, 23])
In the code example, we use the same list as before and use the values() method to get all the values returned as a special view object.
Type Conversion Python Built-In Functions
Type conversion is the process of converting the data type of one variable or object to another. It is important for various operations, including input/output handling and performing mathematical calculations. Python provides many built-in functions for type conversion, as shown in the table below.
Function Name |
Syntax |
Description |
int() |
int(x) |
Converts x to an integer. |
float() |
float(x) |
Converts x to a floating-point number. |
str() |
str(object) |
Converts object to a string. |
list() |
list(iterable) |
Converts iterable to a list. |
tuple() |
tuple(iterable) |
Converts iterable to a tuple. |
bin() |
bin(x) |
Converts an integer, x to a binary string. |
oct() |
oct(x) |
Converts an integer, x to an octal string. |
hex() |
hex(x) |
Converts an integer, x to a hexadecimal string. |
bool() |
bool(argument) |
Converts an argument to a boolean value. |
chr() |
chr(x) |
Returns the character for the integer unicode number, x. |
ord() |
ord(c) |
Returns the integer unicode value of a character c. |
bytearray() |
bytearray() |
It creates an object of bytearray class. |
bytes() |
bytes() |
It creates an immutable object of the bytes class. |
Python int() Function
The Python built-in function is used to convert a number or a string to an integer. It is useful for type conversion when you need to perform arithmetic operations or store numbers in integer format.
Code Example:
string_number = "123"
integer_number = int(string_number)
print("Integer value:", integer_number)
Output:
Integer value: 123
Here, we convert a string (“123”) to an integer (123) using the int() function and then print it.
Python float() Function
The Python built-in function is used to convert a number or a string to a floating-point number. Generally, we use it for type conversion when you need to perform arithmetic operations involving decimal points.
Code Example:
string_number = "123.45"
float_number = float(string_number)
print("Float value:", float_number)
Output:
Float value: 123.45
Here, we convert a string (“123.45”) to a floating-point value (123.45) using the float() function and print it.
Python str() Function
The Python built-in function is used to convert an object to a string representation. Generally, we put it to use when you need to ensure that an object is in string format for concatenation, printing, or other string operations.
Code Example:
number = 123
string_number = str(number)
print("String representation:", string_number)
Output:
String representation: 123
Here, we convert an integer (123) to a string (“123”) using the str() function and print it.
Python list() Function
The Python built-in function is used to convert an iterable to a list. We put it to use for type conversion when you need to manipulate or access the elements of the iterable in list format.
Code Example:
my_tuple = (1, 2, 3)
list_from_tuple = list(my_tuple)
print("List from tuple:", list_from_tuple)
Output:
List from tuple: [1, 2, 3]
Here, we convert a tuple (my_tuple) to a list of characters (list_from_tuple) using the list() function.
Python tuple() Function
The Python built-in function is used to convert an iterable to a tuple. It is useful for type conversion when you need to ensure that the elements are in an immutable sequence.
Code Example:
my_list = [1, 2, 3]
tuple_from_list = tuple(my_list)
print("Tuple from list:", tuple_from_list)
Output:
Tuple from list: (1, 2, 3)
Here, we convert a list (my_list) to a tuple (tuple_from_list) using the tuple() function.
Basic Python Built-In Functions
In this section, we'll cover some of the fundamental built-in functions, their use-cases, the module they belong to (if applicable), and provide example snippets for better understanding. Basic Python built-in functions as listed in the table below, have a wide range of functionalities, from mathematical operations to type conversion and more.
Function Name |
Syntax |
Description |
type() |
type(object) |
Returns the type of an object. |
help() |
help([object]) |
Invokes the built-in help system. |
dir() |
dir([object]) |
Returns a list of valid attributes for the object. |
id() |
id(object) |
Returns the identity of an object. |
callable() |
callable(object) |
Checks if the object appears callable. |
Python type() Function
The Python built-in function is used to determine the type of an object. Generally, we use it for debugging, type checking, and understanding the nature of the objects you are working with.
Code Example:
#Creating an integer variable
number = 123
#Checking its type
print("Type of number:", type(number))
Output:
Type of number: <class 'int'>
Here, we use the type() function to get the type of an integer variable called number.
Python dir() Function
The Python built-in function is used to get a list of the attributes and methods of an object. It is useful for introspection, debugging, and exploring the capabilities of an object.
Code Example:
#Creating a listÂ
my_list = [1, 2, 3]
# Checking and displaying the list attributes using dir() inside print()
print("Attributes and methods of my_list:", dir(my_list))
Output:
Attributes and methods of my_list: ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Here, we use the dir() function to get the attributes and methods of a list, as shown in the output window.
Python id() Function
The Python built-in function is used to get the unique identifier of an object. This is useful for understanding object references, memory management, and ensuring that objects are distinct.
Code Example:
number = 123
#Using id() inside print to check and display the unique identifier for the variable
print("ID of number:", id(number))
Output:
ID of number: 124363478470704
Here, we use the id() function to get the unique identifier of an integer, as shown in the output window.
List Of Python Built-In Functions (Alphabetical)
Listed in the table below are any advanced or less frequently used built-in functions that might not fall into the categories discussed above.
Function Name |
Syntax |
Description |
all() |
all(iterable) |
Returns True if all elements of the iterable are true (or if the iterable is empty). |
any() |
any(iterable) |
Returns True if any element of the iterable is true. If the iterable is empty, returns False. |
ascii() |
ascii(object) |
Returns a string containing a printable representation of an object, escaping non-ASCII characters. |
bin() |
bin(x) |
Converts an integer number to a binary string prefixed with "0b". |
bool() |
bool([x]) |
Converts a value to a Boolean, using the standard truth testing procedure. |
bytearray() |
bytearray([source[, encoding[, errors]]]) |
Returns a new array of bytes. |
bytes() |
bytes([source[, encoding[, errors]]]) |
Returns a new "bytes" object, which is an immutable sequence of integers in the range 0 <= x < 256. |
chr() |
chr(i) |
Returns the string representing a character whose Unicode code point is the integer i. |
classmethod() |
classmethod(function) |
Converts a method into a class method. |
compile() |
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) |
Compiles a source into a code or AST object. |
complex() |
complex([real[, imag]]) |
Creates a complex number. |
delattr() |
delattr(object, name) |
Deletes the named attribute from the object. |
dict() |
dict(**kwargs) |
Creates a new dictionary. |
divmod() |
divmod(a, b) |
Takes two numbers and returns a pair of numbers (a // b, a % b). |
enumerate() |
enumerate(iterable, start=0) |
Returns an enumerate object, which yields pairs containing a count and a value yielded by the iterable. |
eval() |
eval(expression, globals=None, locals=None) |
Evaluates the given expression within the provided globals and locals. |
exec() |
exec(object[, globals[, locals]]) |
Executes the given object within the provided globals and locals. |
format() |
format(value[, format_spec]) |
Converts a value to a formatted string according to format_spec. |
frozenset() |
frozenset([iterable]) |
Returns a new frozenset object, which is an immutable set. |
getattr() |
getattr(object, name[, default]) |
Returns the value of the named attribute of an object. If not found, returns the default value if provided. |
globals() |
globals() |
Returns a dictionary representing the current global symbol table. |
hasattr() |
hasattr(object, name) |
Returns True if the object has the named attribute. |
hash() |
hash(object) |
Returns the hash value of the object. |
hex() |
hex(x) |
Converts an integer number to a lowercase hexadecimal string prefixed with "0x". |
isinstance() |
isinstance(object, classinfo) |
Returns True if the object is an instance or subclass of classinfo. |
issubclass() |
issubclass(class, classinfo) |
Returns True if class is a subclass (directly or indirectly) of classinfo. |
iter() |
iter(object[, sentinel]) |
Returns an iterator object. |
locals() |
locals() |
Updates and returns a dictionary representing the current local symbol table. |
memoryview() |
memoryview(obj) |
Returns a memory view object from the given object. |
next() |
next(iterator[, default]) |
Retrieves the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted. |
object() |
object() |
Returns a new featureless object. |
oct() |
oct(x) |
Converts an integer number to an octal string prefixed with "0o". |
ord() |
ord(c) |
Returns an integer representing the Unicode code point of the given Unicode character. |
property() |
property(fget=None, fset=None, fdel=None, doc=None) |
Returns a property attribute. |
range() |
range(start, stop[, step]) |
Generates a sequence of numbers from start to stop (exclusive) by step. |
repr() |
repr(object) |
Returns a string containing a printable representation of an object. |
reversed() |
reversed(seq) |
Returns an iterator that accesses the given sequence in reverse order. |
round() |
round(number[, ndigits]) |
Rounds a number to a given precision in decimal digits. |
set() |
set([iterable]) |
Returns a new set object. |
setattr() |
setattr(object, name, value) |
Sets the named attribute on the given object to the specified value. |
slice() |
slice(start, stop[, step]) |
Returns a slice object representing the set of indices specified by range(start, stop, step). |
staticmethod() |
staticmethod(function) |
Converts a method into a static method. |
super() |
super([type[, object-or-type]]) |
Returns a proxy object that delegates method calls to a parent or sibling class. |
vars() |
vars([object]) |
Returns the __dict__ attribute of the given object. |
zip() |
zip(*iterables) |
Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument iterables. |
Looking for guidance? Find the perfect mentor from select experienced coding & software experts here.
Let’s discuss three of the more common Python built-in function from the table above, with the help of examples.
Python all() Function
The Python built-in function is used to check if all elements in an iterable satisfy a certain condition. It returns True if all elements in the iterable are true (or if the iterable is empty); otherwise returns False.
Code Example:
numbers = [1, 2, 3, 4, 5]
result = all(num > 0 for num in numbers)
print(result)
Output:
True
Here, we use the all() function to check if all numbers in the list are greater than 0.
Python any() Function
The Python built-in function is used to check if any element in an iterable satisfies a certain condition. It returns True if any elements in the iterable are true (or if the iterable is empty), otherwise returns False.
Code Example:
numbers = [0, 1, 2, 3, 4]
result = any(num > 2 for num in numbers)
print(result)
Output:
True
Here, we use the any() function to check if any numbers in the list are greater than 2.
Python ascii() Function
The Python built-in function is used to get a string representation of an object with non-ASCII characters escaped. It returns a string containing a printable representation of an object, escaping non-ASCII characters.
Code Example:
#Creating a string variable that contains an emoji
text = "Python is fun! ð"
#Finding and printing the ascii value of the emoji
result = ascii(text)
print(result)
Output:
'Python is fun! \U0001f60a'
Here, we convert the emoji to its Unicode escape sequence using the ascii() function.
Conclusion
Python’s built-in functions are the backbone of efficient and effective coding, empowering developers to tackle everything from simple data manipulations to complex computations with ease. Mastering these built-in functions across categories—whether for mathematical operations, string handling, file manipulation, and more—is essential for writing efficient Python programs.
Familiarity with these powerful tools not only simplifies problem-solving but also opens doors to writing cleaner, more readable code. Whether you're just starting or are a seasoned Pythonista, these functions are key to unlocking the language's full potential and enhancing your coding prowess.
Frequently Asked Questions
Q1. How do I find the list of all built-in functions in Python?
To view all built-in functions in Python, you can use the dir() function on the builtins module. This will return a list of all attributes, including functions, exceptions, and other objects.
Code Example:
import builtins
built_in_functions = dir(builtins)
print(built_in_functions)
This will print a list of all the available constants, exceptions and built-in functions in Python.
Q2. Can I override Python built-in functions?
Yes, you can override built-in functions by defining a function with the same name within the current scope. However, this practice is generally discouraged as it may lead to confusion and unexpected behavior in your code.
Q3. What is the difference between all() and any() functions?
The all() function returns True if all elements in the iterable are true, while any() function returns True if any element in the iterable is true.
Q4. How many built-in functions does Python have?
Python has over 70 built-in functions, covering a wide range of functionalities from basic operations to more complex tasks.
Q5. Give an example of the zip() function?
The zip() function combines elements from multiple iterables into pairs, as shown in the example below.
Code Example:
#Using zip on iterables
#And then converting it to a list before printing
print(list(zip([1, 2, 3], ['a', 'b', 'c'])))
Output:
[(1, 'a'), (2, 'b'), (3, 'c')]
In the code example above, we combine two lists into a single list using the zip() function.
Q6. How does enumerate() work and why is it useful?
The enumerate() function adds a counter to an iterable, returning an enumerate object. This is useful for accessing both index and value in a for loop:
Code Example:
for index, value in enumerate(['a', 'b', 'c']):
print(index, value)
Output:
0 a
1 b
2 c
In the code example above, we use the enumerate() function to print the index of each value inside the list.
Q7. What are Python's built-in functions?
Built-in functions in Python arе prе-dеfinеd functions that are readily available and accеssiblе without rеquiring any import statеmеnts or additional sеtups. Thеsе functions arе part of thе Python standard library and offеr a widе rangе of functionalitiеs to perform various tasks.
Q8. How do classmethod() and staticmethod() differ?
The classmethod() converts a method into a class method, which receives the class (cls) as an implicit first argument. The staticmethod() on the other hand, converts a method into a static method, which does not receive an implicit first argument.
Q9. How can I create a range of numbers in Python?
You can use the Python built-in function, range() to create a range of numbers. For example, range(1, 10) generates numbers from 1 to 9.
Q10. How does the eval() function work? Explain with an example.
The eval() function evaluates a string as a Python expression and returns the result. It can also execute code dynamically.
Code Example:
x = 10
expression = "x * 2 + 5"
result = eval(expression)
print(result)
Output:
25
In the code example above, we use eval() function to evaluate the string "x * 2 + 5" as if it were a Python expression, using the current value of x and prints the result.
Think You Know Python Built-in Functions? Prove It!
This compiles our discussion on the Python built-in functions. Here are a few more Python topics you must explore:
- Python Logical Operators, Short-Circuiting & More (With Examples)
- Python Bitwise Operators | Positive & Negative Numbers (+Examples)
- 12 Ways To Compare Strings In Python Explained (With Examples)
- Python Namespace & Variable Scope Explained (With Code Examples)
- How To Reverse A String In Python? 10 Easy Ways With Examples
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.
Divyansh Shrivastava 3 weeks ago
Pranjul Srivastav 1 month ago
Anjali Nimesh 1 month ago
SIRIVERU MAHESWARI 1 month ago
niyati m singh 1 month ago
Pardha Venkata Sai Patnam 1 month ago