Table of Contents

Write a Python Program to Reverse an Array

Let’s say we are given a problem which requires the output of an array in the reverse order. [4,5,6,7,7,3,1]

Approach 1: Reverse an Array in Python

 # Taking Input, Splitting and Converting the input into Integer format
array=list(map(int, input().split()))

# use python reverse function to reverse the array
array.reverse()

#printing the output
print(*array, end= ‘ ‘)

Approach 2: Reverse an Array in Python

Return reverse of an array in integer format

number = input()

print(int(number)[::-1]))

Write a Program to Close an Application using Python Programming

Method 1: Using Subprocess and time modules

import subprocess
import time

# Replace "outlook.exe" with the path to the application you want to open
process = subprocess.Popen("outlook.exe")

# Wait for 5 seconds
time.sleep(5)

# Close the application
process.terminate()

Method 2: Using OS.system and time modules

import os
import time

# Replace "outlook.exe" with the path to the application you want to open
os.system("outlook.exe")

# Wait for 5 seconds
time.sleep(5)

# Close the application
os.system("TASKKILL /F /IM notepad.exe")

How to get current date using python

#Method 1:
from datetime import datetime
today = datetime.now().date()
print(today)

#Method 2:
from datetime import datetime
current_date = datetime.now().strftime('%Y%m%d')
print(current_date)

How to check or get all the attributes of an object

# import the module 
import os

#use dir method to list attributes of the module
dir(os)

How to Connect SQL Database using Python Programming Language

import pyodbc

# set up connection details
server = 'your_server_name'
database = 'your_database_name'
username = 'your_username'
password = 'your_password'

# establish connection
conn = pyodbc.connect(f'DRIVER={{ODBC Driver 17 for SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password}')

# create a cursor
cursor = conn.cursor()

# update query
update_query = '''
    UPDATE your_table_name
    SET your_column_name = your_new_value
    WHERE your_condition
'''

# execute query
cursor.execute(update_query)

# commit changes to database
conn.commit()

# close cursor and connection
cursor.close()
conn.close()


Use Python to run a Stored Procedure in the SQL Database

import pyodbc

# set up connection details
server = 'your_server_name'
database = 'your_database_name'
username = 'your_username'
password = 'your_password'

# establish connection
conn = pyodbc.connect(f'DRIVER={{ODBC Driver 17 for SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password}')

# create a cursor
cursor = conn.cursor()

# call stored procedure
cursor.execute("{CALL your_stored_procedure_name}")

# commit changes to database
conn.commit()

# close cursor and connection
cursor.close()
conn.close()

How to check Python Version

While building programs using python language you may have to know the version of python installed on your system. Here is how to check the version of python installed on your system.

Method 1

# run the following code on terminal of IDE or use CMD (Command Line) 
python --version

Method 2

# run the following code on terminal of IDE or use CMD (Command Line) 
python --V

How to Activate Python Virtual Environment in VS Code IDE

Let’s understand what is environment and why we need it ?

Environment generally consists of An Interpreter and Packages required to run the application or code.

We need it since it helps in keeping packages related to our application isolated and any version changes would not affect our application. So any project where your code might need external dependencies should be used with virtual environment.

To set up a virtual Python environment in VS Code terminal, you can follow these steps:

Open VS Code and open the integrated terminal by selecting “Terminal” from the menu bar and then selecting “New Terminal”.

You can install it by running the following command with python’s inbuilt library venv

py -m venv env_name

Or you can use virtualenv to setup the virtual environment as well. Incase you find any issues with above syntax then install third party module using following command:

pip install virtualenv

Type in the following command to check if you have virtualenv installed:

virtualenv --version

Next, create a new virtual environment by running the following command:

virtualenv myenv

This will create a new virtual environment named “myenv” in the current directory.

Activate the virtual environment by running the following command:

source myenv/bin/activate

You should see the name of the virtual environment in parentheses in your terminal prompt.

When you’re done working in the virtual environment, you can deactivate it by running the following command:

deactivate

Method 2:

  1. Open your terminal or command prompt.
  2. Install the virtualenv package using the following command
pip install virtualenv
  1. Navigate to the directory where you want to create the virtual environment.
  2. Create a new virtual environment using the following command:
python -m venv myenv

This will create a new virtual environment in a directory called myenv.
Activate the virtual environment using the following command:

myenv\Scripts\activate.bat

This will create a new virtual environment in a directory called myenv.
Activate the virtual environment using the following command:

myenv\Scripts\activate.bat

This will create a new virtual environment in a directory called myenv.
Activate the virtual environment using the following command:

myenv\Scripts\activate.bat

Create Virtual Environment in Python
Create Virtual Environment in Python

or Right click on $ activate file under Scripts and select copy Relative Path
Paste that on terminal and hit Enter to activate the virtual environment.

Once activated, the name of your virtual environment should appear in the terminal prompt, indicating that you are now working within the virtual environment.

You can now install any Python packages that you need for your project, and they will be installed only in the virtual environment.

To deactivate the virtual environment, simply type the following command in your terminal:

deactivate


If you find any difficult activating and don't see name of your virtual environment appearing in terminal prompt. then try below method to activate using Activate.ps1 file.

Sometimes you may see message like: Python virtual environment was successfully activated, even though "(venv_pred_model)" indicator may not be present in the terminal prompt. Learn more.

The activate.ps1 file is a PowerShell script that is used to activate a virtual environment in Python on

Windows.

When you activate a virtual environment, it modifies the PATH environment variable to ensure that the Python interpreter and any packages installed in the virtual environment are used instead of the global system installations. The activate.ps1 script sets up this environment by modifying the PATH and PSModulePath variables to include the virtual environment’s Scripts and Modules directories.

To activate a virtual environment using activate.ps1, you can navigate to the virtual environment’s Scripts directory and run the script with the .\activate.ps1 command. This will activate the virtual environment and modify the environment variables as described above.

Navigate to the virtual environment’s Scripts directory:

cd path\to\myenv\Scripts

Run the activate.ps1 script:

.\activate.ps1
  1. This will activate the virtual environment and modify the environment variables.

After running the activate.ps1 script, you should see the name of the virtual environment in the PowerShell prompt, indicating that you are now working within the virtual environment. You can now install any Python packages that you need for your project, and they will be installed only in the virtual environment.

The Activate.ps1 script is designed for PowerShell, and running it with the dot (.) operator is the correct way to activate the virtual environment in PowerShell.

. E:\PythonProjects\venv_flask\Scripts\Activate.ps1

Here’s a quick explanation:

  • The . operator is used to run scripts in the current scope, which is necessary for scripts to modify the environment variables in the current PowerShell session.
  • The Activate.ps1 script sets up the environment variables to make the virtual environment active.

Method 3:

To activate a virtual environment on Windows, you can run:
.\env\Scripts\activate

Once the virtual environment is activated, you should see the name of the environment in your command prompt. For example:

(env) C:\Users\homepc\Documents\Python Projects\SystemCleaner>

Here’s how you may try for it to work:

PS C:\Users\Pankaj\Documents\VSCODE> cd .\ML\Prediction_Models
PS C:\Users\Pankaj\Documents\VSCODE\ML\Prediction_Models> cd .\virt_prediction_model\Scripts
PS C:\Users\Pankaj\Documents\VSCODE\ML\Prediction_Models\virt_prediction_model\Scripts .\Activate.ps1

here’s how activated environment looks like:
(virt_prediction_model) PS C:\Users\Pankaj\Documents\VSCODE\Office\Celonis_Updated\virt_celonis\Scripts>


Method 4:

Just type the below command in terminal after the current location
py -m venv env_name

dir – use dir to check that new environment will show in the directory list

Common Errors While Installing Python Virtual Environment

Error: virtualenv : The term ‘virtualenv’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At line:1 char:1

  • virtualenv venv
  • ~~
    • CategoryInfo : ObjectNotFound: (virtualenv:String) [], CommandNotFoundException
    • FullyQualifiedErrorId : CommandNotFoundException

Method 1: You can install it by running the following command with python’s inbuilt library venv

py -m venv env_name

Incase you find any issues with above syntax then install third party module using following command:

pip install virtualenv

Error: Fatal error in launcher: Unable to create process using ‘”C:\Users\user\Documents\Python Projects\env_name\Scripts\python.exe” “C:\Users\user\Documents\Python Projects\env_name\Scripts\pip.exe” list’: The system cannot find the file specified.

Check that the pip executable is located in the virtual environment’s Scripts directory, i.e., "C:\Users\user\Documents\Python Projects\Scripts\pip.exe". If it is not, try reinstalling the virtual environment or reinstalling pip within the virtual environment using the command python -m ensurepip.

Error: activate.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at

Error running scripts is disabled on this system
Error Snapshot
Solution: The error message you received indicates that PowerShell is blocking the execution of the script "Activate.ps1" because the current execution policy does not allow the execution of scripts on your system.

PowerShell has an execution policy that controls the level of security around the execution of scripts. By default, the execution policy is set to "Restricted," which prevents the execution of any script, including those that are locally created.

To resolve the issue, you can change the execution policy to "RemoteSigned," which allows the execution of scripts that are signed by a trusted publisher or created locally. To do this, follow these steps:

Open PowerShell as an administrator.
Type the following command and press Enter: Set-ExecutionPolicy RemoteSigned
When prompted, type "Y" to confirm the change.
Try running the script again.
Note that changing the execution policy can make your system more vulnerable to malicious scripts, so you should only do this if you trust the source of the scripts you want to run. It's also a good practice to change the execution policy back to its default "Restricted" mode when you're done running your scripts.


OR


use the following command in terminal and press enter.

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted


Close and Reopen the VS Code.



Regenerate response

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted

Reinstall and reactivate python virtual environment

try re-installing the virtual environment from scratch. To do this, follow these steps:

  1. Deactivate the virtual environment by running the command deactivate.
  2. Delete the entire virtual environment directory, which should be named env_name.
  3. Create a new virtual environment using the command python -m venv env_name.
  4. Activate the new virtual environment using the command .\env_name\Scripts\activate.
  5. Install any necessary packages within the new virtual environment using pip

Module not installed error after Activating Virtual Environment

Let me explain this to you in more detail. When you create a virtual environment using virtualenv, it creates a new isolated Python environment with its own Python executable, package directory, and so on. This means that any packages that you install using pip within this virtual environment are installed only within that environment and not system-wide.

To use the packages installed within the virtual environment, you need to activate the virtual environment first. This sets up the necessary environment variables and paths to ensure that when you run Python or pip, it uses the packages installed within the virtual environment.

In your case, you had already activated the virtual environment by running virt_dup_image\Scripts\activate. This sets up the necessary environment variables to use the Python executable and packages installed within the virtual environment.

However, you still had an issue with the toml package (toml used as an example) not being recognized by your Python interpreter. This is because even though the virtual environment was activated, your code editor or IDE might still be using the system-wide Python interpreter instead of the one in the virtual environment.

To fix this, you need to tell your code editor or IDE to use the Python executable within the virtual environment. This can usually be done by selecting the interpreter within the virtual environment in your code editor or IDE settings. Once you have done this, your code editor or IDE should recognize the packages installed within the virtual environment, and you should no longer see any issues with missing packages.

I hope this explanation helps. Let me know if you have any further questions!

Check Current Working Directory of your Code


print(os.getcwd())

How to Change Flder Location in Terminal using Windows Commands

cd – use cd.. command to go one step behind or change the parent directory. The cd command is used to change the current working directory, and it does not take any arguments after the directory path.

dir – use dir command to list all the files and folders in the current location
cd ./FolderName to select the folder
syntax would be currentpath cd ./FolderName

ls – use ls command to list all the files and folders in the current location

How to update python version

Download and Install the latest Python version available from python.org

VS Code Error: You don’t have an extension for debugging Python. Should we find a Python Extension in the Marketplace?

Solution: In order to fix this issue on VS Code, you would need to install Python Extension, see the screenshots below

Click on Extensions Icon on left and Search for python.
Install Python Intellisense extension.
Close and Reopen VS Code to start debugging your code.


Error: Timed out waiting for debuggee to spawn in VS Code

In order to address the above issue, Select Command Palette from View menu list.
Type “Select Interpreter in Search Box”
Select The Python Interpreter and Click on Browser to locate python.exe file and select it.

Error: pip : The term ‘pip’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.

Solution:

his error message indicates that the pip command is not recognized by your system, which is likely because it is not installed or it is not added to the PATH environment variable.

pip is a package manager for Python packages, so it needs to be installed separately from Python. If you have not installed pip yet, you can download it from the official Python website (https://www.python.org/downloads/) and make sure to check the “Add Python to PATH” option during the installation process.

If you have installed pip but still get this error, it may be because the installation directory is not added to the PATH environment variable. You can add the directory that contains the pip executable to the PATH environment variable by following these steps:

  1. Open the Start menu and search for “Environment Variables”.
  2. Click on the “Edit the system environment variables” option.
  3. In the System Properties window, click on the “Environment Variables” button.
  4. In the Environment Variables window, scroll down to find the “Path” variable under System Variables, and click on the “Edit” button.
  5. Click on the “New” button and enter the directory path that contains the pip executable (for example, C:\Python39\Scripts if you installed Python 3.9).
  6. Click “OK” to close all the windows.

After adding the directory to the PATH environment variable, you can try running the pip command again in a new command prompt window.

Or

If you have already installed Python on your system but are still seeing the error message “pip : The term ‘pip’ is not recognized as the name of a cmdlet, function, script file, or operable program,” it’s possible that pip was not installed with the Python distribution.

You can try the following steps to check if pip is installed:

  1. Open a command prompt or terminal window.
  2. Type pip --version and press Enter.

If pip is installed on your system, you should see the version number displayed. If you see an error message such as “pip is not recognized as an internal or external command,” it means that pip is not installed on your system.

To install pip, you can follow these steps:

  1. Download the get-pip.py script from https://bootstrap.pypa.io/get-pip.py.
  2. Open a command prompt or terminal window.
  3. Navigate to the directory where you downloaded the get-pip.py script.
  4. Run the following command: python get-pip.py

This will install pip on your system. After installation, you should be able to use the pip command from the command prompt or terminal window.
Else, Restart your system and that should get it working for you.

Python’s dir() and help () function : How to inspect modules using dir() method

In Python, the dir() function is a built-in function that can be used to list all the attributes, i.e., classes, functions, variables, etc., of a module or an object.

To use the dir() function, simply call it with the name of the module or object that you want to inspect. For example, if you want to inspect the numpy module, you can call dir(numpy).

import numpy
print(dir(numpy)) # list all attributes of the numpy module

#output
['ALLOW_THREADS', 'AxisError', 'BUFSIZE', 'CLIP', 'ComplexWarning', 'DataSource', 'ERR_CALL', 'ERR_DEFAULT', 'ERR_IGNORE', 'ERR_LOG', 'ERR_PRINT', 'ERR_RAISE', 'ERR_WARN', 'FLOATING_POINT_SUPPORT', 'FPE_DIVIDEBYZERO', 'FPE_INVALID', 'FPE_OVERFLOW', 'FPE_UNDERFLOW', 'False_', 'Inf', 'Infinity', 'MAXDIMS', 'MAY_SHARE_BOUNDS', 'MAY_SHARE_EXACT', 'ModuleDeprecationWarning', 'NAN', 'NINF', 'NZERO', 'NaN', 'PINF', 'PZERO', 'RAISE', 'RankWarning', 'SHIFT_DIVIDEBYZERO', 'SHIFT_INVALID', 'SHIFT_OVERFLOW', 'SHIFT_UNDERFLOW', 'ScalarType', 'Tester', 'TooHardError', 'True_', 'UFUNC_BUFSIZE_DEFAULT', 'UFUNC_PYVALS_NAME', 'VisibleDeprecationWarning', 'WRAP', '_CopyMode', '_NoValue', '_UFUNC_API', '__NUMPY_SETUP__', '__all__', '__builtins__', '__cached__', '__config__', '__deprecated_attrs__', '__dir__', '__doc__', '__expired_functions__', '__file__', '__getattr__', '__git_version__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_add_newdoc_ufunc', '_distributor_init', '_financial_names', '_from_dlpack', '_globals', '_mat', '_pytesttester', '_version', 'abs', 'absolute', 'add', 'add_docstring', 'add_newdoc', 'add_newdoc_ufunc', 'alen', 'all', 'allclose', 'alltrue', 'amax', 'amin', 'angle', 'any', 'append', 'apply_along_axis', 'apply_over_axes', 'arange', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'argmax', 'argmin', 'argpartition', 'argsort', 'argwhere', 'around', 'array', 'array2string', 'array_equal', 'array_equiv', 'array_repr', 'array_split', 'array_str', 'asanyarray', 'asarray', 'asarray_chkfinite', 'ascontiguousarray', 'asfarray', 'asfortranarray', 'asmatrix', 'asscalar', 'atleast_1d', 'atleast_2d', 'atleast_3d', 'average', 'bartlett', 'base_repr', 'binary_repr', 'bincount', 'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'blackman', 'block', 'bmat', 'bool8', 'bool_', 'broadcast', 'broadcast_arrays', 'broadcast_shapes', 'broadcast_to', 'busday_count', 'busday_offset', 'busdaycalendar', 'byte', 'byte_bounds', 'bytes0', 'bytes_', 'c_', 'can_cast', 'cast', 'cbrt', 'cdouble', 'ceil', 'cfloat', 'char', 'character', 'chararray', 'choose', 'clip', 'clongdouble', 'clongfloat', 'column_stack', 'common_type', 'compare_chararrays', 'compat', 'complex128', 'complex256', 'complex64', 'complex_', 'complexfloating', 'compress', 'concatenate', 'conj', 'conjugate', 'convolve', 'copy', 'copysign', 'copyto', 'core', 'corrcoef', 'correlate', 'cos', 'cosh', 'count_nonzero', 'cov', 'cross', 'csingle', 'ctypeslib', 'cumprod', 'cumproduct', 'cumsum', 'datetime64', 'datetime_as_string', 'datetime_data', 'deg2rad', 'degrees', 'delete', 'deprecate', 'deprecate_with_doc', 'diag', 'diag_indices', 'diag_indices_from', 'diagflat', 'diagonal', 'diff', 'digitize', 'disp', 'divide', 'divmod', 'dot', 'double', 'dsplit', 'dstack', 'dtype', 'e', 'ediff1d', 'einsum', 'einsum_path', 'emath', 'empty', 'empty_like', 'equal', 'errstate', 'euler_gamma', 'exp', 'exp2', 'expand_dims', 'expm1', 'extract', 'eye', 'fabs', 'fastCopyAndTranspose', 'fft', 'fill_diagonal', 'find_common_type', 'finfo', 'fix', 'flatiter', 'flatnonzero', 'flexible', 'flip', 'fliplr', 'flipud', 'float128', 'float16', 'float32', 'float64', 'float_', 'float_power', 'floating', 'floor', 'floor_divide', 'fmax', 'fmin', 'fmod', 'format_float_positional', 'format_float_scientific', 'format_parser', 'frexp', 'frombuffer', 'fromfile', 'fromfunction', 'fromiter', 'frompyfunc', 'fromregex', 'fromstring', 'full', 'full_like', 'gcd', 'generic', 'genfromtxt', 'geomspace', 'get_array_wrap', 'get_include', 'get_printoptions', 'getbufsize', 'geterr', 'geterrcall', 'geterrobj', 'gradient', 'greater', 'greater_equal', 'half', 'hamming', 'hanning', 'heaviside', 'histogram', 'histogram2d', 'histogram_bin_edges', 'histogramdd', 'hsplit', 'hstack', 'hypot', 'i0', 'identity', 'iinfo', 'imag', 'in1d', 'index_exp', 'indices', 'inexact', 'inf', 'info', 'infty', 'inner', 'insert', 'int0', 'int16', 'int32', 'int64', 'int8', 'int_', 'intc', 'integer', 'interp', 'intersect1d', 'intp', 'invert', 'is_busday', 'isclose', 'iscomplex', 'iscomplexobj', 'isfinite', 'isfortran', 'isin', 'isinf', 'isnan', 'isnat', 'isneginf', 'isposinf', 'isreal', 'isrealobj', 'isscalar', 'issctype', 'issubclass_', 'issubdtype', 'issubsctype', 'iterable', 'ix_', 'kaiser', 'kernel_version', 'kron', 'lcm', 'ldexp', 'left_shift', 'less', 'less_equal', 'lexsort', 'lib', 'linalg', 'linspace', 'little_endian', 'load', 'loadtxt', 'log', 'log10', 'log1p', 'log2', 'logaddexp', 'logaddexp2', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'logspace', 'longcomplex', 'longdouble', 'longfloat', 'longlong', 'lookfor', 'ma', 'mask_indices', 'mat', 'math', 'matmul', 'matrix', 'matrixlib', 'max', 'maximum', 'maximum_sctype', 'may_share_memory', 'mean', 'median', 'memmap', 'meshgrid', 'mgrid', 'min', 'min_scalar_type', 'minimum', 'mintypecode', 'mod', 'modf', 'moveaxis', 'msort', 'multiply', 'nan', 'nan_to_num', 'nanargmax', 'nanargmin', 'nancumprod', 'nancumsum', 'nanmax', 'nanmean', 'nanmedian', 'nanmin', 'nanpercentile', 'nanprod', 'nanquantile', 'nanstd', 'nansum', 'nanvar', 'nbytes', 'ndarray', 'ndenumerate', 'ndim', 'ndindex', 'nditer', 'negative', 'nested_iters', 'newaxis', 'nextafter', 'nonzero', 'not_equal', 'numarray', 'number', 'obj2sctype', 'object0', 'object_', 'ogrid', 'oldnumeric', 'ones', 'ones_like', 'os', 'outer', 'packbits', 'pad', 'partition', 'percentile', 'pi', 'piecewise', 'place', 'poly', 'poly1d', 'polyadd', 'polyder', 'polydiv', 'polyfit', 'polyint', 'polymul', 'polynomial', 'polysub', 'polyval', 'positive', 'power', 'printoptions', 'prod', 'product', 'promote_types', 'ptp', 'put', 'put_along_axis', 'putmask', 'quantile', 'r_', 'rad2deg', 'radians', 'random', 'ravel', 'ravel_multi_index', 'real', 'real_if_close', 'rec', 'recarray', 'recfromcsv', 'recfromtxt', 'reciprocal', 'record', 'remainder', 'repeat', 'require', 'reshape', 'resize', 'result_type', 'right_shift', 'rint', 'roll', 'rollaxis', 'roots', 'rot90', 'round', 'round_', 'row_stack', 's_', 'safe_eval', 'save', 'savetxt', 'savez', 'savez_compressed', 'sctype2char', 'sctypeDict', 'sctypes', 'searchsorted', 'select', 'set_numeric_ops', 'set_printoptions', 'set_string_function', 'setbufsize', 'setdiff1d', 'seterr', 'seterrcall', 'seterrobj', 'setxor1d', 'shape', 'shares_memory', 'short', 'show_config', 'sign', 'signbit', 'signedinteger', 'sin', 'sinc', 'single', 'singlecomplex', 'sinh', 'size', 'sometrue', 'sort', 'sort_complex', 'source', 'spacing', 'split', 'sqrt', 'square', 'squeeze', 'stack', 'std', 'str0', 'str_', 'string_', 'subtract', 'sum', 'swapaxes', 'sys', 'take', 'take_along_axis', 'tan', 'tanh', 'tensordot', 'test', 'testing', 'tile', 'timedelta64', 'trace', 'tracemalloc_domain', 'transpose', 'trapz', 'tri', 'tril', 'tril_indices', 'tril_indices_from', 'trim_zeros', 'triu', 'triu_indices', 'triu_indices_from', 'true_divide', 'trunc', 'typecodes', 'typename', 'ubyte', 'ufunc', 'uint', 'uint0', 'uint16', 'uint32', 'uint64', 'uint8', 'uintc', 'uintp', 'ulonglong', 'unicode_', 'union1d', 'unique', 'unpackbits', 'unravel_index', 'unsignedinteger', 'unwrap', 'use_hugepage', 'ushort', 'vander', 'var', 'vdot', 'vectorize', 'version', 'void', 'void0', 'vsplit', 'vstack', 'warnings', 'where', 'who', 'zeros', 'zeros_like']

The dir() function will return a list of all the attributes of the module or object, sorted alphabetically. This list includes both built-in attributes and any user-defined attributes that are defined in the module or object.

help() function to get more information about a specific attribute or function

To get more information about a specific attribute, you can use the help() function. For example, if you want to get more information about the numpy.array function, you can call help(numpy.array).

By using the dir() and help() functions together, you can explore the classes, functions, and variables that are defined in a module and learn how to use them in your code. This can be especially helpful when working with large and complex libraries, such as NumPy, Pandas, or Matplotlib, where there are many classes and functions to choose from.

# Get help on the built-in function `zip`
help(zip)

#This will output a help message with a description of what the zip function does, as well as information on its parameters, return value, and any exceptions it might raise. Here's an example of the output you might see:

output#

Help on class zip in module builtins:

class zip(object)
 |  zip(*iterables) --> A zip object yielding tuples until an input is exhausted.
 |  
 |  Equivalent to:
 |      def zip(*iterables):
 |          sentinel = object()
 |          iterators = [iter(it) for it in iterables]
 |          while iterators:
 |              result = []
 |              for it in iterators:
 |                  elem = next(it, sentinel)
 |                  if elem is sentinel:
 |                      return
 |                  result.append(elem)
 |              yield tuple(result)
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)




ModuleNotFoundError: No module named ‘scripts’

When importing or selecting modules in Python, the interpreter searches for the module in the directories listed in sys.path. By default, the current working directory is not included in sys.path, which means that Python will not look for modules in the current directory unless you add it to the path explicitly.

To add the current directory to sys.path, you can use the sys.path.append() method. Here’s an example:

import sys
sys.path.append('.')

This will add the current directory to sys.path, allowing you to import modules from the current directory.

Alternatively, you can use the sys.path.insert() method to add the current directory to the beginning of sys.path, like this:

import sys
sys.path.insert(0, '.')

This will add the current directory to the beginning of sys.path, which means that Python will search for modules in the current directory before searching in other directories.

Once you have added the current directory to sys.path, you can import modules using the import statement, like this:

import module_name

You can also use the from ... import ... syntax to select specific functions or variables from a module, like this:

pythonCopy codefrom module_name import function_name, variable_name

Make sure that the module you are trying to import or select is located in the current directory and has the .py file extension.

from module_name import function_name, variable_name

If you still have trouble solving this issue then it could be

here’s an example of how you can add a custom module to sys.path:

Try running your script with the virtual environment activated, but without adding anything to sys.path. If the scripts module is installed in your virtual environment, Python should be able to find it without any additional configuration.

Let’s say you have a virtual environment located at C:\path\to\my_venv and you have a custom module called my_module located in the directory C:\path\to\my_project. To add my_project to sys.path, you can modify your Python script like this:

import sys
sys.path.insert(0, r'C:\path\to\my_project')

import my_module

# rest of your code here

This will insert the path to my_project at the beginning of sys.path, which means that Python will look for modules in that directory before looking in any other locations. Once the path is added to sys.path, you can import the my_module module like you would any other module.

Note that you should use sys.path.insert() instead of sys.path.append() if you want to prioritize a specific directory over other directories in sys.path. The 0 argument passed to sys.path.insert() tells Python to add the path at the beginning of sys.path. If you were to use sys.path.append(), the path would be added to the end of sys.path, which means that Python would look for modules in other locations before looking in your custom directory.

Let’s understand String Formatting in Python Language

String formatting is an essential aspect of programming in Python. It allows you to create dynamic and readable strings by substituting variables, expressions, or values into a pre-defined string format. There are several ways to format strings in Python, including %-formatting, str.format() method, f-strings, and template strings.

Using %-formatting: This is the oldest form of string formatting in Python, which uses the % operator to format strings. For example:

name = 'John'
age = 25
print('My name is %s and I am %d years old' % (name, age))

Using str.format() method: This method provides more flexibility and readability than %-formatting.

name = 'John'
age = 25
print('My name is {} and I am {} years old'.format(name, age))

Using f-strings (or formatted string literals): This is the newest and most preferred way of string formatting in Python 3.6 and above. It allows you to embed expressions inside string literals using curly braces {}.

name = 'John'
age = 25
print(f'My name is {name} and I am {age} years old')

Using Template strings: This method uses the string.Template class to substitute values in a string using placeholders

from string import Template
name = 'John'
age = 25
t = Template('My name is $name and I am $age years old')
print(t.substitute(name=name, age=age))

Use Case of ‘%’ string formatiing operator

#import the necessary modules 
import datetime

#define the number of days you want to subtract from the current date for example, subtract 7 days
days = 7

use the datetime.today() function to get the current date and subtract the specified number of days using the timedelta() function:

today_date = datetime.today().date() - datetime.timedelta(days=days)

#resulting today_date variable will be a datetime.date object representing the date that is days number of days before the current date.

year = today_date.year 
month = today_date.month
date = today_date.day

#These three lines of code extract the year, month, and day from the today_date variable using its year, month, and day attributes, respectively.

m = '%02d' % month
d = '%02d' % date

Two lines of code use the ‘%02d’ % syntax to format the month and date variables as two-digit strings with leading zeros if necessary. This ensures that the resulting strings are always two characters long, which can be useful for sorting or displaying dates in a consistent format.For example, if today_date is equal to datetime.date(2023, 3, 11), then after running this code, year will be 2023, m will be '03', and d will be '11'.

Let’s understand it in more detailed manner:

The syntax used to format the month and date variables as two-digit strings with leading zeros is called a string formatting operator. Specifically, it uses the % operator followed by a format specifier.

The format specifier used in this case is 02d, which specifies a field of width 2 characters and pads the value with leading zeros if necessary. Here’s a breakdown of the format specifier:

  • 0: specifies the character to use for padding (in this case, zero).
  • 2: specifies the width of the field to be formatted.
  • d: specifies that the value being formatted is an integer.

So when the code uses the syntax '%02d' % month, it’s telling Python to format the month variable as an integer with a field width of 2 characters, and to pad the value with leading zeros if necessary. For example, if month is equal to 3, then this code would produce the string '03'.

Similarly, when the code uses the syntax '%02d' % date, it’s telling Python to format the date variable as an integer with a field width of 2 characters, and to pad the value with leading zeros if necessary. For example, if date is equal to 11, then this code would produce the string '11'.

TOML: Pyproject.toml

Python TOML is a library for working with TOML (Tom’s Obvious, Minimal Language) files in Python. TOML is a configuration file format that is designed to be easy to read and write for both humans and machines.

The Python TOML library provides a simple way to load and manipulate TOML files in Python. It supports all of the features of the TOML format, including tables, arrays, and nested key-value pairs. It also provides helpful features like type inference and type checking to ensure that your TOML files are well-formed and consistent.

One example use case for Python TOML is in configuration files for Python applications. By using TOML files for configuration, you can keep your application settings organized and easy to read, and make it easy to update settings without having to modify code. For example, you might use a TOML file to store the settings for a web application, including things like the database connection string, the API key for a third-party service, and the server port number.

Here’s a simple example of how you might use Python TOML to load a configuration file:

import toml

# Load the configuration from a TOML file
config = toml.load("config.toml")

# Retrieve a setting from the configuration
database_url = config["database"]["url"]

In this example, we use the toml.load() function to load a TOML file named “config.toml”. We can then retrieve settings from the configuration by using key indexing on the config dictionary.

Overall, Python TOML is a powerful and flexible library for working with TOML files in Python, and is a great choice for anyone who needs to manage configuration settings for their Python applications.

TOML Error: TomlDecodeError

Exception has occurred: TomlDecodeError
Reserved escape sequence used (line 13 column 1 char 307) During handling of the above exception, another exception occurred:

Rootcause: The error message suggests that there is an issue with the escape sequences in line 13 of your TOML file, which contains the subject_I regular expression. The backslashes in the regular expression are used to escape special characters like parentheses and dollar signs.

In TOML, backslashes are also used for escaping characters. When a backslash is encountered in a TOML file, it is treated as the start of an escape sequence, which is a reserved syntax used to represent special characters.

Solution: To fix this error, you can use double backslashes to escape the special characters in your regular expression

Error: Code: 502 Msg: Couldn’t connect to TWS. Confirm that “Enable ActiveX and Socket EClients” is enabled and connection port is the same as “Socket Port” on the TWS “Edit->Global Configuration…->API->Settings” menu. Live Trading ports: TWS: 7496; IB Gateway: 4001. Simulated Trading ports for new installations of version 954.1 or newer: TWS: 7497; IB Gateway: 4002

RCA and Solution:

The error message suggests that the code is unable to connect to TWS (Trader Workstation) or IB Gateway, the trading platforms provided by Interactive Brokers.

The error message also provides some suggestions for resolving the issue. Here are some steps you can take to troubleshoot the problem:

  1. Check that the TWS or IB Gateway is running and connected to the Internet. Make sure that you have logged in and that the status bar at the bottom of the TWS or IB Gateway window indicates that you are connected.
  2. Check that the API settings in TWS or IB Gateway are configured correctly. Go to the “Edit” menu, select “Global Configuration”, then select “API” from the left-hand side menu. Make sure that the “Enable ActiveX and Socket EClients” option is enabled, and that the “Socket Port” is set to the correct value. If you are using live trading, the port should be 7496 for TWS and 4001 for IB Gateway. If you are using simulated trading, the port should be 7497 for TWS and 4002 for IB Gateway.
  3. Check that your code is using the correct port number. Make sure that the port argument in your code is set to the correct port number for the trading platform you are using (TWS or IB Gateway) and the type of trading you are doing (live or simulated).
  4. If you are using a firewall or antivirus software, make sure that it is not blocking the connection to TWS or IB Gateway. You may need to add an exception to your firewall or antivirus software to allow the connection.
  5. If none of the above steps work, try restarting your computer and then restarting TWS or IB Gateway. This can sometimes resolve connection issues.

If you are still unable to connect to TWS or IB Gateway after trying these steps, you may need to contact Interactive Brokers customer support for further assistance.

Python Regex: Regular Expression in Python

cheat sheet for regular expressions (regex) in Python:

Basic Syntax:

  • . matches any single character
  • [] matches any character inside the brackets
  • [^] matches any character NOT inside the brackets
  • * matches 0 or more occurrences of the previous character/group
  • + matches 1 or more occurrences of the previous character/group
  • ? matches 0 or 1 occurrence of the previous character/group
  • | matches either the expression before or after the symbol
  • () groups characters together

Anchors:

  • ^ matches the beginning of a string
  • $ matches the end of a string

Character Classes:

  • \d matches any digit (0-9)
  • \D matches any non-digit
  • \w matches any word character (a-z, A-Z, 0-9, and _)
  • \W matches any non-word character
  • \s matches any whitespace character (space, tab, newline, etc.)
  • \S matches any non-whitespace character

Quantifiers:

  • {n} matches exactly n occurrences of the previous character/group
  • {n,} matches at least n occurrences of the previous character/group
  • {n,m} matches between n and m occurrences of the previous character/group

Special Characters:

  • \ escapes a special character
  • . matches any character except newline
  • \b matches a word boundary
  • \B matches a non-word boundary
  • \n matches a newline character
  • \t matches a tab character

Flags:

  • re.I or re.IGNORECASE makes the regex case-insensitive
  • re.M or re.MULTILINE allows ^ and $ to match the beginning and end of each line (rather than just the whole string)
import re

# search for a pattern in a string
match = re.search(r'pattern', 'this is the string to search for the pattern')
if match:
    print('Found the pattern')

# find all occurrences of a pattern in a string
matches = re.findall(r'pattern', 'this is the string to search for the pattern')
print('Found', len(matches), 'occurrences of the pattern')

# replace all occurrences of a pattern with a new string
new_string = re.sub(r'pattern', 'replacement', 'this is the string to search for the pattern')
print('New string:', new_string)

# use flags
match = re.search(r'pattern', 'this is the string to search for the PATTERN', re.IGNORECASE)
if match:
    print('Found the pattern (case-insensitive)')

# use quantifiers
match = re.search(r'a{3,5}', 'aaabbbaaa')
if match:
    print('Found', match.group())

Here are a few websites similar to regexr.com for testing and learning regular expressions:

  1. Regexr – https://regexr.com/
  2. Regex101 – https://regex101.com/
  3. RegExr by gskinner – https://regexr.com/
  4. Regexpal – https://www.regexpal.com/
  5. RegexPlanet – https://www.regexplanet.com/
  6. Pythex – https://pythex.org/
  7. RegexOne – https://regexone.com/
  8. Debuggex – https://www.debuggex.com/
  9. Regex Tester – https://regex101.com/regex-tester/
  10. Regex Coach – http://www.weitz.de/regex-coach/

Error: Connection to smtp-out.domain.com requires verification of your systems domain.com status. This is done by a reverse DNS lookup against Domain or business primary DNS servers.’

Solution: It looks like you are trying to connect to the SMTP server smtp-out.domain.com, but the server requires verification that your system’s domain is authorized to send emails. This is typically done by performing a reverse DNS lookup on the IP address of your system and verifying that the domain name associated with the IP address matches the domain name in your email address.

To resolve this issue, you may need to contact the IT department or email administrator for your organization and ask them to verify that your system’s domain is authorized to send emails through the Companies SMTP server. They may need to update the DNS records for your domain or add your system’s IP address to a whitelist of authorized senders.

Alternatively, you could try using a different SMTP server that does not have domain verification requirements, or you could use a service like Gmail or Yahoo Mail to send your emails instead of using your organization’s SMTP server.

Reference Links:

  • https://packaging.python.org/en/latest/guides/installing-using-pip-and-virtual-environments/

By Pankaj

Leave a Reply

Your email address will not be published. Required fields are marked *