0% found this document useful (0 votes)
4 views

Report of Python (1.) (1)

The document is a comprehensive guide to Python programming, covering topics such as syntax, data types, control structures, functions, collections, object-oriented programming, file handling, and modules. It includes practical examples and explanations of key concepts, making it suitable for beginners and those looking to enhance their Python skills. Additionally, it outlines a task to build an ATM machine interface and provides interview questions related to Python.

Uploaded by

ravithejayg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Report of Python (1.) (1)

The document is a comprehensive guide to Python programming, covering topics such as syntax, data types, control structures, functions, collections, object-oriented programming, file handling, and modules. It includes practical examples and explanations of key concepts, making it suitable for beginners and those looking to enhance their Python skills. Additionally, it outlines a task to build an ATM machine interface and provides interview questions related to Python.

Uploaded by

ravithejayg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Python

Table Of Content

1. Introduction to Python

2. Python Syntax and Semantics

3. Variable and Data Types

4. Basic Operations

5. Control Structures

6. Functions

7. Collections

8. Object-Oriented Programming (OOP)

9. File Handling

10. Modules and Packages

11. Exception Handling

12. Advanced Topics

13. My Task (To build an ATM Machine Interface)

14. Interview questions

15. Conclusion

Page | 1
Python

1. Introduction to Python

Python is a high-level, interpreted programming language known for its simplicity and
readability. It was created by Guido van Rossum and first released in 1991. Python is open-
source and has a large community, making it a versatile tool for many programming tasks
including web development, data analysis, artificial intelligence, and scientific computing.

Key Features:

❖ Easy to Read, Learn, and Write: Python has a simple syntax similar to English,
making it an excellent choice for beginners.

❖ Open Source: python is free and open source , meaning the source code is also free
and open.

❖ Interpreted Language: Python is executed line by line at runtime, which makes


debugging easier.

❖ Dynamically Typed: No need to declare the type of variable; the type is determined
at runtime.

❖ Extensive Libraries and Frameworks:

Python has a rich standard library and many third-party modules and frameworks.

❖ Interactive Mode:
Python has support for an interactive mode which allows interactive testing and
debugging of snippets of code.

❖ Portable:
Python can run on a wide variety of hardware platforms and has the same interface
on all platforms.

Page | 2
Python

❖ Extendable:
You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.

❖ Databases:
Python provides interfaces to all major commercial databases.

❖ GUI Programming:
Python supports GUI applications that can be created and ported to many system
calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X
Window system of Unix.

❖ Scalable:
Python provides a better structure and support for large programs than shell
scripting.

Scripting Language:

A scripting or script language is a programming language that supports scripts,


programs written for a special run-time environment that automate the execution of
tasks that could alternatively be executed one-by-one by a human operator.

Scripting languages are often interpreted (rather than compiled). Primitives are
usually the elementary tasks or API calls, and the language allows them to be
combined into more complex programs. Environments that can be automated
through scripting include software applications, web pages within a web browser,
the shells of operating systems (OS), embedded systems, as well as numerous
games.

A scripting language can be viewed as a domain-specific language for a particular


environment; in the case of scripting an application, this is also known as an
extension language. Scripting languages are also sometimes referred to as very
high-level programming languages, as they operate at a high level of abstraction, or
as control languages.

2. Python Syntax and Semantics


Hello World:

The simplest Python program prints "Hello, World!" to the console.

Comments:

Page | 3
Python

Comments are used to explain code. Single-line comments start with #, and multi-line
comments are enclosed in triple quotes (''' or """).

3. Variables and Data Types


Variables:

Variables are used to store data. Python's variables do not require explicit declaration
to reserve memory space.

Data Types:

Page | 4
Python

• Integer (int): Whole numbers

• Float (float): Decimal numbers

• String (str): Sequence of characters

• Boolean (bool): True or False


• NoneType (None): Represents the absence of value

4. Basic Operations
Arithmetic Operators:

Comparison Operators:

Compare values and return a boolean.

Page | 5
Python

Logical Operators:

Combine conditional statements.

5. Control Structures

Conditional Statements:

Execute a code based on conditions.

Page | 6
Python

Loops:
For Loop:

Iterates over a sequence.

While Loop:

Repeats as long as a condition is true.

Page | 7
Python

6. Functions
Functions are reusable blocks of code that perform a specific task.

Defining a Function:

def greet(name):

return(f”Hello,{name}!”)

Calling a Function:

message = greet("Bob")
print(message) # Outputs: Hello, Bob!

Parameters and Arguments:

Functions can accept parameters and return values.

def add(a, b):


return a + b

result = add(5, 3)

print(result) # Outputs: 8

Lambda Functions:

Anonymous functions defined with the lambda keyword.


square = lambda x: x ** 2

print(square(5)) # Outputs: 25

Page | 8
Python

7. Collections
Python provides several built-in collection data types for managing groups of data.

Or Single “variable” used to store multiple values.

List:

The list is a most versatile datatype available in Python which can be written as a list
of comma- separated values (items) between square brackets. Important thing about a
list is that items in a list need not be of the same type.

Creating a list is as simple as putting different comma-separated values between


square brackets. For example − list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1,
2, 3, 4, 5 ]; list3 = ["a", "b", "c", "d"];

Similar to string indices, list indices start at 0, and lists can be sliced, concatenated
and so on.

Accessing Values in Lists:

To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index.

For example − list1 = ['physics', 'chemistry', 1997, 2000];

list2 = [1, 2, 3, 4, 5, 6, 7 ];

print ("list1[0]: ", list1[0] )

print( "list2[1:5]: ", list2[1:5] )

Output: list1[0]: physics


list2[1:5]: [2, 3, 4, 5]

Update: list = ['physics', 'chemistry', 1997, 2000];

Print( "Value available at index 2 : ")

Print (list[2] list[2] = 2001);

print("New value available at index 2 : " )

print (list[2])

Output: Value available at index 2 :

1997 New value available at index 2 :


2001

Page | 9
Python

Delete: list1 = ['physics', 'chemistry', 1997, 2000];

print (list1 del list1[2]);

print ("After deleting value at index 2 : ")


print (list1['physics', 'chemistry', 1997, 2000])

Output: After deleting value at index 2 :

['physics', 'chemistry', 2000]

Example: fruits = ["apple", "banana", "cherry"]

fruits.append("orange")

print(fruits) # Outputs: ['apple', 'banana', 'cherry', 'orange']

print(fruits[0]) #Output: [‘apple’]


print(fruits[0:2]) #Output: [‘apple’,’banana’,’cherry’,’orange’]

Basic List Operation :

Python Expression Results Description

len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] True Membership

for x in [1, 2, 3]: print x, 123 Iteration

Built-in List Functions & Methods:

Page | 10
Python

SN Function with Description

1 cmp(list1, list2) Compares elements of both lists.

2 len(list) Gives the total length of the list.

3 max(list) Returns item from the list with max value.

4 min(list) Returns item from the list with min value.

5 list(seq) Converts a tuple into list

Python includes following list methods :

SN Methods with Description

1 list.append(obj) Appends object obj to list

2 list.count(obj) Returns count of how many times obj occurs in list

3 list.extend(seq) Appends the contents of seq to list

4 list.index(obj) Returns the lowest index in list that obj appears

5 list.insert(index, obj) Inserts object obj into list at offset index

6 list.pop(obj=list[-1]) Removes and returns last object or obj from list

7 list.remove(obj) Removes object obj from list

8 list.reverse() Reverses objects of list in place

9 list.sort([func]) Sorts objects of list, use compare func if given

Page | 11
Python

Tuples:

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The
differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples
use parentheses.

Accessing Values in Tuples:

To access values in tuple, use the square brackets for slicing along with the index or indices
to obtain value available at that index.

For example − tup1 = ('physics', 'chemistry', 1997, 2000);

tup2 = (1, 2, 3, 4, 5, 6, 7 );

print( "tup1[0]: ",tup1[0] )

print( "tup2[1:5]: ", tup2[1:5])


When the above code is executed, it produces the following result − tup1[0]:

physics tup2[1:5]: [2, 3, 4, 5]

Basic Tuples Operations

Tuples respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new tuple, not a string. In fact, tuples respond to
all of the general sequence operations we used on strings in the prior chapter

Python Expression Results Description

len((1, 2, 3)) 3 Length

(1, 2, 3)+ (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!') * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition

3 in (1, 2, 3) True Membership

for x in (1, 2, 3): print x, 123 Iteration

Page | 12
Python

Built-in Tuple Functions:

Python includes the following tuple functions –

SN Function with Description

1 cmp(tuple1, tuple2) Compares elements of both tuples.

2 len(tuple) Gives the total length of the tuple.

3 max(tuple) Returns item from the tuple with max value.

4 min(tuple) Returns item from the tuple with min value.

5 tuple(seq) Converts a list into tuple.

Sets:

Unordered, mutable, and does not allow duplicate elements.

unique_numbers = {1, 2, 3, 2}
print(unique_numbers) # Outputs: {1, 2, 3}

ex:

# Creating a Set

set1 = set()

print(set1)

set1 = set("GeeksForGeeks")
print(set1)

# Creating a Set with the use of a List


set1 = set(["Geeks", "For", "Geeks"])

Page | 13
Python

print(set1)

# Creating a Set with the use of a tuple

tup = ("Geeks", "for", "Geeks")


print(set(tup))

# Creating a Set with the use of a dictionary

d = {"Geeks": 1, "for": 2, "Geeks": 3}

print(set(d))

Output:

set()
{'e', 'r', 'o', 'k', 'G', 's', 'F'}
{'For', 'Geeks'}

{'for', 'Geeks'}

{'for', 'Geeks'}

Dictionaries:

Unordered, mutable, and stores data in key-value pairs.

student = {"name": "Alice", "age": 21}


print(student["name"]) # Outputs: Alice

# Concession stand program using Dictionaries:

Page | 14
Python

Output:

Page | 15
Python

8. Object-Oriented Programming (OOP)


OOP is a programming paradigm based on the concept of "objects," which can
contain data and code to manipulate that data.

Classes and Objects:

• Class: A blueprint for creating objects.

• Object: An instance of a class.

Example:

class Dog:
def __init__(self, name, age):

self.name = name

self.age = age

def bark(self):

return f"{self.name} says woof!"

# Create an object

my_dog = Dog("Rex", 5)

print(my_dog.bark()) # Outputs: Rex says woof!

Inheritance:
Inheritance allows a class to inherit attributes and methods from another class.

class Animal:

def __init__(self, name):

self.name = name

def speak(self):

raise NotImplementedError("Subclasses must implement this method")

class Dog(Animal):
def speak(self):

Page | 16
Python

return f"{self.name} says woof!"

class Cat(Animal):

def speak(self):
return f"{self.name} says meow!"

# Create objects

dog = Dog("Rex")

cat = Cat("Whiskers")

print(dog.speak()) # Outputs: Rex says woof!

print(cat.speak()) # Outputs: Whiskers says meow!


Encapsulation:
Encapsulation restricts access to certain components of an object.

class Person:

def __init__(self, name, age):

self.__name = name # Private attribute

self.__age = age # Private attribute

def get_name(self):
return self.__name

def get_age(self):

return self.__age

person = Person("Alice", 30)

print(person.get_name()) # Outputs: Alice


Polymorphism:

Polymorphism allows methods to be used interchangeably between different object


types.

Page | 17
Python

class Bird:

def speak(self):

return "Chirp!"

class Duck(Bird):

def speak(self):

return "Quack!"

# Create objects

bird = Bird()

duck = Duck()

# Polymorphism

for animal in [bird, duck]:

print(animal.speak()) # Outputs: Chirp! Quack!

9. File Handling
Python provides built-in functions for reading and writing files.

Reading Files:

with open('example.txt', 'r') as file:


content = file.read()

print(content) # Outputs the content of example.txt

Writing Files:

with open('example.txt', 'w') as file:

file.write("Hello, file!")

Appending to Files:

with open('example.txt', 'a') as file:

file.write("\nAppending new line.")

Page | 18
Python

10. Modules and Packages


Introduction to Modules:

Modules are files containing Python code that can define functions, classes, and
variables. They can also include runnable code. Using modules helps in organizing
your code into manageable sections and promotes code reuse.

Importing Modules

You can import a module using the import statement.

import math

print(math.sqrt(16)) # Outputs: 4.0

Importing Specific Attributes

You can import specific attributes from a module using the from keyword.
from math import pi, sqrt

print(pi) # Outputs: 3.141592653589793

print(sqrt(25)) # Outputs: 5.0

Aliasing

Modules can be aliased using the as keyword.

import numpy as np

array = np.array([1, 2, 3])


print(array) # Outputs: [1 2 3]

Creating a Module

A module is simply a Python file with a .py extension.

# my_module.py

def greet(name):

return f"Hello, {name}!"

You can use the module in another file by importing it.


# main.py

import my_module

message = my_module.greet("Alice")
print(message) # Outputs: Hello, Alice!
Page | 19
Python

Introduction to Packages:

A package is a way of organizing related modules into a directory hierarchy. A


package must contain an __init__.py file.

Creating a Package

1. Create a directory for the package.

2. Add an __init__.py file to the directory.

3. Add modules to the package.


Directory structure:

mypackage/

__init__.py

module1.py

module2.py

Using a Package:

from mypackage import module1, module2

11. Exception Handling


Introduction to Exception Handling:

Exception handling is a mechanism to handle runtime errors, ensuring the flow of the
program can continue or gracefully terminate.

Try-Except Block

Handle exceptions using a try-except block.

try:

result = 10 / 0

except ZeroDivisionError:

print("Cannot divide by zero!")


Catching Specific Exceptions

You can catch specific exceptions and handle them differently.

try:

result = 10 / 0
except ZeroDivisionError:
Page | 20
Python

print("Cannot divide by zero!")

except TypeError:

print("Invalid type!")

Finally Block
The finally block is executed regardless of whether an exception occurred or not.

try:

file = open('example.txt', 'r')

content = file.read()

except FileNotFoundError:

print("File not found!")

finally:
file.close()
print("File closed.")

Raising Exceptions

You can raise exceptions using the raise keyword.

def divide(a, b):

if b == 0:

raise ValueError("Cannot divide by zero!")

return a / b

try:

print(divide(10, 0))

except ValueError as e:

print(e) # Outputs: Cannot divide by zero!

12. Advanced Topics


List Comprehensions:

List comprehensions provide a concise way to create lists.


squares = [x ** 2 for x in range(10)]

Page | 21
Python

print(squares) # Outputs: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Generators:

Generators are functions that return an iterable set of items, one at a time, using the
yield keyword.

def count_up_to(max):

count = 1

while count <= max:


yield count

count += 1

counter = count_up_to(5)

print(next(counter)) # Outputs: 1

print(next(counter)) # Outputs: 2

Decorators:
Decorators are functions that modify the behavior of other functions.

def my_decorator(func):

def wrapper():

print("Something is happening before the function is called.")

func()

print("Something is happening after the function is called.")

return wrapper

@my_decorator

def say_hello():

print("Hello!")

say_hello()

Context Managers:
Context managers allow you to allocate and release resources precisely when you
want.

Page | 22
Python

with open('example.txt', 'r') as file:

content = file.read()

print(content)

# The file is automatically closed after the block


Multithreading and Multiprocessing:

Python provides support for concurrent execution of code.

Multithreading:

import threading

def print_numbers():

for i in range(5):
print(i)

thread = threading.Thread(target=print_numbers)

thread.start()

thread.join()

Multiprocessing:

import multiprocessing

def print_numbers():

for i in range(5):

print(i)

process = multiprocessing.Process(target=print_numbers)

process.start()

process.join()

13. My Task (To Build an ATM Interface):


Source Code:

Page | 23
Python

Page | 24
Python

Source Code

1. Importing the Time Module

import time

• The time module is imported to introduce delays in the code execution using
time.sleep() function.

2. Printing Header Lines

print("======================================================")

print("======================================================")

• Two lines with equal signs are printed to create a visual separator or header.
3. Defining and Printing the Welcome Logo

Page | 25
Python

welcome_logo = """

............

"""

print(welcome_logo)
• A multi-line string welcome_logo contains an ASCII art representation of a welcome
message.

• The welcome logo is printed to the console.


4. Printing Footer Lines

print("======================================================")

print("======================================================")

• Two more lines with equal signs are printed to create another visual separator.

5. Prompting User to Insert Card

print("\n====------------------------- Please inert your Card ---------------------------


====")

time.sleep(5)

• A message prompts the user to insert their card.


• A delay of 5 seconds is introduced to simulate the time taken for card insertion.

6. Setting the ATM PIN and Initial Balance

password = 1010

balance = 10000

• The ATM PIN is set to 1010.

• The initial balance is set to 10,000.

7. Asking User for PIN Input

pin = int(input("\n\tEnter your ATM PIN: "))


• The user is prompted to enter their ATM PIN, which is converted to an integer.

8. Verifying the PIN

if pin == password:

• If the entered PIN matches the stored password (1010), the following block of code is
executed.
9. Displaying the ATM Menu

Page | 26
Python

while True:

print('''

1 : Check Balance

2 : Withdraw
3 : Deposit

4 : Exit

''')

• A while loop is used to repeatedly display the ATM menu until the user decides to
exit.

• The menu offers four options: Check Balance, Withdraw, Deposit, and Exit.

10. Handling User Selection with Exception Handling

try:

option = int(input("\tPlease select any one option: "))

• The user is prompted to select an option from the menu.


• The input is converted to an integer and wrapped in a try block to handle invalid
input.
11. Checking Balance Option

if option == 1:

print("___________________________________________________________")

print("***********************************************************")

print(f"\n\tYour current balance is {balance}")

print("___________________________________________________________")

print("***********************************************************")

• If the user selects option 1, their current balance is displayed.


12. Withdraw Option

if option == 2:

withdraw_amount = int(input("\n\tPlease enter your Withdraw Amount: "))

balance = balance - withdraw_amount

print("___________________________________________________________")
print("***********************************************************")

Page | 27
Python

print(f"\t{withdraw_amount} is debited from your account")

print("___________________________________________________________")

print("***********************************************************")

print("========================================================
===")

print("___________________________________________________________")

print("***********************************************************")

print(f"\tYour update current balance is {balance}")


print("___________________________________________________________")

print("***********************************************************")

• If the user selects option 2, they are prompted to enter the withdraw amount.

• The balance is updated by subtracting the withdraw amount.

• Messages are printed to confirm the transaction and display the updated balance.

13. Deposit Option

if option == 3:
deposit_amount = int(input("\n\tPlease enter your Deposit Amount: "))

balance = balance + deposit_amount

print("___________________________________________________________")

print("***********************************************************")

print(f"\t{deposit_amount} is credited to your account")

print("___________________________________________________________")

print("***********************************************************")

print("======================================================")

print("___________________________________________________________")
print("***********************************************************")

print(f"\tYour updated current balance is {balance}")

print("___________________________________________________________")
print("***********************************************************")

Page | 28
Python

• If the user selects option 3, they are prompted to enter the deposit amount.

• The balance is updated by adding the deposit amount.

• Messages are printed to confirm the transaction and display the updated balance.

14. Exit Option


if option == 4:

break

• If the user selects option 4, the while loop breaks, and the program exits.

15. Handling Invalid Input

except:

print("\tPlease enter a valid option between 1 to 4")

• If the user enters an invalid option (non-integer or out of range), an error message is
printed.

16. Incorrect PIN Handling

else:
print("\n\tPIN inserted by you is not correct")

• If the entered PIN does not match the stored password, an error message is displayed.

Output:

Page | 29
Python

14. Interview questions:

1. How will you improve the performance of a program in Python?

There are many ways to improve the performance of a Python program. Some of these are as
follows:

Data Structure: We have to select the right data structure for our purpose in a
Python program.

Standard Library: Wherever possible, we should use methods from standard


library. Methods implemented in standard library have much better
performance than user implementation.

Abstraction: At times, a lot of abstraction and indirection can cause slow

Performance of a program. We should remove the redundant abstraction in code.

Algorithm: Use of right algorithm can make a big difference in a program. We

have to find and select the suitable algorithm to solve our problem with

2. What are the benefits of using Python?

Python is strong that even Google uses it. Some of the benefits of using Python are as
follows:

i. Efficient: Python is very efficient in memory

management. For a large data set like Big Data, it is much

easier to program in Python.


ii. Faster: Though Python code is interpreted, still Python has very fast performance.

iii. Wide usage: Python is widely used among different

organizations for different projects. Due to this wide usage, there are thousands of
add-ons available for use with Python.

iv. Easy to learn: Python is quite easy to learn. This is the

biggest benefit of using Python. Complex tasks can be very easily implemented in
Python.

Page | 30
Python

3. How will you specify source code encoding in a Python source file?

By default, every source code file in Python is in UTF-8 encoding. But we can also specify
our own encoding for source files. This can be done by adding following line after #! line in
the source file.

# -*- coding: encoding -*-

In the above line we can replace encoding with the encoding that we want to use.

4. What is the use of PEP 8 in Python?

PEP 8 is a style guide for Python code. This document provides the coding conventions for
writing code in Python. Coding conventions are about indentation, formatting, tabs,
maximum line length, imports organization, line spacing etc. We use PEP 8 to bring
consistency in our code. We consistency it is easier for other developers to read the code.

5. What is Pickling in Python?


Pickling is a process by which a Python object hierarchy can be converted into a byte
stream. The reverse operation of Pickling is Unpickling.

Python has a module named pickle. This module has the implementation of a powerful
algorithm for serialization and de-serialization of Python object structure.

Some people also call Pickling as Serialization or Marshalling.


With Serialization we can transfer Python objects over the network. It is also used in
persisting the state of a Python object. We can write it to a file or a database.

6. How does memory management work in Python?

There is a private heap space in Python that contains all the Python objects and data
structures. In C, Python there is a memory manager responsible for managing the heap
space.

There are different components in Python memory manager that handle segmentation,
sharing, caching, memory pre-allocation etc.

Python memory manager also takes care of garbage collection by using Reference counting
algorithm.

Page | 31
Python

7. How will you perform Static Analysis on a Python Script?

We can use Static Analysis tool called PyChecker for this purpose. PyChecker can detect
errors in Python code.

PyChecker also gives warnings for any style issues.

Some other tools to find bugs in Python code are pylint and pyflakes.

8. What is the difference between a Tuple and List in Python?

In Python, Tuple and List are built-in data structures.

Some of the differences between Tuple and List are as follows:

I. Syntax: A Tuple is enclosed in parentheses:

E.g. myTuple = (10, 20, “apple”);

A List is enclosed in brackets: E.g. myList = [10, 20, 30];

II. Mutable: Tuple is an immutable data structure. Whereas, a List is


a mutable data structure.

III. Size: A Tuple takes much lesser space than a List in Python.

IV. Performance: Tuple is faster than a List in Python. So it gives us

good performance.

V. Use case: Since Tuple is immutable, we can use it in cases like

Dictionary creation. Whereas, a List is preferred in the use case

where data can alter.

9. What is a Python Decorator?

A Python Decorator is a mechanism to wrap a Python function and modify its behavior by
adding more functionality to it. We can use @ symbol to call a Python Decorator function.

Page | 32
Python

10. How are arguments passed in a Python method? By value or by reference?

Every argument in a Python method is an Object. All the variables in Python have reference
to an Object. Therefore arguments in Python method are passed by Reference.

Since some of the objects passed as reference are mutable, we can change those objects in a
method. But for an Immutable object like String, any change done within a method is not
reflected outside.

11. What is the difference between List and Dictionary data types in Python?

Main differences between List and Dictionary data types in Python are as follows:

I. Syntax: In a List we store objects in a sequence. In a Dictionary

we store objects in key-value pairs.

II. Reference: In List we access objects by index number. It starts


from 0 index. In a Dictionary we access objects by key specified at the time of Dictionary
creation.
III. Ordering: In a List objects are stored in an ordered sequence. In a

Dictionary objects are not stored in an ordered sequence.

IV. Hashing: In a Dictionary, keys have to be hashable. In a List there

is no need for hashing.

12. What are the different built-in data types available in Python?

Some of the built-in data types available in Python are as follows:


Numeric types: These are the data types used to represent numbers in Python.

int: It is used for Integers

long: It is used for very large integers of non-limited length.

float: It is used for decimal numbers.

complex: This one is for representing complex numbers

Sequence types: These data types are used to represent sequence of characters or objects.

str: This is similar to String in Java. It can represent a sequence of characters.

bytes: This is a sequence of integers in the range of 0-255.


byte array: like bytes, but mutable (see below); only available in Python 3.x list: This is a
sequence of objects.

Page | 33
Python

tuple: This is a sequence of immutable objects.

Sets: These are unordered collections.

set: This is a collection of unique objects.

frozen set: This is a collection of unique immutable objects.


Mappings: This is similar to a Map in Java.

dict: This is also called hashmap. It has key value pair to store information by using hashing.

13. What is a Namespace in Python?

A Namespace in Python is a mapping between a name and an object. It is currently


implemented as Python dictionary.

E.g. the set of built-in exception names, the set of built-in names, local names in a function

At different moments in Python, different Namespaces are created. Each Namespace in


Python can have a different lifetime.

For the list of built-in names, Namespace is created when Python interpreter starts.

When Python interpreter reads the definition of a module, it creates global namespace for that
module.

When Python interpreter calls a function, it creates local namespace for that function.

14. How will you concatenate multiple strings together in Python?


We can use following ways to concatenate multiple string together in Python:

I. use + operator:

E.g. >>> fname="John" >>> lname="Ray" >>> print fname+lname JohnRay

II. use join function:

E.g. >>> ''.join(['John','Ray']) 'JohnRay'

15. What is the use of Pass statement in Python?


The use of Pass statement is to do nothing. It is just a placeholder for a statement that is
required for syntax purpose. It does not execute any code or command.

Some of the use cases for pass statement are as follows:


I. Syntax purpose:

Page | 34
Python

>>> while True:

... pass # Wait till user input is received

II. Minimal Class: It can be used for creating minimal classes: >>> class MyMinimalClass:

... pass
III. Place-holder for TODO work:

We can also use it as a placeholder for TODO work on a function or code that needs to be
implemented at a later point of time.
>>> def initialization(): ... pass # TODO

16. What is the use of Slicing in Python?

We can use Slicing in Python to get a substring from a String. The syntax of Slicing is very
convenient to use.

E.g. In following example we are getting a substring out of the name John. >>> name="John"

>>> name[1:3] 'oh'

In Slicing we can give two indices in the String to create a Substring. If we do not give first
index, then it defaults to 0.

E.g. >>> name="John" >>> name[:2] 'Jo'

If we do not give second index, then it defaults to the size of the String. >>> name="John"

>>> name[3:] 'n

17. What is the difference between Docstring in Python and Javadoc in Java?

A Docstring in Python is a string used for adding comments or summarizing a piece of code
in Python.

The main difference between Javadoc and Docstring is that docstring is available during
runtime as well. Whereas, Javadoc is removed from the Bytecode and it is not present in
.class file.
We can even use Docstring comments at run time as an interactive help manual.

In Python, we have to specify docstring as the first statement of a code object, just after the
def or class statement.
The docstring for a code object can be accessed from the '__doc__' attribute of that object.

Page | 35
Python

18. How do you perform unit testing for Python code?

We can use the unit testing modules unittest or unittest2 to create and run unit tests for
Python code.

We can even do automation of tests with these modules. Some of the main components of
unittest are as follows:

I. Test fixture: We use test fixture to create preparation methods

required to run a test. It can even perform post-test cleanup.

II. Test case: This is main unit test that we run on a piece of code. We
can use Testcase base class to create new test cases.

III. Test suite: We can aggregate our unit test cases in a Test suite.

IV. Test runner: We use test runner to execute unit tests and produce

reports of the test run.

19. What is the difference between and Iterator and Iterable in Python?

An Iterable is an object that can be iterated by an Iterator. In Python, Iterator object provides
_iter_() and next() methods.

In Python, an Iterable object has _iter_ function that returns an Iterator object.

When we work on a map or a for loop in Python, we can use next() method to get an Iterable
item from the Iterator.

20. What is the use of Generator in Python?

We can use Generator to create Iterators in Python. A Generator is written like a regular
function. It can make use yield statement to return data during the function call. In this way
we can write complex logic that works as an Iterator.

A Generator is more compact than an Iterator due to the fact that _iter_() and next() functions
are automatically created in a Generator.

Also within a Generator code, local variables and execution state are saved between multiple
calls. Therefore, there is no need to add extra variables like self.index etc to keep track of
iteration.

Generator also increases the readability of the code written in Python. It is a very simple
implementation of an Iterator.

Page | 36
Python

21. What is the significance of functions that start and end with _ symbol in Python?

Python provides many built-in functions that are surrounded by _ symbol at the start and end
of the function name. As per Python documentation, double _ symbol is used for reserved
names of functions.

These are also known as System-defined names. Some of the important functions are:

Object._new_ Object._init_ Object._del_

22. What is the difference between xrange and range in Python?


In Python, we use range(0,10) to create a list in memory for 10 numbers.

Python provides another function xrange() that is similar to range() but xrange() returns a
sequence object instead of list object. In xrange() all the values are not stored simultaneously
in memory. It is a lazy loading based function.

But as per Python documentation, the benefit of xrange() over range() is very minimal in
regular scenarios.

As of version 3.1, xrange is deprecated.

23. What is lambda expression in Python?

A lambda expression in Python is used for creating an anonymous function. Wherever we


need a function, we can also use a lambda expression.
We have to use lambda keyword for creating a lambda expression. Syntax of lambda function
is as follows:

lambda argumentList: expression E.g. lambda a,b: a+b

The above mentioned lambda expression takes two arguments and returns their sum.

We can use lambda expression to return a function.

A lambda expression can be used to pass a function as an argument in another function.

24. How will you copy an object in Python?

In Python we have two options to copy an object. It is similar to cloning an object in Java.
I. Shallow Copy: To create a shallow copy we call copy.copy(x). In
a shallow copy, Python creates a new compound object based on

Page | 37
Python

the original object. And it tries to put references from the original

object into copy object.

II. Deep Copy: To create a deep copy, we call copy.deepcopy(x). In a

deep copy, Python creates a new object and recursively creates and inserts copies of the
objects from original object into copy object. In a deep copy, we may face the issue of
recursive loop due to infinite recursion.

25. What are the main benefits of using Python?

Some of the main benefits of using Python are as follows:


I. Easy to learn: Python is simple language. It is easy to learn for a

new programmer.

II. Large library: There is a large library for utilities in Python that

can be used for different kinds of applications.

III. Readability: Python has a variety of statements and expressions

that are quite readable and very explicit in their use. It increases the readability of overall
code.

IV. Memory management: In Python, memory management is built

into the Interpreter. So a developer does not have to spend effort on managing memory
among objects.

V. Complex built-in Data types: Python has built-in Complex data

types like list, set, dict etc. These data types give very good
performance as well as save time in coding new features.

26. What is a metaclass in Python?

A metaclass in Python is also known as class of a class. A class defines the behavior of an
instance. A metaclass defines the behavior of a class.

One of the most common metaclass in Python is type. We can subclass type to create our own
metaclass.

We can use metaclass as a class-factory to create different types of classes.

27. What is the use of frozenset in Python?

Page | 38
Python

A frozenset is a collection of unique values in Python. In addition to all the properties of set, a
frozenset is immutable and hashable.

Once we have set the values in a frozenset, we cannot change. So we cannot use and update
methods from set on frozenset.

Being hashable, we can use the objects in frozenset as keys in a Dictionary.

28. What is Python Flask?

Python Flask is a micro-framework based on Python to develop a web application.

It is a very simple application framework that has many extensions to build an enterprise
level application.

Flask does not provide a data abstraction layer or form validation by default. We can use
external libraries on top of Flask to perform such tasks.

29. What is None in Python?


None is a reserved keyword used in Python for null objects. It is neither a null value nor a
null pointer. It is an actual object in Python. But there is only one instance of None in a
Python environment.

We can use None as a default argument in a function.

During comparison we have to use “is” operator instead of “==” for None.

30. What is the use of zip() function in Python?

In Python, we have a built-in function zip() that can be used to aggregate all the Iterable
objects of an Iterator.

We can use it to aggregate Iterable objects from two iterators as well. E.g.

list_1 = ['a', 'b', 'c'] list_2 = ['1', '2', '3']

for a, b in zip(list_1, list_2): print a, b

Output:

a1 b2 c3

By using zip() function we can divide our input data from different sources into fixed number
of sets.

31. What is the use of // operator in Python?

Page | 39
Python

Python provides // operator to perform floor division of a number by another. The result of //
operator is a whole number (without decimal part) quotient that we get by dividing left
number with right number.

It can also be used floordiv(a,b).

E.g.

10// 4 = 2

-10//4 = -3

32. What is a Module in Python?


A Module is a script written in Python with import statements, classes, functions etc. We can
use a module in another Python script by importing it or by giving the complete namespace.

With Modules, we can divide the functionality of our application in smaller chunks that can
be easily managed.

33. How can we create a dictionary with ordered set of keys in Python?

In a normal dictionary in Python, there is no order maintained between keys. To solve this
problem, we can use OrderDict class in Python. This class is available for use since version
2.7.

It is similar to a dictionary in Python, but it maintains the insertion order of keys in the
dictionary collection.

34. Python is an Object Oriented programming language or a functional programming


language?

Python uses most of the Object Oriented programming concepts. But we can also do
functional programming in Python. As per the opinion of experts, Python is a multi-paradigm
programming language.

We can do functional, procedural, object-oriented and imperative programming with the help
of Python.

35. How can we retrieve data from a MySQL database in a Python script?

To retrieve data from a database we have to make use of the module available for that
database. For MySQL database, we import MySQLdb module in our Python script.

Page | 40
Python

We have to first connect to a specific database by passing URL, username, password and the
name of database.

Once we establish the connection, we can open a cursor with cursor() function. On an open
cursor, we can run fetch() function to execute queries and retrieve data from the database
tables.

36. What is the difference between append() and extend() functions of a list in Python?

In Python, we get a built-in sequence called list. We can call standard functions like append()
and extend() on a list.

We call append() method to add an item to the end of a list. We call extend() method to add
another list to the end of a list.

In append() we have to add items one by one. But in extend() multiple items from another list
can be added at the same time.

37. How will you handle an error condition in Python code?

We can implement exception handling to handle error conditions in Python code. If we are
expecting an error condition that we cannot handle, we can raise an error with appropriate
message.

E.g.

>>> if student_score < 0: raise ValueError(“Score can not be negative”)

If we do not want to stop the program, we can just catch the error condition, print a message
and continue with our program.

E.g. In following code snippet we are catching the error and continuing with the default value
of age.

#!/usr/bin/python try:

age=18+'duration' except:

print("duration has to be a number")

age=18 print(age)

38. What is the difference between split() and slicing in Python?


Both split() function and slicing work on a String object. By using split() function, we can get
the list of words from a String.

Page | 41
Python

E.g. 'a b c '.split() returns [‘a’, ‘b’, ‘c’]

Slicing is a way of getting substring from a String. It returns another String. E.g. >>> 'a b
c'[2:3] returns b.

39. How will you check in Python, if a class is subclass of another class?

Python provides a useful method issubclass(a,b) to check whether class a is a subclass of b.

E.g. int is not a subclass of long >>> issubclass(int,long) False


bool is a subclass of int >>> issubclass(bool,int)

True.

40. How will you debug a piece of code in Python?

In Python, we can use the debugger pdb for debugging the code. To start debugging we have
to enter following lines on the top of a Python script.

import pdb pdb.set_trace()

After adding these lines, our code runs in debug mode. Now we can use commands like
breakpoint, step through, step into etc for debugging.

41. How do you profile a Python script?

Python provides a profiler called cProfile that can be used for profiling Python code.
We can call it from our code as well as from the interpreter.

It gives use the number of function calls as well as the total time taken to run the script.

We can even write the profile results to a file instead of standard out.

42. What is the difference between ‘is’ and ‘==’ in Python?

We use ‘is’ to check an object against its identity. We use ‘==’ to check equality of two
objects.

E.g.

>>> lst = [10,20, 20]

>>> lst == lst[:] True >>> lst is lst[:] False


43. How will you share variables acrossmodules in Python?

Page | 42
Python

We can create a common module with variables that we want to share.

This common module can be imported in all the modules in which we want to share the
variables.

In this way, all the shared variables will be in one module and available for sharing with any
new module as well.

44. How can we do Functional programming in Python?

In Functional Programming, we decompose a program into functions. These functions take


input and after processing give an output. The function does not maintain any state.

Python provides built-in functions that can be used for Functional programming. Some of
these functions are:

I. Map()

II. reduce()

III. filter()
Event iterators and generators can be used for Functional programming in Python.

45. What is the improvement inenumerate() function of Python?

In Python, enumerate() function is an improvement over regular iteration. The enumerate()


function returns an iterator that gives (0, item[0]).

E.g.

>>> thelist=['a','b']

>>> for i,j in enumerate(thelist):

... print i,j ...

0a
1b

46. How will you execute a Python script in Unix?

To execute a Python script in Unix, we need to have Python executor in

Unix environment.

In addition to that we have to add following line as the first line in a Python
script file.

Page | 43
Python

#!/usr/local/bin/python

This will tell Unix to use Python interpreter to execute the script.

47. What are the popular Python libraries used in Data analysis?
Some of the popular libraries of Python used for Data analysis are:

I. Pandas: Powerful Python Data Analysis Toolkit

II. SciKit: This is a machine learning library in Python.

III. Seaborn: This is a statistical data visualization library in Python.

IV. SciPy: This is an open source system for science, mathematics and

engineering implemented in Python.

48. What is the output of following code in Python?


>>> thelist=['a','b']

>>> print thelist[3:]

Ans: The output of this code is following:

[]

Even though the list has only 2 elements, the call to thelist with index 3

does not give any index error.

49. What is the output of following code in Python?

>>>name=’John Smith’

>>>print name[:5] + name[5:]

Ans: Output of this will be

John Smith

This is an example of Slicing. Since we are slicing at the same index, the

first name[:5] gives the substring name upto 5th location excluding 5th
location. The name[5:] gives the rest of the substring of name from the 5th

location. So we get the full name as output.

Page | 44
Python

50. If you have data with name of customers and their location, which data type will you
use to store it in Python?

In Python, we can use dict data type to store key value pairs. In this

example, customer name can be the key and their location can be the value

in a dict data type.

Dictionary is an efficient way to store data that can be looked up based on a

key.

Python Programs

1. Area of Rectangle

Output:

2. Area of Circle

Output:

Page | 45
Python

3. Factorial of a number

Output:

4. Neon number

Page | 46
Python

Output:

5. Reverse a String Output:

6. Strong Number

Page | 47
Python

Output:

7. Sunny Number

Output:

8. Vowels of String

Page | 48
Python

Output:

9. Pyramid Patterns in Python with Alphabet

n=5

alph = 65

for i in range(0, n):

print(" " * (n-i), end=" ")

for j in range(0, i+1):

print(chr(alph), end=" ")


alph += 1

alph = 65

print()

Output:

Page | 49
Python

AB

ABC

ABCD

ABCDE

10. Pyramid patterns in python with Numbers

def print_number_pyramid(rows):
for i in range(1, rows + 1):
# Print spaces
for j in range(rows - i):
print(" ", end="")
# Print numbers
for j in range(2 * i - 1):
print(j + 1, end="")
# Move to the next line after each row
print()

# Example usage
num_rows = 5
print_number_pyramid(num_rows)

Output:
1
123
12345
1234567
123456789

11. Inverted full pyramid patterns

# Function to print inverted full pyramid pattern


def inverted_full_pyramid(n):
# Outer loop for the number of rows
for i in range(n, 0, -1):
# Inner loop for leading spaces in each row
for j in range(n - i):
print(" ", end="")
# Inner loop for printing asterisks in each row

Page | 50
Python

for k in range(2*i - 1):


print("*", end="")
# Move to the next line after each row
print("")

# Set the value of n (number of rows)


n=5

# Call the function to print the inverted full pyramid


inverted_full_pyramid(n)

Output;
*********

*******
*****

***

12. Data Type in Python

a = 4 # integer
b = 4.5 # float

c = 4j # complex number

print(type(a))

print(type(b))
print(type(c))

Output:

<class 'int'>

<class 'float'>
<class 'complex'>

Page | 51
Python

15. Conclusion
In conclusion, Python is a versatile and powerful programming language that offers a
wide range of functionalities for developers of all levels. Its simplicity and readability
make it an ideal choice for beginners, while its extensive libraries and frameworks
make it suitable for complex applications and advanced users. Throughout this
training and internship, we have explored various aspects of Python, from basic
syntax and data types to more advanced topics such as object-oriented programming
and file handling.

Key Takeaways

• Simplicity and Readability: Python's clean and straightforward syntax makes it easy
to learn and write, reducing the likelihood of errors and improving maintainability.

• Dynamic Typing: The language's dynamic typing system allows for flexibility in
variable usage and reduces the need for explicit type declarations.

• Rich Standard Library: Python's extensive standard library and the availability of
numerous third-party libraries enable developers to accomplish a wide range of tasks
without reinventing the wheel.

• Versatile Application: Python's ability to support multiple programming paradigms,


including procedural, object-oriented, and functional programming, makes it suitable
for various types of projects, from web development and data analysis to artificial
intelligence and scientific computing.

• Community and Support: The large and active Python community provides
extensive resources, including documentation, tutorials, and forums, making it easier
to find solutions and improve skills.

Practical Experience

The hands-on experience gained during this training and internship has provided a
solid foundation in Python programming. By working on real-world projects and
solving practical problems, we have developed a deeper understanding of how to
apply Python in various contexts. This experience will undoubtedly be valuable in
future endeavors, whether in academic pursuits or professional careers.
Future Prospects

As Python continues to evolve and grow in popularity, mastering this language opens
up numerous opportunities in the tech industry. Its applications in emerging fields
such as machine learning, data science, and automation ensure that Python skills will
remain in high demand. Continuous learning and staying updated with the latest
advancements in Python and its ecosystem will be crucial for leveraging its full
potential.

Page | 52

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy