webounstraininghub.in

Edit Content
Click on the Edit Content button to edit/add the content.

Unlock Potential with Python Programming

Sharpen Skills, Ace Interviews

Python : Backend Development Interview Questions

Python is a high-level object-oriented programming language that is easy to use and understand. It is design
ed to develop apps and the web.

The benefits of Python are as follows:

  1. Speed
    and productivity
  2. Extensive Support for Libraries
  3. User-friendly Data Structures
  4. Existence of Third-Party Modules
  5. Easy Learning

The key features of Python are as follows-

  1. Interpreted Language
  2. Highly Portable
  3. Extensible
  4. GUI programming Support

Python is a Scripting language.

Some of the applications of Python are-

  1. GUI-based desktop applications
  2. Image processing applications
  3. Business and Enterprise applications
  4. Prototyping
  5. Web and web framework applications

List- The list is mutable (can be changed)
These lists’ performance is slower compared to lists

Syntax: list_1 = [20, ‘Mindmajix’, 30]

Tuple- A tuple is immutable (remains constant)
Tuple performance is faster when compared to lists

Syntax: tup_1 = (20, ‘Mindmajix’, 30)

It is a file that includes various sets of functions that we want to add to our applications

  1. Integer
  2. Complex numbers
  3. Floating-point numbers
  4. Strings
  5. Built-in functions

The three types of namespaces in python-

  1. Local namespace
  2. Global namespace
  3. Built-in namespace

Function is created by using the def statement.

Package is a collection of different modules.

Boolean is a built-in type in Python. It contains two values-

  1. True 
  2. False

It is a case-sensitive programming language.

init is a method or constructor in Python.

To modify the strings, Python’s “re” module is providing 3 methods. They are:

  1. split() – uses a regex pattern to “split” a given string into a list.
  2. sub() – finds all substrings where the regex pattern matches and then replaces them with a different string.
  3. subn() – it is similar to sub() and also returns the new string along with the no. of replacements.

A list is mutable, meaning you can add, remove, and modify elements in it, whereas a tuple is immutabl
e, meaning you cannot modify its elements once it is created. Additionally, lists are defined using square
brackets [], while tuples use parentheses ().

Python 2 and Python 3 are two different versions of the Python programming language. Python 3 was introduced to address certain shortcomings and improve the language. Some of the differences between the two include:

In Python 3, the print statement requires parentheses while in Python 2 it does not.
Python 3 has a different division operator (/) that performs true division, while Python 2 performs integer d
ivision.
Some Python 2 features, such as the x range function and the "raise exception, value" syntax, were remo
ved in Python 3.
Python 3 includes a number of performance improvements and security enhancements.

A decorator is a function that takes another function as input, adds some functionality to it, and returns it. Decorators are used to modify the behavior of a function without changing its source code. They are often used to add logging, caching, or authentication to a function.

A generator is a special type of function that can be used to create iterators. When a generator function is called, it returns a generator object, which can be used to iterate over a sequence of values. Unlike regular functions, generators do not return a value and instead use the "yield" keyword to return a value and pause the function execution until the next value is requested.

Duck typing is a programming concept that allows you to determine an object’s type based on its behavior, rather than its class or type. In Python, this means that you can use any object that provides the required methods and properties, regardless of its actual class or type. For example, you can use a string or a list interchangeably as long as they support the required methods, such as indexing or iteration.

Here are the main differences between .py and .pyc files:

.py files contain the main source code in plain text format, while .pyc files contain the compiled bytecode in
binary format.
.py files are human-readable and editable, while .pyc files are not meant to be edited directly.
.py files are interpreted by the Python interpreter at runtime, while .pyc files are pre-compiled and can be executed faster by the interpreter.
 If a .py file is modified, the Python interpreter will re-compile it to update the corresponding .pyc file. If the .pyc file is missing or outdated, the interpreter will automatically re-create it before executing the script.
.pyc files are platform-dependent, meaning that they are created and used only on the specific platform and Python version where they were generated. If you move a .pyc file to a different platform or Python version, it may not work correctly.

const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
const fs = require('fs');
const content = 'Some content!';
fs.writeFile('example.txt', content, (err) => {
if (err) {
console.error(err);
return;
}
console.log('File has been written');
});
const http = require('http');
http.get('http://example.com', (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
console.log(data);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
const express = require('express');
const app = express();
app.use(express.static('public'));
app.listen(3000, () => {
console.log('Server running on port 3000');
});
const express = require('express');
const app = express();
app.use(express.json());
app.post('/submit', (req, res) => {
const data = req.body;
res.send(`Received data: ${JSON.stringify(data)}`);
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
const express = require('express');
const app = express();
const customMiddleware = (req, res, next) => {
console.log('Middleware executed');
next();
};
app.use(customMiddleware);
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Home Page');
});
app.get('/about', (req, res) => {
res.send('About Page');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('Connected to the database');
});
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: String,
age: Number,
email: String
});
const User = mongoose.model('User', userSchema);
const express = require('express');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
const app = express();
app.post('/upload', upload.single('file'), (req, res) => {
res.send(`File uploaded: ${req.file.filename}`);
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
const express = require('express');
const app = express();
app.get('/', (req, res) => {
throw new Error('Something went wrong');
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
const express = require('express');
const session = require('express-session');
const app = express();
app.use(session({
secret: 'secret-key',
resave: false,
saveUninitialized: true,
cookie: { secure: false }
}));
app.get('/', (req, res) => {
if (req.session.views) {
req.session.views++;
res.send(`Views: ${req.session.views}`);
} else {
req.session.views = 1;
res.send('Welcome to the session demo. Refresh the page!');
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});How do you send JSON responses in Express.js?

const express = require('express');
const app = express();
app.use(express.json());

const items = [];

app.get('/items', (req, res) => {
res.json(items);
});

app.post('/items', (req, res) => {
const item = req.body;
items.push(item);
res.status(201).json(item);
});

app.put('/items/:id', (req, res) => {
const { id } = req.params;
const updatedItem = req.body;
items[id] = updatedItem;
res.json(updatedItem);
});

app.delete('/items/:id', (req, res) => {
const { id } = req.params;
items.splice(id, 1);
res.status(204).send();
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});

const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
const secretKey = 'your-secret-key';

app.use(express.json());

app.post('/login', (req, res) => {
const { username, password } = req.body;
if (username === 'admin' && password === 'password') {
const token = jwt.sign({ username }, secretKey, { expiresIn: '1h' });
res.json({ token });
} else {
res.status(401).send('Invalid credentials');
}
});

app.get('/protected', (req, res) => {
const token = req.headers['authorization'];
if (token) {
jwt.verify(token, secretKey, (err, decoded) => {
if (err) {
return res.status(401).send('Unauthorized');
}
res.json({ message: 'Protected content', user: decoded.username });
});
} else {
res.status(401).send('No token provided');
}
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});

const Koa = require('koa');
const app = new Koa();
app.use(ctx => {
ctx.body = 'Hello World';
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});

const Koa = require('koa');
const Router = require('koa-router');
const multer = require('@koa/multer');
const app = new Koa();
const router = new Router();
const upload = multer({ dest: 'uploads/' });

router.post('/upload', upload.single('file'), ctx => {
ctx.body = `File uploaded: ${ctx.file.filename}`;
});

app.use(router.routes());
app.listen(3000, () => {
console.log('Server running on port 3000');
});

const express = require('express');
const app = express();

app.get('/', (req, res) => {
res.send('Home Page');
});

app.use((req, res) => {
res.status(404).send('Page not found');
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});

const net = require('net');
const server = net.createServer((socket) => {
socket.write('Hello, client!');
socket.on('data', (data) => {
console.log('Received: ' + data);
});
socket.on('end', () => {
console.log('Client disconnected');
});
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});

const https = require('https');
const fs = require('fs');

const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};

https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('Hello, Secure World!\n');
}).listen(3000, () => {
console.log('Server running on port 3000');
});

const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 3000 });

server.on('connection', ws => {
ws.on('message', message => {
console.log('Received: ' + message);
});
ws.send('Hello, client!');
});

console.log('WebSocket server running on port 3000');

const express = require('express');
const rateLimit = require('express-rate-limit');

const app = express();
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});

app.use(limiter);
app.get('/', (req, res) => {
res.send('Hello, World!');
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});

const interval = setInterval(() => {
console.log('Task running every 2 seconds');
}, 2000);

setTimeout(() => {
clearInterval(interval);
console.log('Task stopped');
}, 10000);

const fetch = require('node-fetch');

const urls = [
'https://jsonplaceholder.typicode.com/posts/1',
'https://jsonplaceholder.typicode.com/posts/2',
'https://jsonplaceholder.typicode.com/posts/3'
];

Promise.all(urls.map(url => fetch(url).then(resp => resp.json())))
.then(results => {
console.log(results);
})
.catch(error => {
console.error('Error:', error);
});

const express = require('express');
const app = express();

const items = Array.from({ length: 100 }).map((_, index) => `Item ${index + 1}`);

app.get('/items', (req, res) => {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const startIndex = (page - 1) * limit;
const endIndex = page * limit;

const results = items.slice(startIndex, endIndex);
res.json({ page, limit, results });
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});

const nodemailer = require('nodemailer');

const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your-email@gmail.com',
pass: 'your-password'
}
});

const mailOptions = {
from: 'your-email@gmail.com',
to: 'recipient-email@gmail.com',
subject: 'Test Email',
text: 'This is a test email.'
};

transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error(error);
} else {
console.log('Email sent: ' + info.response);
}
});

const fs = require('fs');

const readStream = fs.createReadStream('input.txt');
const writeStream = fs.createWriteStream('output.txt');

readStream.pipe(writeStream);

readStream.on('end', () => {
console.log('Data has been copied');
});

const crypto = require('crypto');

const password = 'mysecretpassword';
const hash = crypto.createHash('sha256').update(password).digest('hex');

console.log('Hashed password:', hash);

process.on('SIGINT', () => {
console.log('Received SIGINT. Exiting...');
process.exit();
});

process.on('SIGTERM', () => {
console.log('Received SIGTERM. Exiting...');
process.exit();
});

console.log('Press Ctrl+C to exit');
setInterval(() => {}, 1000); // Keep the process running

Get in touch

We are here to help you & your business

We provide expert guidance, personalized support, and resources to help you excel in your digital marketing career.

Timing
9:00 am - 5:00 pm

    Book Your FREE  Digital Marketing Consultation

    +91 8005836769

    info@webounstraininghub.in