Python is one of the most widely-used and popular programming languages, was developed by Guido van Rossum and released first in 1991. Python is a free and open-source language with a very simple and clean syntax which makes it easy for developers to learn Python. It supports object-oriented programming and is most commonly used to perform general-purpose programming.
Why Python?
- Easy to Learn – Clean, readable syntax that feels like plain English.
- Free & Open-Source – No cost, no restrictions—just pure coding freedom.
- Object-Oriented & Versatile – Supports multiple programming paradigms.
- Massive Community Support – Tons of libraries, frameworks and active contributors.
Where is Python Used?
To master python from scratch, you can refer to our article: Python Tutorial
Python Basics
Printing Output
print() function in Python is used to print Python objects as strings as standard output. keyword end can be used to avoid the new line after the output or end the output with a different string.
Python
# python program to print "Hello World"
print("Hello World")
# ends the output with a space
print("Welcome to", end=' ')
print("GeeksforGeeks", end=' ')
Python sep parameter in print()
The separator between the inputs to the print() method in Python is by default a space, however, this can be changed to any character, integer, or string of our choice. The 'sep' argument is used to do the same thing.
Python
# code for disabling the softspace feature
print('09', '12', '2016', sep='-')
# another example
print('Example', 'geeksforgeeks', sep='@')
input() method in Python is used to accept user input. By default, it returns the user input as a string. By default, the input() function accepts user input as a string.
Python
# Python program showing
# a use of input()
val = input("Enter your value: ")
print(val)
Output:
Enter your value: Hello Geeks
Hello Geeks
Comments in Python are the lines in the code that are ignored by the interpreter during the execution of the program. There are three types of comments in Python:
- Single line Comments
- Multiline Comments
- Docstring Comments
Python
# Single Line comment
# Python program to demonstrate
# multiline comments
""" Python program to demonstrate
multiline comments"""
name = "geeksforgeeks"
print(name)
Variables and Data Types
Variables store values and Python supports multiple data types.
Python
# Variable Declaration
x = "Hello World"
# DataType Output: int
x = 50
# DataType Output: float
x = 60.5
# DataType Output: complex
x = 3j
Type Checking and Conversion
We can check the data type of a variable using type() and convert types if needed.
Python
print(type(x)) # <class 'int'>
y = int(y) # Convert float to int
Operators in Python
In general, Operators are used to execute operations on values and variables. These are standard symbols used in logical and mathematical processes.
Control Flow
Conditional Statements
Used to execute different blocks of code based on conditions.
Python
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is 5")
else:
print("x is less than 5")
Loops
Loops help iterate over sequences or repeat actions.
For Loop:
Python
for i in range(5):
print(i) # Prints 0 to 4
While Loop:
Python
i = 0
while i < 5:
print(i)
i += 1
Loop Control Statements
Loop Control Statements include break and continue.
break exits the loop, while continue skips the current iteration.
Python
for i in range(10):
if i == 5:
break # Exits loop
if i == 3:
continue # Skips iteration
print(i)
Interesting Facts about Loops in Python:
1. Using enumerate to Get Index and Value in a Loop: Want to find the index inside a for loop? Wrap an iterable with ‘enumerate’ and it will yield the item along with its index. See this code snippet
Python
vowels=['a','e','i','o','u']
for i, letter in enumerate(vowels):
print (i, letter)
Output0 a
1 e
2 i
3 o
4 u
Python Functions
Python Functions are a collection of statements that serve a specific purpose. The idea is to bring together some often or repeatedly performed actions and construct a function so that we can reuse the code included in it rather than writing the same code for different inputs over and over.
Python
# A simple Python function
def fun():
print("Welcome to GFG")
# Driver code to call a function
fun()
Function Arguments
Arguments are the values given between the function's parenthesis. A function can take as many parameters as it wants, separated by commas.
Python
# A simple Python function to check
# whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
evenOdd(2)
evenOdd(3)
Return Statement in Python Function
The function return statement is used to terminate a function and return to the function caller with the provided value or data item.
Python
# Python program to
# demonstrate return statement
def add(a, b):
# returning sum of a and b
return a + b
def is_true(a):
# returning boolean of a
return bool(a)
# calling function
res = add(2, 3)
print("Result of add function is {}".format(res))
res = is_true(2<5)
print("\nResult of is_true function is {}".format(res))
OutputResult of add function is 5
Result of is_true function is True
The range() function
The Python range() function returns a sequence of numbers, in a given range.
Python
# print first 5 integers
# using python range() function
for i in range(5):
print(i, end=" ")
print()
*args and **kwargs in Python
The *args and **kwargs keywords allow functions to take variable-length parameters. The number of non-keyworded arguments and the action that can be performed on the tuple are specified by the *args.**kwargs, on the other hand, pass a variable number of keyword arguments dictionary to function, which can then do dictionary operations.
Python
def myFun(arg1, arg2, arg3):
print("arg1:", arg1)
print("arg2:", arg2)
print("arg3:", arg3)
# Now we can use *args or **kwargs to
# pass arguments to this function :
args = ("Geeks", "for", "Geeks")
myFun(*args)
kwargs = {"arg1": "Geeks", "arg2": "for", "arg3": "Geeks"}
myFun(**kwargs)
Outputarg1: Geeks
arg2: for
arg3: Geeks
arg1: Geeks
arg2: for
arg3: Geeks
Interesting Facts about Functions in Python:
1. One can return multiple values in Python: In Python, we can return multiple values from a function. Python allows us to return multiple values by separating them with commas. These values are implicitly packed into a tuple and when the function is called, the tuple is returned
Python
def func():
return 1, 2, 3, 4, 5
one, two, three, four, five = func()
print(one, two, three, four, five)
Data Structures in Python
List in Python
Python list is a sequence data type that is used to store the collection of data. Tuples and String are other types of sequence data types.
Python
Var = ["Geeks", "for", "Geeks"]
print(Var)
Output['Geeks', 'for', 'Geeks']
List comprehension
A Python list comprehension is made up of brackets carrying the expression, which is run for each element, as well as the for loop, which is used to iterate over the Python list's elements.
Also, Read - Python Array
Python
# Using list comprehension to iterate through loop
List = [character for character in [1, 2, 3]]
# Displaying list
print(List)
Interesting Facts about Lists in Python
- Lists Have Been in Python Since the Beginning: When Guido van Rossum created Python in the late 1980s, lists were an essential part of the language from the very first version (Python 1.0, released in 1991). Unlike languages like C or Java, where arrays have strict rules.
- Inspired by ABC Language: Python was influenced by the ABC programming language, which also had a simple and intuitive way of handling sequences. However, Python improved upon it by making lists mutable (meaning they can be changed), which is one of the biggest reasons for their popularity.
Explore in detail about Interesting Facts About Python Lists
Dictionary in Python
A dictionary in Python is a collection of key values, used to store data values like a map, which, unlike other data types holds only a single value as an element.
Python
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(Dict)
Output{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary Comprehension
Like List Comprehension, Python allows dictionary comprehension. We can create dictionaries using simple expressions. A dictionary comprehension takes the form {key: value for (key, value) in iterable}
Python
# Lists to represent keys and values
keys = ['a','b','c','d','e']
values = [1,2,3,4,5]
# but this line shows dict comprehension here
myDict = { k:v for (k,v) in zip(keys, values)}
# We can use below too
# myDict = dict(zip(keys, values))
print (myDict)
Output{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
Interesting Facts About Python Dictionary
- Dictionaries Are Ordered: Before Python 3.7, dictionaries did not preserve the order of insertion. However, with the introduction of Python 3.7 and beyond, dictionaries now maintain the order of the key-value pairs. Now we can rely on the insertion order of keys when iterating through dictionaries, which was previously a feature exclusive to OrderedDict.
- Dictionaries Can Have Any Immutable Type as Keys: The keys of a dictionary must be immutable, meaning they can be strings, numbers or tuples, but not lists or other mutable types. This feature ensures that the dictionary keys are hashable, maintaining the integrity and performance of lookups.
Explore in detail about Interesting Facts About Python Dictionary
Tuples in Python
Tuple is a list-like collection of Python objects. A tuple stores a succession of values of any kind, which are indexed by integers.
Python
var = ("Geeks", "for", "Geeks")
print(var)
Output('Geeks', 'for', 'Geeks')
Sets in Python
Python Set is an unordered collection of data types that can be iterated, mutated and contains no duplicate elements. The order of the elements in a set is unknown, yet it may contain several elements.
Python
var = {"Geeks", "for", "Geeks"}
print(var)
Python String
In Python, a string is a data structure that represents a collection of characters. A string cannot be changed once it has been formed because it is an immutable data type.
Creating and Accessing String
Strings in Python can be created using single quotes or double quotes or even triple quotes. In Python, individual characters of a String can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the String.
Python
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
# Printing First character
print("\nFirst character of String is: ")
print(String1[0])
# Printing Last character
print("\nLast character of String is: ")
print(String1[-1])
OutputInitial String:
GeeksForGeeks
First character of String is:
G
Last character of String is:
s
String Slicing
Strings in Python can be constructed with single, double, or even triple quotes. The slicing method is used to access a single character or a range of characters in a String. A Slicing operator (colon) is used to slice a String.
Python
# Creating a String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
# Printing 3rd character
print("\nSlicing characters from 3-12: ")
print(String1[3])
# Printing characters between
# 3rd and 2nd last character
print("\nSlicing characters between " +
"3rd and 2nd last character: ")
print(String1[3:-2])
OutputInitial String:
GeeksForGeeks
Slicing characters from 3-12:
k
Slicing characters between 3rd and 2nd last character:
ksForGee
Interesting Facts About Python strings
- Strings are Immutable, once a string is defined, it cannot be changed.
- Strings Can Be Concatenated Using the + Operator: We can easily combine (concatenate) strings using the + operator. This simple operation allows us to build longer strings from smaller ones, which is helpful when working with user input or constructing strings dynamically.
Explore in detail about Interesting Facts about Python Strings
Explore in Detail Python Data Structures and Algorithms
Python Built-In Function
There are numerous built-in methods in Python that make creating code easier. Learn about the built-in functions of Python in this post as we examine their numerous uses and highlight a few of the most popular ones.
For More Read, refer Python Built in Functions
Python OOPs Concepts
Object-oriented Programming (OOPs) is a programming paradigm in Python that employs objects and classes. It seeks to include real-world entities such as inheritance, polymorphisms, encapsulation and so on into programming. The primary idea behind OOPs is to join the data and the functions that act on it as a single unit so that no other portion of the code can access it.
In this example, we have a Car class with characteristics that represent the car's make, model and year. The _make attribute is protected with a single underscore _. The __model attribute is marked as private with two underscores __. The year attribute is open to the public.
We can use the getter function get_make() to retrieve the protected attribute _make. We can use the setter method set_model() to edit the private attribute __model. Using the getter method get_model(), we may retrieve the changed private attribute __model. There are no restrictions on accessing the public attribute year. We manage the visibility and accessibility of class members by using encapsulation with private and protected properties, offering a level of data hiding and abstraction.
Python
class Car:
def __init__(self, make, model, year):
self._make = make # protected attribute
self.__model = model # private attribute
self.year = year # public attribute
def get_make(self):
return self._make
def set_model(self, model):
self.__model = model
def get_model(self):
return self.__model
my_car = Car("Toyota", "Corolla", 2022)
print(my_car.get_make()) # Accessing protected attribute
my_car.set_model("Camry") # Modifying private attribute
print(my_car.get_model()) # Accessing modified private attribute
print(my_car.year) # Accessing public attribute
Interesting facts about OOPs in Python:
1. Python Supports Multiple Programming Paradigms: One of Python's key strengths is its flexibility. Python supports several programming paradigms, including:
- Object-Oriented Programming (OOP)
- Functional Programming
- Procedural Programming
2. Everything in Python Is an Object: In Python, everything is an object, including data types such as integers, strings and functions. This allows for object-oriented programming (OOP) principles to be applied across all aspects of the language, including the ability to define classes, inheritance and methods.
Python
x = 5
# <class 'int'>
print(type(x))
def greet(name):
return f"Hello, {name}"
# <class 'function'>
print(type(greet))
Output<class 'int'>
<class 'function'>
Python RegEx
We define a pattern using a regular expression to match email addresses. The pattern r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b" is a common pattern for matching email addresses. Using the re.search() function, the pattern is then found in the given text. If a match is found, we use the match object's group() method to extract and print the matched email. Otherwise, a message indicating that no email was found is displayed.
Python
import re
# Text to search
text = "Hello, my email is [email protected]"
# Define a pattern to match email addresses
pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"
# Search for the pattern in the text
match = re.search(pattern, text)
# Check if a match is found
if match:
email = match.group()
print("Found email:", email)
else:
print("No email found.")
MetaCharacters are helpful, significant and will be used in module re functions, which helps us comprehend the analogy with RE. The list of metacharacters is shown below.
- \ sed to drop the special meaning of character following it.
- [] Represent a character class.
- ^ Matches the beginning.
- $ Matches the end.
- . Matches any character except newline.
- | Means OR (Matches with any of the characters separated by it.
- ? Matches zero or one occurrence.
- * Any number of occurrences (including 0 occurrences).
- + One or more occurrences.
- {} Indicate the number of occurrences of a preceding RegEx to match.
- () Enclose a group of RegEx.
For More RegEx example, refer to Python RegEx.
Exception Handling in Python
In Python, Try and except statements are used to catch and manage exceptions. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.
Python
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
# Throws error since there are only 3 elements in array
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")
OutputSecond element = 2
An error occurred
Debugging in Python
Debugging is the process of finding and fixing errors (bugs) in our code. Python provides several methods and tools to help debug programs effectively.
1. Using Print Statements
Python
x = 10
y = 20
print("x:", x)
print("y:", y)
result = x + y
print("result:", result)
Outputx: 10
y: 20
result: 30
2. Using pdb (Python Debugger)
The pdb module provides an interactive debugging environment. We can set breakpoints, step through the code, inspect variables and more. To start debugging, insert pdb.set_trace() where we want to start the debugger.
Python
import pdb
x = 5
y = 10
pdb.set_trace() # Debugger starts here
result = x + y
print(result)
Output
> /home/repl/2b752c75-c2c1-44d7-b2bd-fa43a3072b3c/main.py(6)<module>()
-> result = x + y
(Pdb)
Once the program reaches pdb.set_trace(), it will enter the interactive mode where we can run various commands like:
- n (next): Execute the next line of code.
- s (step): Step into a function.
- c (continue): Continue execution until the next breakpoint.
- q (quit): Exit the debugger.
3. Using logging Module
The logging module is more advanced than print() statements and is useful for debugging in production environments. It allows us to log messages with different severity levels (DEBUG, INFO, WARNING, ERROR, CRITICAL).
Python
import logging
# Set up logging configuration
logging.basicConfig(level=logging.DEBUG)
# Log different messages
logging.debug("This is a debug message")
logging.info("This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")
logging.critical("This is a critical message")
Output
DEBUG:root:This is a debug message
INFO:root:This is an info message
WARNING:root:This is a warning message
ERROR:root:This is an error message
CRITICAL:root:This is a critical message
File Handling in Python
Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files.
Python
import os
def create_file(filename):
try:
with open(filename, 'w') as f:
f.write('Hello, world!\n')
print("File " + filename + " created successfully.")
except IOError:
print("Error: could not create file " + filename)
def read_file(filename):
try:
with open(filename, 'r') as f:
contents = f.read()
print(contents)
except IOError:
print("Error: could not read file " + filename)
def append_file(filename, text):
try:
with open(filename, 'a') as f:
f.write(text)
print("Text appended to file " + filename + " successfully.")
except IOError:
print("Error: could not append to file " + filename)
def rename_file(filename, new_filename):
try:
os.rename(filename, new_filename)
print("File " + filename + " renamed to " +
new_filename + " successfully.")
except IOError:
print("Error: could not rename file " + filename)
def delete_file(filename):
try:
os.remove(filename)
print("File " + filename + " deleted successfully.")
except IOError:
print("Error: could not delete file " + filename)
if __name__ == '__main__':
filename = "example.txt"
new_filename = "new_example.txt"
create_file(filename)
read_file(filename)
append_file(filename, "This is some additional text.\n")
read_file(filename)
rename_file(filename, new_filename)
read_file(new_filename)
delete_file(new_filename)
OutputFile example.txt created successfully.
Hello, world!
Text appended to file example.txt successfully.
Hello, world!
This is some additional text.
File example.txt renamed to new_example.txt successfu...
Reading and Writing Files
Python provides built-in functions to handle file operations such as reading from and writing to files. We can use the open() function to work with files.
1. Opening a File:
The open() function is used to open a file and returns a file object.
Python
file = open('filename.txt', 'mode')
- 'r': Read (default mode) - Opens the file for reading.
- 'w': Write - Opens the file for writing (creates a new file or overwrites an existing one).
- 'a': Append - Opens the file for appending data.
- 'rb', 'wb': Read/Write in binary mode.
2. Reading from a File:
There are several methods to read the contents of a file:
- read()
- readline()
- readlines()
Python
with open('example.txt', 'r') as file:
# Using read()
content = file.read()
print(content)
# Resetting the pointer to the beginning of the file
file.seek(0)
# Using readline()
first_line = file.readline()
print(first_line)
# Resetting the pointer again
file.seek(0)
# Using readlines()
lines = file.readlines()
print(lines)
3. Writing to a File:
We can write data to a file using the write()
or writelines()
methods:
write(): Writes a string to the file.
Python
with open('filename.txt', 'w') as file:
file.write("Hello, World!")
writelines(): Writes a list of strings to the file.
Python
with open('filename.txt', 'w') as file:
file.writelines(['Hello\n', 'World\n'])
4. Closing the File:
It is good practice to close the file after operations using file.close(), but it is recommended to use the with statement as it automatically handles file closure.
Python
Memory Management in Python
Memory management in Python is handled by the Python memory manager. Python uses an automatic memory management system, which includes garbage collection to reclaim unused memory and reference counting to track memory usage.
Key Concepts:
- Reference Counting: Every object in Python has a reference count. When the count reaches zero, the object is deleted automatically.
- Garbage Collection: Python uses a garbage collector to clean up circular references (when objects reference each other in a cycle).
Python
import sys
x = 10
y = [1, 2, 3]
# Checking memory size of variables
print("Memory size of x:", sys.getsizeof(x))
print("Memory size of y:", sys.getsizeof(y))
# Reference counting
a = [1, 2, 3]
b = a
print(sys.getrefcount(a))
OutputMemory size of x: 28
Memory size of y: 88
3
Decorators in Python
Decorators are used to modifying the behavior of a function or a class. They are usually called before the definition of a function we want to decorate.
1. property Decorator (getter)
Python
@property
def name(self):
return self.__name
2. setter Decorator
It is used to set the property 'name'
Python
@name.setter
def name(self, value):
self.__name=value
3. deleter Decorator
It is used to delete the property 'name'
Python
@name.deleter
def name(self, value):
print('Deleting..')
del self.__name
Libraries in Python
Libraries in Python are collections of pre-written code that allow us to perform common tasks without having to write everything from scratch. They provide functions and classes to help with tasks like data manipulation, web scraping and machine learning. Python has a vast ecosystem of libraries, both built-in and third-party.
Basic Libraries
These libraries are part of Python's standard library and come bundled with Python installation. Some Basic Libraries are:
- math: Provides mathematical functions such as trigonometric, logarithmic and basic arithmetic operations.
- datetime: Works with dates and times, allows for formatting and manipulation of date/time data.
- os: Provides functions for interacting with the operating system, such as working with files and directories.
- sys: Provides access to system-specific parameters and functions, such as the interpreter's version or command-line arguments.
Data Science and Analysis Libraries
These libraries are essential for data manipulation, analysis and visualization. Some Data Science and Analysis Libraries are:
- numpy: A fundamental package for scientific computing with Python. It provides support for large multidimensional arrays and matrices.
- pandas: Used for data manipulation and analysis. It provides data structures like DataFrames to handle structured data.
- matplotlib: A 2D plotting library to create static, animated and interactive visualizations.
Web Development Libraries
These libraries help us build and interact with web applications and services. Some Web Development Libraries are:
- flask: A lightweight web framework for building web applications.
- requests: A simple HTTP library for sending HTTP requests, handling responses and interacting with APIs.
Machine Learning and AI Libraries
These libraries help build machine learning models, perform deep learning and work with AI algorithms. Some Machine Learning and AI Libraries are:
- scikit-learn: A machine learning library that provides simple and efficient tools for data mining and data analysis.
- tensorflow: A deep learning framework developed by Google, used for building neural networks and training AI models.
Python Modules
A library is a group of modules that collectively address a certain set of requirements or applications. A module is a file (.py file) that includes functions, class defining statements and variables linked to a certain activity. The term "standard library modules" refers to the pre-installed Python modules.
Interesting Facts about Python Modules:
1. import this:There is actually a poem written by Tim Peters named as THE ZEN OF PYTHON which can be read by just writing import this in the interpreter.
Python
Output
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
2. The "antigravity" Easter Egg in Python: The statement import antigravity in Python is a fun Easter egg that was added to the language as a joke. When we run this command, it opens a web browser to a comic from the popular webcomic xkcd (specifically, xkcd #353: "Python").
Python
Python Interview Questions Answers
Python Cheat Sheet
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Fundamentals
Python IntroductionPython was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in PythonUnderstanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython's input() function
7 min read
Python VariablesIn Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Python OperatorsIn Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. OPERATORS: These are the special symbols. Eg- + , * , /,
6 min read
Python KeywordsKeywords in Python are reserved words that have special meanings and serve specific purposes in the language syntax. Python keywords cannot be used as the names of variables, functions, and classes or any other identifier. Getting List of all Python keywordsWe can also get all the keyword names usin
2 min read
Python Data TypesPython Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Conditional Statements in PythonConditional statements in Python are used to execute certain blocks of code based on specific conditions. These statements help control the flow of a program, making it behave differently in different situations.If Conditional Statement in PythonIf statement is the simplest form of a conditional sta
6 min read
Loops in Python - For, While and Nested LoopsLoops in Python are used to repeat actions efficiently. The main types are For loops (counting through items) and While loops (based on conditions). In this article, we will look at Python loops and understand their working with the help of examples. For Loop in PythonFor loops is used to iterate ov
9 min read
Python FunctionsPython Functions is a block of statements that does a specific task. The idea is to put some commonly or repeatedly done task together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over an
9 min read
Recursion in PythonRecursion involves a function calling itself directly or indirectly to solve a problem by breaking it down into simpler and more manageable parts. In Python, recursion is widely used for tasks that can be divided into identical subtasks.In Python, a recursive function is defined like any other funct
6 min read
Python Lambda FunctionsPython Lambda Functions are anonymous functions means that the function is without a name. As we already know the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python. In the example, we defined a lambda function(u
6 min read
Python Data Structures
Python StringA string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1.Pythons = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # update print(s1) # printOut
6 min read
Python ListsIn Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read
Python TuplesA tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e., they are immutable). Tuples can hold elements of different data types. The main characteristics of tuples are being ordered , heterogene
6 min read
Dictionaries in PythonPython dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier to
7 min read
Python SetsPython set is an unordered collection of multiple items having different datatypes. In Python, sets are mutable, unindexed and do not contain duplicates. The order of elements in a set is not preserved and can change.Creating a Set in PythonIn Python, the most basic and efficient method for creating
10 min read
Python ArraysLists in Python are the most flexible and commonly used data structure for sequential storage. They are similar to arrays in other languages but with several key differences:Dynamic Typing: Python lists can hold elements of different types in the same list. We can have an integer, a string and even
9 min read
List Comprehension in PythonList comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying an expression to each item in an existing iterable (such as a list or range). This helps us to write cleaner, more readable code compared to traditional looping techniques.For example,
4 min read
Advanced Python
Python OOPs ConceptsObject Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. OOPs is a way of organizing code that uses objects and classes to represent real-world entities and their behavior. In OOPs, object has attributes thing th
11 min read
Python Exception HandlingPython Exception Handling handles errors that occur during the execution of a program. Exception handling allows to respond to the error, instead of crashing the running program. It enables you to catch and manage errors, making your code more robust and user-friendly. Let's look at an example:Handl
6 min read
File Handling in PythonFile handling refers to the process of performing operations on a file, such as creating, opening, reading, writing and closing it through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely a
4 min read
Python Database TutorialPython being a high-level language provides support for various databases. We can connect and run queries for a particular database using Python and without writing raw queries in the terminal or shell of that particular database, we just need to have that database installed in our system.A database
4 min read
Python MongoDB TutorialMongoDB is a popular NoSQL database designed to store and manage data flexibly and at scale. Unlike traditional relational databases that use tables and rows, MongoDB stores data as JSON-like documents using a format called BSON (Binary JSON). This document-oriented model makes it easy to handle com
2 min read
Python MySQLMySQL is a widely used open-source relational database for managing structured data. Integrating it with Python enables efficient data storage, retrieval and manipulation within applications. To work with MySQL in Python, we use MySQL Connector, a driver that enables seamless integration between the
9 min read
Python PackagesPython packages are a way to organize and structure code by grouping related modules into directories. A package is essentially a folder that contains an __init__.py file and one or more Python files (modules). This organization helps manage and reuse code effectively, especially in larger projects.
12 min read
Python ModulesPython Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work.In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we c
7 min read
Python DSA LibrariesData Structures and Algorithms (DSA) serve as the backbone for efficient problem-solving and software development. Python, known for its simplicity and versatility, offers a plethora of libraries and packages that facilitate the implementation of various DSA concepts. In this article, we'll delve in
15 min read
List of Python GUI Library and PackagesGraphical User Interfaces (GUIs) play a pivotal role in enhancing user interaction and experience. Python, known for its simplicity and versatility, has evolved into a prominent choice for building GUI applications. With the advent of Python 3, developers have been equipped with lots of tools and li
11 min read
Data Science with Python
NumPy Tutorial - Python LibraryNumPy (short for Numerical Python ) is one of the most fundamental libraries in Python for scientific computing. It provides support for large, multi-dimensional arrays and matrices along with a collection of mathematical functions to operate on arrays.At its core it introduces the ndarray (n-dimens
3 min read
Pandas TutorialPandas is an open-source software library designed for data manipulation and analysis. It provides data structures like series and DataFrames to easily clean, transform and analyze large datasets and integrates with other Python libraries, such as NumPy and Matplotlib. It offers functions for data t
6 min read
Matplotlib TutorialMatplotlib is an open-source visualization library for the Python programming language, widely used for creating static, animated and interactive plots. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, Qt, GTK and wxPython. It
5 min read
Python Seaborn TutorialSeaborn is a library mostly used for statistical plotting in Python. It is built on top of Matplotlib and provides beautiful default styles and color palettes to make statistical plots more attractive.In this tutorial, we will learn about Python Seaborn from basics to advance using a huge dataset of
15+ min read
StatsModel Library- TutorialStatsmodels is a useful Python library for doing statistics and hypothesis testing. It provides tools for fitting various statistical models, performing tests and analyzing data. It is especially used for tasks in data science ,economics and other fields where understanding data is important. It is
4 min read
Learning Model Building in Scikit-learnBuilding machine learning models from scratch can be complex and time-consuming. Scikit-learn which is an open-source Python library which helps in making machine learning more accessible. It provides a straightforward, consistent interface for a variety of tasks like classification, regression, clu
8 min read
TensorFlow TutorialTensorFlow is an open-source machine-learning framework developed by Google. It is written in Python, making it accessible and easy to understand. It is designed to build and train machine learning (ML) and deep learning models. It is highly scalable for both research and production.It supports CPUs
2 min read
PyTorch TutorialPyTorch is an open-source deep learning framework designed to simplify the process of building neural networks and machine learning models. With its dynamic computation graph, PyTorch allows developers to modify the networkâs behavior in real-time, making it an excellent choice for both beginners an
7 min read
Web Development with Python
Flask TutorialFlask is a lightweight and powerful web framework for Python. Itâs often called a "micro-framework" because it provides the essentials for web development without unnecessary complexity. Unlike Django, which comes with built-in features like authentication and an admin panel, Flask keeps things mini
8 min read
Django Tutorial | Learn Django FrameworkDjango is a Python framework that simplifies web development by handling complex tasks for you. It follows the "Don't Repeat Yourself" (DRY) principle, promoting reusable components and making development faster. With built-in features like user authentication, database connections, and CRUD operati
10 min read
Django ORM - Inserting, Updating & Deleting DataDjango's Object-Relational Mapping (ORM) is one of the key features that simplifies interaction with the database. It allows developers to define their database schema in Python classes and manage data without writing raw SQL queries. The Django ORM bridges the gap between Python objects and databas
4 min read
Templating With Jinja2 in FlaskFlask is a lightweight WSGI framework that is built on Python programming. WSGI simply means Web Server Gateway Interface. Flask is widely used as a backend to develop a fully-fledged Website. And to make a sure website, templating is very important. Flask is supported by inbuilt template support na
6 min read
Django TemplatesTemplates are the third and most important part of Django's MVT Structure. A Django template is basically an HTML file that can also include CSS and JavaScript. The Django framework uses these templates to dynamically generate web pages that users interact with. Since Django primarily handles the ba
7 min read
Python | Build a REST API using FlaskPrerequisite: Introduction to Rest API REST stands for REpresentational State Transfer and is an architectural style used in modern web development. It defines a set or rules/constraints for a web application to send and receive data. In this article, we will build a REST API in Python using the Fla
3 min read
How to Create a basic API using Django Rest Framework ?Django REST Framework (DRF) is a powerful extension of Django that helps you build APIs quickly and easily. It simplifies exposing your Django models as RESTfulAPIs, which can be consumed by frontend apps, mobile clients or other services.Before creating an API, there are three main steps to underst
4 min read
Python Practice
Python QuizThese Python quiz questions are designed to help you become more familiar with Python and test your knowledge across various topics. From Python basics to advanced concepts, these topic-specific quizzes offer a comprehensive way to practice and assess your understanding of Python concepts. These Pyt
3 min read
Python Coding Practice ProblemsThis collection of Python coding practice problems is designed to help you improve your overall programming skills in Python.The links below lead to different topic pages, each containing coding problems, and this page also includes links to quizzes. You need to log in first to write your code. Your
1 min read
Python Interview Questions and AnswersPython is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read