Monday, May 24, 2021

python - Strings

Strings: 

The string is a data type in Python. A string is a sequence of characters enclosed in quotes.

We can primarily, write a string in three ways:

Single quoted strings : a = ‘sri’

Double quoted strings : b = “sri”

Triple quoted strings : c = ‘’’ sri‘’’

String Slicing/Accessing Values in Strings:

To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. For example −

Index starts with 0 and goes till string (length - 1).

var1 = 'Hello World!'
var2 = "Python Programming"
print(var1[0]) # 1st character
print(var2[1:5]) # 2nd character to 4th one

output:

H

ytho

Negative Indices: Negative indices can also be used .-1 corresponds to the (length-1) index, -2 to (length-2).

var1 = 'Hello World!'
print(var1[-1])
print(var1[-8:])

output:

!

o World!

Slicing with skip value:

We can provide a skip value as a part of our slice like this:

word = “amazing”

print(word[1:6:2] )         # It will return ’mzn’


Other advanced slicing techniques:

word = ‘amazing’

word[:7] or word[0:7]      #It will return ‘amazing’

word[0:] or word[0:7]      #It will return ‘amazing’


String Functions:

Some of the mostly used functions to perform operations on or manipulate strings are:

len() function : It returns the length of the string.

len(‘harry’)               #Returns 5

endswith(“rry”) : This function tells whether the variable string ends with the string “rry” or not. If string is “harry”, it returns for “rry” since harry ends with rry.

count(“c”) : It counts the total number of occurrences of any character.

capitalize() : This function capitalizes the first character of a given string.

find(word) : This function finds a word and returns the index of first occurrence of that word in the string.

replace(oldword, newword) : This function replaces the old word with the new word in the entire string.

Escape Sequence Characters:

Sequence of characters after backslash ‘\’ [Escape Sequence Characters]

Escape Sequence Characters comprises of more than one character but represents one character when used within the string.

Examples: \n (new line), \t (tab), \’ (single quote), \\ (backslash), etc.

String Special Operators:

Assume string variable a holds 'Hello' and variable b holds 'Python', then −

Operator Description Example

+ Concatenation -

 Adds values on either side of the operator a + b will give HelloPython

* Repetition - 

Creates new strings, concatenating multiple copies of the same string a*2 will give -HelloHello

[] Slice - 

Gives the character from the given index a[1] will give e

[ : ] Range Slice - 

Gives the characters from the given range a[1:4] will give ell

in Membership - 

Returns true if a character exists in the given string H in a will give 1

not in Membership - 

Returns true if a character does not exist in the given string M not in a will give 1

r/R Raw String - 

Suppresses actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw string operator, the letter "r," which precedes the quotation marks. The "r" can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark. print r'\n' prints \n and print R'\n' prints \n

% Format - 

Performs String formatting.


String Formatting Operator:

One of Python's coolest features is the string format operator %. Following is a simple example −

print("My name is %s and my age is %d"%('srinanda',33))

output:

My name is srinanda and my age is 33

List of formatters:

Format Symbol Conversion

%c character

%s string conversion via str() prior to formatting

%i signed decimal integer

%d signed decimal integer

%u unsigned decimal integer

%o octal integer

%x hexadecimal integer (lowercase letters)

%X hexadecimal integer (UPPERcase letters)

%e exponential notation (with lowercase 'e')

%E exponential notation (with UPPERcase 'E')

%f floating point real number

%g the shorter of %f and %e

%G the shorter of %f and %E

Practice:

Write a program to fill in a letter template given below with name and date.

letter = ‘’’ Dear <|NAME|>,


                        You are selected!


                        <|DATE|>

from datetime import date
letter ='''Dear <|NAME|>,\n\tYoy are selected!\n<|DATE|>'''
name=input("Enter your Name:")
dt=str(date.today())
letter=letter.replace('<|NAME|>',name)
letter=letter.replace('<|DATE|>',dt)
print(letter)

output:

Enter your Name:srinanda

Dear srinanda,

        Yoy are selected!

2021-05-24

Write a program to detect double spaces in a string.

st="My name is  srinanda das"
resultst.find("  ")
temp = False
if(result != '-1'):
    temp=True
    print("It contains double spaces: ",temp)
else:
    print("It does not contain double spaces: ",temp)
if(temp == True):
    print("at position:",result).


python - Variables and Data Types

Variable: 

A variable is a name given to a memory location in a program. For example

a=30

b=”Sri”

c=71.22


Variable – Container to store a value

Keywords – Reserved words in Python

Identifiers – class/function/variable name


Data Types:

Python is a fantastic language that automatically identifies the type of data for us. Data types identifies which type of data a variable can store.

Primarily there are the following data types in Python:

Integers

Floating point numbers

Strings

Booleans

None

Example:

a = 71                                    #Identifies a as class<int>

b = 88.44                              #Identifies b as class<float>

name = “Sri”                  #Identifies name as class<Str>


Rules for defining a variable name: (Also applicable to other identifiers)

  • A variable name can contain alphabets, digits, and underscore.
  • A variable name can only start with an alphabet and underscore.
  • A variable can’t start with a digit.
  • No white space is allowed to be used inside a variable name.
  • Variable names are case sensitive.
  • We cant use reserved words as variable name.

Examples of few valid variable names,

Harry, harry, one8, _akki, aakash, harry_bro, etc.


Operators in Python

The following are some common operators in Python:

Arithmetic Operators (+, -, *, /, etc.)

Assignment Operators (=, +=, -=, etc.)

Comparison Operators (==, >=, <=, >, <, !=, etc.)

Logical Operators (and, or, not)


type() function and Typecasting

type function is used to find the data type of a given variable in Python.

a = 31

type(a)                      #class<int>

b = “31”

type(b)                      #class<str>

A number can be converted into a string and vice versa (if possible)

There are many functions to convert one data type into another.

Str(31)           # ”31” Integer to string conversion

int(“32”)       # 32 String to int conversion

float(32)       #32.0 Integer to float conversion

… and so on

Here “31” is a string literal and 31 is a numeric literal.


input() function

This function allows the user to take input from the keyboard as a string.

a = input(“Enter name”)               #if a is “harry”, the user entered harry

Note: The output of the input function is always a string even if the number is entered by the user.

Suppose if a user enters 34 then this 34 will automatically convert to “34” string literal.

To add quick single line comment press ctrl + forward slash

Practice:

Write a Python program to add two numbers.

a=20
b=30
print("the addition of a and b is:"a+b)

Write a Python program to find the remainder when a number is divided by Z(Integer).

a=24
b=11
print("the reminder is when a is divided by b :"a%b)

Check the type of the variable assigned using the input() function.

a=input("Please enter a number:")
print("the input type is:"type(a))

Please enter a number:23 the input type is: <class 'str'>

Use a comparison operator to find out whether a given variable a is greater than b or not. (Take a=34 and b=80)

a=34
b=80
print("checking if a is greater than b:"a>b)

checking if a is greater than b: False

Write a Python program to find the average of two numbers entered by the user.

a=input("Enter 1st number:")
b=input("Enter 2nd number:")
avg=(int(a)+int(b))/2
print("avearge of",a,"and ",b,"is :",avg)

Write a Python program to calculate the square of a number entered by the user.

a=int(input("Enter the number:"))
sqr=a*a
print("the square of the number",a,"is :",sqr)





Sunday, May 23, 2021

Python - Modules, Comments & Pip

 Open the vs code and first install python extension

Let’s write our very first python program.

Create a file called hello.py and paste the below code in it

print(“Hello World”)         => print is a function (more later)

Execute this file (.py file) by typing python hello.py and you will see Hello World printed on the screen.


Modules

A module is a file containing code written by somebody else (usually) which can be imported and used in our programs.

Pip

Pip is a package manager for python. You can use pip to install a module on your system.

E.g. pip install flask (It will install flask module in your system)


Types of modules

There are two types of modules in Python:

Built-in modules – Pre-installed in Python

External modules – Need to install using pip

Some examples of built-in modules are os, abc, etc.

Some examples of external modules are TensorFlow, flask, etc.


Using Python as a Calculator

We can use python as a calculator by typing “python” + TO DO on the terminal. [It opens REPL or read evaluation print loop]


Comments

Comments are used to write something which the programmer does not want to execute.

Comments can be used to mark author name, date, etc.


Types of Comments:

There are two types of comments in python,

Single line comments – Written using # (pound/hash symbol)

Multi-line comments – Written using ‘’’ Comment ‘’’ or “”” Comment “””.

Notes:

1. To print multiple lines in print function, you have to keep the multiple lines within the tripe quote  ''' or """.

print("""Twinkle, twinkle, little star,
How I wonder what you are.
Up above the world so high,
Like a diamond in the sky.
Twinkle, twinkle, little star,
How I wonder what you are!""")


2. How to import one external module and run on vs code:

https://pypi.org/project/playsound/

run pip install playsound

from playsound import playsound
playsound('C:\\Users\\Srinanda\\Desktop\\python\\1. Chapter 1\\play.mp3')

3. Always Use labels in comments

4. How to print the contents of a directory using os module:

import os

print(os.listdir())

or

import os

print(os.listdir('C://Users//Srinanda'))

python - pip install

Initially after the installation of python 3.9.5, I have checked that the pip is not installed by default in the python39\Scripts folder.

C:\Users\Srinanda\AppData\Local\Programs\Python\Python39\Scripts\

Need to do following steps to install the pip:

Step 1: Check if Pip is Already Installed

Pip is installed by default on many newer Python builds. To check and see if it is already installed on our system, open a command prompt and type the following command.

pip help

If Pip is installed, you will receive a message explaining how to use the program. If Pip is not installed, you will get an error message stating that the program is not found.

Step 2: Confirm that Python is installed.

The simplest way to test for a Python installation on your Windows server is to open a command prompt. Once a command prompt window opens, type python and press Enter. If Python is installed correctly, you should see output similar to what is shown below.

Python 3.9.5 (tags/v3.9.5:0a7dcbd, May  3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>>.

If you receive a message like:

Python is not recognized as an internal or external command, operable program or batch file.

Python is either not installed or the system variable path has not been set. You will need to either launch Python from the folder in which it is installed or adjust your system variables to allow Python to be launched from any location.

Step 3: Installing Pip on Windows

Once you have confirmed that Python is installed correctly, we can proceed with installing Pip.

Download get-pip.py file and store it in the same directory as python is installed.
C:\Users\Srinanda\AppData\Local\Programs\Python\Python39


Change the current path of the directory in the command line to the path of the directory where the above file exists.
cd C:\Users\Srinanda\AppData\Local\Programs\Python\Python39

Run the following command:

python get-pip.py

pip files will be store here 

C:\Users\Srinanda\AppData\Local\Programs\Python\Python39\Scripts


Step4: Add this path to system environment path if not added.

This PC - right click on it - Properties - advance system settings - Environment variables - path - edit and append  with ";C:\Users\Srinanda\AppData\Local\Programs\Python\Python39\Scripts"

Step 4: Verify Installation and Check the Pip Version

We can now verify that Pip was installed correctly by opening a command prompt and entering the following command.

pip -V

You should see output similar to the following:

C:\Users\Srinanda\AppData\Local\Programs\Python\Python39>pip -V

pip 21.1.2 from c:\users\srinanda\appdata\local\programs\python\python39\lib\site-packages\pip (python 3.9)

Reference: pip-install & Download-pip

python - Install required software and validation

Step1:  Search "python install" in Browser and download python 3.9.5(www.python.org)

during installation, 

  • checked the option - add python 3.9 to path
  • install now 
  • yes
  • close

Step2: Search "VS Code install" in browser. (IDE cum source code editor)code.visualstudio.com

For my case, its windows 64 bit. (my pc --> right click properties-->check 32/64 bit)

During installation,

  • I accept the agreement
  • check all the 4 options in delect additional sections
  • next 
  • install
  • uncheck launch vs code
  • finish

Step3: open windows power shell/CMD and validate as following:

>python

>>>exit()

>python --version

python 3.9.5

>pip






windows - dll file - api-ms-win-crt-runtime-l1-1-0.dll is missing

 For my case, While I have installed the python 3.9.5 and VS Code 1.56.2 software and trying to run python from windows power shell, I got this prompt "api-ms-win-crt-runtime-l1-1-0.dll is missing" issue.

Steps to resolve this error:

DOWNLOAD & INSTALL VISUAL C++ REDISTRIBUTABLE FOR VISUAL STUDIO 2015 MANUALLY:

  • Visit Microsoft Website’s Software Download Page.
  • Select the software language and Click on the ‘Download‘ button
  • Now, tick the system type x64 or x86 (As per your PC’s compatibility) and Click on ‘Next‘.The file should now start downloading. Once it is downloaded, double click on the .EXE file to run the program.
  • Now, follow the instructions that are being displayed on the screen. Once done, hit finish.

This method should fix api-ms-win-crt-runtime-l1-1-0.dll is missing error for sure.

Reference:

https://www.intenseclick.com/api-ms-win-crt-runtime-l1-1-0-dll-is-missing-error/

Thursday, May 20, 2021

OIC - ERP - xsl template to create control file BI report

Usecase: This xsl template is used to create a text file, comma separated csv file where we can use some xslt aggregator functions.

.xsl template:

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="2.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

xmlns:exslt="http://exslt.org/common"

xmlns:xdoxslt="http://www.oracle.com/XSL/Transform/java/oracle.xdo.template.rtf.XSLTFunctions"

xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>

<xsl:template match="/">

<xsl:text>REPORT_NAME</xsl:text>

<xsl:text>,</xsl:text>

<xsl:text>ROW_COUNT</xsl:text>

<xsl:text>,</xsl:text>

<xsl:text>TOTAL_AMOUNT</xsl:text>

<xsl:text>&#xa;</xsl:text>

<xsl:text>AP: BI_REPORT_NAME</xsl:text>

<xsl:text>,</xsl:text>

<xsl:value-of select="count(DATA_DS/G_1)"/>

<xsl:text>,</xsl:text>

<xsl:value-of select="sum(DATA_DS/G_1/PAID_AMOUNT)"/>

</xsl:template>

</xsl:stylesheet>


We can also use some format number functions as below:

format-number(count(DATA_DS/G_1)-1,'#')

format-number(count(DATA_DS/G_1[SUMD!=0),'#')

format-number(sum(DATA_DS/G_1/SUMD),'#.00')


Featured Post

11g to 12c OSB projects migration points

1. Export 11g OSB code and import in 12c Jdeveloper. Steps to import OSB project in Jdeveloper:   File⇾Import⇾Service Bus Resources⇾ Se...