Back to Python
2026-01-115 min read

PSU Batch (Python Programming)

Learn PSU Batch (Python Programming) step by step with clear examples and exercises.

Title: PSU Batch (Python Programming) - Master Python for PSU Interviews and Beyond

Why This Matters

Python is a versatile, high-level programming language that's essential for many roles in the tech industry, particularly in Public Sector Undertakings (PSUs). With its clean syntax and readability, Python is an excellent choice for beginners and experienced programmers alike. In this lesson, we will guide you through the core concepts of Python programming, demonstrating practical examples that are relevant to PSU interviews and real-world projects.

Prerequisites

Before diving into Python, it's essential to have a basic understanding of the following topics:

  1. Familiarity with operating systems and file systems
  2. Basic mathematical concepts such as arithmetic operations, functions, and variables
  3. Understanding of data structures like lists, tuples, and dictionaries
  4. Knowledge of control flow statements (if-else, loops)
  5. Familiarity with basic input/output operations
  6. Experience working with command line interfaces in your operating system
  7. A text editor or Integrated Development Environment (IDE) for writing and running Python code

Core Concept

Python's syntax is designed to be easy to read and understand. Let's explore some key concepts:

Variables and Data Types

In Python, variables are used to store data. There are several built-in data types, including integers (int), floating-point numbers (float), strings (str), lists (list), tuples (tuple), and dictionaries (dict).

x = 10 # integer
y = 20.5 # float
z = "Hello, World!" # string
a = [1, 2, 3] # list
b = (4, 5, 6) # tuple
c = {"name": "John", "age": 30} # dictionary

Functions

Functions in Python are defined using the def keyword. A function takes one or more arguments and returns a value.

def add_numbers(x, y):
return x + y

result = add_numbers(5, 7)
print(result) # Output: 12

Control Flow Statements

Python provides several control flow statements to manage the flow of execution.

if-else Statement

x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")

Loops

Python offers two types of loops: for and while.

for loop

for i in range(10):

print(i)

while loop

i = 0

while i < 10:

print(i)

i += 1


### Modules and Libraries

Python has a vast ecosystem of modules and libraries that extend its functionality. Some commonly used libraries include NumPy, Pandas, Matplotlib, and Scikit-learn for data analysis and machine learning tasks.

import numpy as np # Import the NumPy library as np

array = np.array([1, 2, 3]) # Create a NumPy array

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

Worked Example

In this example, we'll create a simple Python script that reads data from a file, performs some operations, and writes the results back to a file.

Read data from a file

with open("data.txt", "r") as f:

lines = f.readlines()

Perform calculations on each line

results = []

for line in lines:

num1, num2 = map(int, line.split())

sum = num1 + num2

results.append(sum)

Write the results to a file

with open("output.txt", "w") as f:

for result in results:

f.write(str(result) + "\n")


In this example, we read lines from `data.txt`, split each line into two numbers, perform addition, and write the results to `output.txt`.

Common Mistakes

  1. Forgetting to close files: Always use the with open() as f: syntax to ensure that files are properly closed after use.
  2. Misunderstanding data types: Be aware of Python's automatic data type conversions, which can lead to unexpected results.
  3. Not handling exceptions: Properly handle exceptions to make your code more robust and avoid crashes.
  4. Ignoring indentation: Python uses whitespace for syntax, so ensure that your code is properly indented.
  5. Overcomplicating solutions: Keep your code clean and simple – avoid unnecessary complexity.
  6. Neglecting to import necessary libraries: Make sure you have the required libraries installed and imported before running your script.
  7. Forgetting to define functions before calling them: Ensure that all functions are defined before they are called in your code.

Practice Questions

  1. Write a function to find the sum of all numbers in a list.
  2. Write a script to sort a dictionary by its values.
  3. Implement a simple calculator that can perform addition, subtraction, multiplication, and division.
  4. Create a Python script to read a CSV file and calculate the total sales for each product.
  5. Write a function that finds the maximum number in a list.
  6. Implement a function that reverses a string.
  7. Write a script that calculates the factorial of a given number.
  8. Create a program that generates prime numbers up to a specified limit.
  9. Develop a Python script that reads a text file, counts the occurrences of each word, and writes the results to another file.
  10. Implement a function that finds the longest word in a string.

FAQ

Q: What is the difference between lists and tuples in Python?

A: Lists are mutable, meaning their elements can be changed, while tuples are immutable, meaning their elements cannot be changed.

Q: How do I handle exceptions in Python?

A: You can use a try-except block to catch and handle exceptions. For example:

try:

code that might raise an exception

except ExceptionType:

code to handle the exception


3. Q: Why does Python require indentation?
A: Python uses indentation to define blocks of code, such as loops and functions. This makes the code easier to read and understand.

4. Q: How do I create a new line in a string in Python?
A: You can use the `\n` character to create a new line in a string. For example:

my_string = "Hello\nWorld"

print(my_string) # Output: Hello

World (on a new line)


5. Q: What are modules and libraries in Python?
A: Modules are reusable pieces of code that perform specific tasks, while libraries are collections of related modules. Python has a vast ecosystem of modules and libraries that extend its functionality.

6. Q: How do I install additional libraries in Python?
A: You can use pip, the Python package manager, to install additional libraries. For example:

pip install numpy


7. Q: What is the purpose of the `with open() as f:` syntax when working with files in Python?
A: The `with open() as f:` syntax ensures that files are properly closed after use, even if an error occurs during execution. It simplifies file handling and helps prevent resource leaks.
PSU Batch (Python Programming) | Python | XQA Learn