Introduction to Python Programming Basics
Introduction to Python Programming Basics
Python is a high-level, interpreted programming language known for its simplicity and
readability. Created by Guido van Rossum in the late 1980s, Python supports code
readability and a clear syntax that allows programmers to express concepts in fewer lines of
code as compared to other languages.
1. Easy to Learn and Use: Python has a clean, simple, and small syntax that makes it
easy for beginners to understand and write code.
2. Versatile and Cross-Platform: Python can be used for a wide range of applications,
including web development, data analysis, scientific computing, artificial intelligence,
machine learning, automation, and more.
3. Interpreted and Interactive: Python is an interpreted language, which means that
the code is executed line by line without the need for explicit compilation.
4. Large Standard Library: Python comes with a comprehensive standard library that
provides a wide range of modules and functions for common tasks. It offers ready-to-
use modules for file I/O, networking, regular expressions, database access, and much
more, reducing the need for external dependencies.
5. Third-Party Ecosystem: Python has a thriving ecosystem of third-party libraries and
frameworks maintained by the community. These libraries extend Python’s
capabilities and offer specialized tools for specific domains, such as Django and Flask
for web development, NumPy and Pandas for data manipulation, TensorFlow and
PyTorch for machine learning, and many others.
6. Dynamic Typing: Python uses dynamic typing, which means that you don’t need to
explicitly declare variable types. The type of a variable is determined at runtime based
on the assigned value. This allows for flexibility and faster development but requires
attention to type-related issues.
Python Interview Questions for Freshers
Question 1: Tell something about Python ?
Answer: Python is a general-purpose, high-level, and interpreted programming
language. Python supports objects, modules, exception-handling, threads, and automatic
memory management which help in solving real-world problems with less coding.
NumPy is mainly used in data analysis, scientific calculations, and machine learning.
Pandas: This library is used for data manipulation and analysis. Pandas offers data structures
(such as DataFrames) and functions for cleaning, transforming and exploring structured data.
Matplotlib: This library for creating static, animated, and interactive visualizations in Python
from the data provided by the user. Matplotlib enables the creation of various plots, charts,
and graphs, making it a go-to choice for data visualization tasks.
TensorFlow: An open-source library for machine learning and deep learning. TensorFlow
provides a flexible ecosystem for building and deploying machine learning models, especially
neural networks. It is widely used in research, production-grade applications, and AI
development.
Scikit-learn: A machine learning library that offers a range of algorithms and tools for data
mining, classification, regression, clustering, and dimensionality reduction. Scikit-learn
simplifies the implementation of machine learning models and pipelines.
Beautiful Soup: A library for web scraping and parsing HTML/XML documents. Beautiful
Soup makes it easy to extract data from web pages, navigate the HTML/XML structure, and
scrape information for various applications.
PyTorch: PyTorch is designed to take advantage of GPUs for fast computation in deep
learning tasks. It provides a tensor library that enables efficient data storage and manipulation
on GPUs. PyTorch is widely used in developing and training neural networks.
And in the case of Interpreted language, an interpreter reads and executes the source code
line by line at runtime. The interpreter translates each line of code into machine code while
the program is running.
Ex-
Python provides a wide range of built-in modules that offer various functionalities like:
import math
value = [Link]
print("Value of Pi = : ",value)
Question 6: In python, arguments are passed by reference or value ?
Answer: In python, arguments are passed through reference. This means that when a
function is called and an argument is passed, a reference to the object is passed in place of the
value itself.
Output: 3
range() function in Python allows to create a sequence of numbers that can be used for
iteration. It can be used to create a range of numbers with a specified start, stop, and step
value.
[ i.e. range( start, stop, steps) ]
Code Ex –
for i in range(10):
print(i) #Output: 0 1 2 3 4 5 6 7 8 9
for j in range(0, 10, 2):
print(j) #Output: 0 2 4 6 8
Question 9: What is the difference between data structures like list, tuples, dictionaries
and sets in python ?
*args (pronounced “star args”) allows you to pass multiple number of arguments to a
function without specifying their names in advance. It collects all the arguments into a tuple,
which you can access within the function.
Run
def prac_function(*args):
for ARG in args:
print(ARG)
prac_function(1,2,3,4,5,6) #Output: 1 2 3 4 5 6
**kwargs (pronounced “star star kwargs”) allows you to pass multiple number of
keyword arguments to a function. Keyword arguments are like labeled items you put into the
bag. **kwargs collects these labeled items into a dictionary, where the labels (keywords)
become the keys and the values are the corresponding items.
Run
def prac_function(**kwargs):
for key, value in [Link]():
print(key, value)
prac_function(Name='Viraj', Age=22, City='Lucknow')
Question 12: What is Slicing ?
Answer: Slicing is a technique used to extract a part or a subsequence of a sequence, such as
a string, list, or tuple. It allows you to retrieve a specific range of elements or specific element
from the sequence based on indices.
Run
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sliced = my_list[2:6]
print(sliced) #Output: [3, 4, 5, 6]
sliced = my_list[-3:]
print(sliced) #Output: [8, 9, 10]
Question 13: What is the Lambda expressions in Python ? Explain with an example.
Answer:
Lambda expressions are a way to quickly create what are known as anonymous functions,
basically just, one-time-use functions that you don’t even really name. You just use them one
time and then never reference them again.
Code Ex-
Run
add = lambda x, y: x + y
result = add(20,15)
print(result) #Output: 35
PEP 8 is a guide that helps in writing clean, consistent, and maintainable Python code that is
easy to read and understand. It stands for Python Enhancement Proposal, it specifically
provides guidelines and recommendations on how to format and structure Python code to
enhance readability and reliability of the code.
Some key points of PEP 8 include:
.py files:
1. These files are compiled bytecode files generated by the Python interpreter.
2. They are not human-readable and cannot be edited directly.
3. The Python interpreter compiles the .py source code into bytecode and saves it as a
.pyc file for efficient execution in subsequent runs.
4. The .pyc files speed up the loading and execution of Python programs since the
interpreter can directly execute the bytecode without the need for recompilation.
Numeric Types:
dict: Represents a collection of key-value pairs (e.g., {‘name’: ‘John’, ‘age’: 25}).
Set Types:
Boolean Type:
None Type:
Pickling:
1. Pickling is the process of converting a Python object hierarchy into a byte stream.
2. It allows you to save the state of an object or a collection of objects as a file or
transfer it over a network.
3. The resulting byte stream can be stored persistently or transmitted between different
systems.
4. Pickling is commonly used for tasks like caching, serialization, and data persistence.
Unpickling:
Shallow Copy:
Shallow copy creates a new object and then copies the references of the original
object’s elements into the new object.
The new object and the original object share the same elements (references), so
changes made to one object may affect the other.
In a shallow copy, the top-level elements are copied, but the nested objects within
them are not duplicated.
Shallow copies are created using methods like slicing, the `copy()` method, or the
`copy` module.
Deep Copy:
Deep copy creates a new object and recursively copies all the elements and nested
objects of the original object.
The new object is completely independent of the original object, and any changes
made to one object do not affect the other.
Deep copies ensure that all levels of the object hierarchy are duplicated, including
nested objects and their references.
Deep copies are created using the `[Link]()` function from the `copy`
module.
Python OOPS Interview Questions
Question 21: List some common Python interpreters.
Answer:
1. CPython: The default and most widely used Python interpreter. It is written in C and
serves as the reference implementation for the Python language.
2. Jython: An implementation of Python that runs on the Java Virtual Machine (JVM).
It allows seamless integration with Java code and libraries.
3. IronPython: An implementation of Python targeting the .NET framework. It provides
integration with the .NET ecosystem and allows Python code to interact with .NET
languages and libraries.
4. PyPy: A fast and highly optimized implementation of Python. It utilizes a Just-in-
Time (JIT) compiler to improve execution speed.
5. Stackless Python: A variant of CPython that provides support for micro threads,
allowing lightweight concurrency without the need for traditional operating system
threads.
6. MicroPython: A lightweight implementation of Python specifically designed for
microcontrollers and embedded systems. It provides a reduced subset of the Python
language to optimize for limited resources.
Question 22: Write a program to produce the Fibonacci series in Python.
Answer:
Run
def fibonacci(n):
series = [ ]
a, b = 0, 1
while len(series) < n:
[Link](a)
a, b = b, a + b
return series
n = int(input("Enter number of terms in the Fibonacci series: "))
fibonacci_series = fibonacci(n)
print("Fibonacci series:", fibonacci_series)
Code Ex-
Run
Code Ex-
Run
#include<bits/stdc++.h>
using namespace std;
int main ()
{
int x = 5; // x is an integer
cout << x << endl;
x = "Hello";
cout << x << endl;
return 0;
}
1. Encapsulation:
Encapsulation is the process of hiding the internal implementation details of an object and
exposing only the necessary information. It helps in achieving data security and code
maintainability.
Ex-
Run
class Car:
Inheritance is a mechanism where a class inherits properties and methods from a parent class.
It allows code reuse and the creation of specialized classes based on more general classes.
Ex-
Run
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
print("Animal speaks.")
class Dog(Animal):
def speak(self):
print("Woof!")
my_dog = Dog("Buddy")
print(my_dog.name)
Output: Buddy
my_dog.speak() #Output: Woof!
3. Polymorphism:
Ex-
Run
class Shape:
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
[Link] = width
[Link] = height
def area(self):
return [Link] * [Link]
class Circle(Shape):
def __init__(self, radius):
[Link] = radius
def area(self):
return 3.14 * [Link] ** 2
shapes = [Rectangle(4, 5), Circle(3)]
for shape in shapes:
print([Link]())
4. Abstraction:
Abstraction involves representing essential features of an object while hiding the unnecessary
details. It allows programmers to work with high-level concepts without worrying about
implementation specifics.
Ex-
Run
Docstring is a string literal used to document modules, classes, functions, and methods. It
serves as a documentation tool to describe the purpose, behavior, parameters, return values,
and other important details of the code.
A docstring is enclosed in triple quotes (single or double) and is typically placed as the first
line after the definition of a module, class, function, or method. It can span multiple lines and
supports both single-line and multi-line docstrings.
Run
def hello(name):
"""
This function says hello to the person with the given name.
Parameters: name (str): The name of the person to be greeted.
Returns: str: A greeting message.
"""
return "Hello, " + name + " !!!!!"
print(hello("Isabelle"))
Question 30: What are python namespaces ? What are their applications ?
Answer:
Python uses namespaces to determine the scope of names. When you use a variable, function,
or any other object, Python looks for that name within the available namespaces to resolve it.
*
**
***
****
*****
Run
def pattern_print(rows):
for i in range(1, rows + 1):
print("*" * i)
# Take input from the user
rows = int(input("Enter the number of rows: "))
# Call the function to print the pattern
pattern_print(rows)
Question 33 : Python program to print following ‘*’ pattern:
****
***
**
*
Run
def pattern(rows):
for i in range(rows, 0, -1):
print("*" * i)
# Take input from the user
num_rows = int(input("Enter the number of rows: "))
# Call the function to print the pattern
pattern(num_rows)
Question 34 : Write a python program to perform bubble sort for given array.
Run
def bubble_sort(arr): # Bubble Sort Function
n = len(arr)
for i in range(n - 1):
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
numbers = input("Enter the List of numbers: ").split()
numbers = [int(num) for num in numbers]
bubble_sort(numbers) # Calling bubble sort function
print("Sorted list:", numbers) # Sorted List
Question 35 : Write a python program to perform merge sort for given array.
Run
def star_triangle(rows):
for i in range(1, rows + 1):
print(" " * (rows - i), end="")
print("*" * (2*i - 1))
num_rows = int(input("Enter the number of ROWS: "))
star_triangle(num_rows)
Question 38: What is PythonPath ?
PYTHONPATH is an environment variable in Python that tells the interpreter where to look
for Python modules and packages.
It is a list of directory paths separated by colons (on Unix-based systems) or semicolons (on
Windows). When you import a module or package, Python searches for it in the directories
listed in PYTHONPATH. It allows you to specify additional directories outside the default
ones where your Python code resides, enabling easy access to custom modules or packages.
Ex:
x = 10
def print_global():
print(x)
print_global()
# Output: 10
Local variables are declared within a function or block and can only be accessed within that
specific function or block. They have a local scope, meaning they are visible and accessible
only within their respective function or block.
Ex:
def print_local():
y = 20
print(y)
print_local()
# Output: 20
Question 40: Make a Binary search program in Python
Run
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
mid_value = arr[mid]
if mid_value == target:
return mid
elif mid_value < target:
low = mid + 1
else:
high = mid - 1
return -1
elements = input("Enter a list of numbers = ").split()
target = int(input("Enter the number to be searched = "))
arr = [int(element) for element in elements]
[Link]()
print("Sorted List =",arr)
index = binary_search(arr, target)
if index != -1:
print(f"{target} is at index {index}")
else:
print(f"{target} is not present in the list")
Python Interview Questions for Experienced
Question 41: Make a linear search program in python.
Run
Continue statement: When continue is used inside a loop, it tells Python to skip the current
iteration and move on to the next one. Any code after the continue statement within the loop
for that iteration will be ignored, and the loop will continue with the next iteration.
Break statement: When break is used inside a loop, it tells Python to immediately exit the
loop, regardless of any remaining iterations. Any code after the break statement within the
loop will be skipped, and the program will continue executing from the next statement after
the loop.
Pass statement: pass is used as a placeholder when you need to have a statement for
syntactic reasons, but you don’t want to do anything in that part of the code. It doesn’t do
anything and is mainly used to avoid syntax errors when you’re still working on
implementing certain parts of your code.
It contains data (in the form of attributes or properties) and behaviors (in the form of methods
or functions) that define the objects’ characteristics and actions. It provides a way to organize
related data and functions into a single unit.
An object, on the other hand, is an instance of a class. It represents a specific entity or item
created based on the class definition. Objects have their own unique state and can interact
with other objects or perform operations defined within the class.
1. remove(): Removes the first occurrence of a specific element from the array.
2. pop(): Removes and returns an element at a specified index from the array.
3. del statement: Deletes an element or a slice of elements from the array.
It is suitable for smaller projects, APIs, or situations where simplicity and control are desired.
Flask allows developers to have more control over the architecture and components they use
but lacks some of the built-in functionalities provided by Django.
Conclusion is that Django’s comprehensive feature set, strong community support, and
emphasis on convention-over-configuration make it a preferred choice for many web
development projects.
Question 49: Write the python code to perform Write and Read operation in Python ?
Run
1. Basic Syntax
2. DSA Based Coding
3. File Handling
4. Libraries
5. Supported Frameworks
.etc.
Question 2: In an Interview how do we explain why we chose Python ?
Due to its clean, simple and small syntax with Wide variety Libraries Support makes Python
easy – to – learn language. It is Dynamically Typed Languages which makes it more easier
language to understand.
Logged in as adinathhipparkar9. Edit your profile. Log out? Required fields are marked *