Wednesday, June 30, 2021

Python - Inheritance & more on OOPs

 Inheritance is a way of creating a new class from an existing class.

Syntax:

class Emoloyee: #Base Class

#Code

class Programmer(Employee): #Derived or child class

#Code

We can use the methods and attributes of Employee in Programmer object. Also, we can overwrite or add new attributes and methods in the Programmer class.


Type of Inheritance:

  • Single inheritance
  • Multiple inheritance
  • Multilevel inheritance

Single Inheritance

Single inheritance occurs when child class inherits only a single parent class.

Base -> Derived


Multiple Inheritance:

Multiple inheritance occurs when the child class inherits from more than one parent class.

Multilevel Inheritance

When a child class becomes a parent for another child class.


Super() method

Super method is used to access the methods of a super class in the derived class.

super().__init__()  #Calls constructor of the base class


Class methods

A class method is a method which is bound to the class and not the object of the class.

@classmethod decorator is used to create a class method.

Syntax to create a class method:

@classmethod

def (cls, p1, p2):

#code

@property decorators

Consider the following class

class Employee:

@property 

def name(self):

return self.ename

if e = Employee() is an object of class employee, we can print (e.name) top print the ename/call name() function.


@.getters and @.setters

The method name with @property decorator is called getter method.

We can define a function + @name.setter decorator like below:

@name.setter

def name(self, value):

self.ename = value

Operator overloading in Python

Operators in python can be overloaded using dunder methods.

These methods are called when a given operator is used on the objects.

Operators in python can be overloaded using the following methods:

p1 + p2 -> p1.__add__(p2)

p1 – p2 -> p1.__sub__(p2)

p1 * p2 -> p1.__mul__(p2)

p1 / p2 -> p1.__truediv__(p2)

p1 // p2 -> p1.__floordiv__(p2)

Other dunder/magic methods in Python

__str__() -> used  to set what gets displayed upon calling str(obj)

__len__() -> used to set what gets displayed upon calling .__len__() or len(obj)

 

Practice:

Create a class C-2d vector and use it to create another class representing a 3-d vector.

class C2dVec:
    def __init__(selfij):
        self.icap = i
        self.jcap = j

    def __str__(self):
        return f"{self.icap}i + {self.jcap}j"

class C3dVec(C2dVec):
    def __init__(selfijk):
        super().__init__(ij)
        self.kcap = k
    
    def __str__(self):
        return f"{self.icap}i + {self.jcap}j + {self.kcap}k"
    
    
v2d = C2dVec(13)
v3d = C3dVec(197)
print(v2d)
print(v3d)

Create a class pets from a class Animals and further create class Dog from Pets. Add a method bark to class Dog.

class Animals:
    color = "White"

class Pets(Animals):
    @staticmethod
    def sleep():
        print("Pets are sleeping")


class Dog(Pets):
    
    @staticmethod
    def bark():
        print("Dog is barking Bow Bow")

d = Dog()
print(d.color)
d.sleep()
d.bark()

Create a class Employee and add salary and increment properties to it.

Write a method SalaryAfterIncrement method with a @property decorator with a setter which changes the value of increment based on the salary.

class Employee:
    salary2000
    increments=1.5

    @property
    def salaryAfterIncrements(self):
        return self.salary * self.increments

    @salaryAfterIncrements.setter
    def salaryAfterIncrements(selfsal):
        self.incrementssal / self.salary

e = Employee()
print(e.salaryAfterIncrements)
print(e.increments)
e.salaryAfterIncrements=5000
print(e.salaryAfterIncrements)
print(e.increments)

Write a class complex to represent complex numbers, along with overloaded operators + and * which adds and multiplies them.

class Complex:
    def __init__(selfij):
        self.i =i
        self.j=j
    
    def __add__(self,obj2):
        return Complex(self.i + obj2.i, self.j + obj2.j)
    def __str__(self):
        return f"{self.i} + {self.j}i"
c1=Complex(2,3)
c2=Complex(3,4)
print(c1 + c2)



Thursday, June 24, 2021

OIC - pgp tool to encrypt or decrypt the file

Object: Pgp tool is used to encrypt or decrypt any file. Suppose your integration is handling or sending  any encrypted file to endpoint and there is any issue occured in the file data, so we may need to check the file contents, using the pgp key we can easily decrypt the file with this pgp tool and debug the issue.

Download links:

Go to below link or search in google with pgp key

https://pgptool.github.io/

Download the installer package or zip package as per your convenient.

One more thing, to run this tool we need to install java jdk 1.8.0 version.

Go this below link or search in google.

https://java.com/en/download/


After installation

open the pgp tool and go to keyring tab and use import pgp key to import the pgp key and then click encrypt or decrypt.



Monday, June 21, 2021

OIC JS - return today's date in yyyymmdd format

 Js codes:

function returnMultiPeriodDate(){

var today = new Date();

var dd = today.getDate();

var mm = today.getMonth() + 1;

var yyyy = today.getFullYear();

if (dd <10){

dd = '0' + dd;

}

if (mm < 10) {

mm = '0' + mm;

}

today = yyyy + '0' + mm;

return today;

}


Note:

today = yyyy + mm + dd; 

OIC JS - return last day

Object: Return last day of the month in this format yyyy-mm-dd

Js codes:

function returnLastDay(){

var date = new Date(), y = date.getFullYear(), m = date.getMonth();

var lastDate = new Date(y, m + 1, 0);

var day = lastDate.getDate();

var month = lastDate.getMonth() + 1;

var year = lastDate.getFullYear();

if ( parseInt(month) < 10 ) {

var newMonth = "0" + month;

}

else { 

var newMonth = month;

}

if ( parseInt(day) < 10 ) {

var newDay = "0" + day;

}

else { 

var newDay = day;

}

var lastday = year + "-" + newMonth + "-" + newDay;

return lastday;

}


Note

getMonth() method returns the months from 0 to 11. January is the 0 and February is 1 and so on...

firstDay = new Date(y, m, 1)

lastDay = new Date(y, m+1, 0)




Tuesday, June 8, 2021

OIC - NVL in javascript

NVL lets us to replace null (returned as blank) with a string in the results of a query. For example, 

NVL(value1, value2)

If value1 is null then it will be replaced with value2.


Javascript:

function nvl(value,nullValue){

var output = "";

if (value == null || value == "")

{

output = nullValue;

}else {

output = value;

}

return output;

}

Monday, June 7, 2021

OIC - send Notification - email, log file and create incident

Usecase: Here, we will create a reusable component "Notification service" and we will perform following functions:

  • Send Email
  • Create Incident
  • LogFile
Rest Request Json:
{
"sendEmailFlag": "Y",
"emailFrom": "",
"emailSubject": "",
"emailBody": "",
"attachmentFlag": "",
"attachmentBase64Reference": "",
"createIncidentFlag" : "",
"incidentCallerId" : "",
"incidentBusinessService" : "",
"incidentCategory" : "",
"incidentSubcategory: "",
"incidentContactType": "",
"incidentShortDescription" : "",
"incidentDescription" : "",
"createLogFileFlag" : "",
"directoryAdaptet" : "",
"logDescription" : "",
"logFileName" : ""
}

Response rest Json:

{
"emailSent" : "",
"incidentCreated" : "",
"incidentId" : "",
"logCreated" : "",
"ExceptionCode" : "",
"ExceptionReason" : "",
"ExceptionDetails" : ""
}

To send email:

  • Create a app driven integration and take body scope
  • Within the body, take a switch block and check if sendEmailFlag = "Y" then 
  • Take a stage action and write a file for the attachment.
  • Take a notification action and provide all details like emailFrom, emailSubject, create a EMAIL_BODY param and assign with emailBody and use in the body section with {EMAIL_BODY}.
  • In the attachment section, add the write file reference. Or use decodebase64ToReference() to convert the feeded attachment base64 to reference.
  • Update the emailsent response as "Y"

To Log file:

Here i will log the zip file in the S3 bucket using rest call.
  1. First create a rest S3 connection using
    1. rest api base url like https://hostname, 
    2. security as aws Signature version 4 and
    3.  access key, secret key, aws region like US West(Oregon) Region (us-west-2) and service name Amazon S3.
  2. In the integration, check if createLogFlag = "Y" then , write the log file using stage action. Provide file name, output directory,provide a csv file etc and in the map, assign log description.
  3. Zip the file. Provide logFileZipName and directory to zip and output directory.
  4. Configure the S3 rest connection and provide 
    1. relative url as /{pathAndFileName}, 
    2. verb put ,  
    3. provide request payload as Binary and media type of the request body as application/zip.
    4. In the map, assign pathandFilename to template param and zip reference to stream reference.
    5. Update that log created = Y

To create Incident:

  1. As service now is a rest service so first create a rest incident service connection using base API base URI, basic authentication and provide user and password.
  2. Use that connection  and configure in the integration and
    1.  provide relative uri "/api/now/table/incident" in this case, 
    2. verb as post
    3. Provide request and response JSON sample payload
    4.  then map the request payload.


Sunday, June 6, 2021

Python - Object-Oriented Programming

Solving a problem by creating objects is one of the most popular approaches in programming. This is called object-oriented programming.This concept focuses on using reusable code. (Implements DRY principle)

Class

A class is a blueprint for creating objects.

The syntax of a class looks like this:

Class Employee: [classname is written in PascalCase]

#methods & variables

Object

An object is an instantiation of a class. When class is defined, a template(info) is defined. Memory is allocated only after object instantiation.

Objects of a given class can invoke the methods available to it without revealing the implementation details to the user.     #Abstraction & Encapsulation!

Modelling a problem in OOPs

We identify the following in our problem

Noun -> Class -> Employee

Adjective -> Attributes -> name,age,salary

Verbs -> Methods -> getSalary(), increment()


Class Attributes

An attribute that belongs to the class rather than a particular object.

Example:

Class Employee:

company = “Google” #Specific to each class

harry = Employee() #Object instantiation

harry.company

Employee.company = “YouTube” #changing class attribute

Instance Attributes

An attribute that belongs to the Instance (object)

Assuming the class from the previous example:

harry.name = “Harry”

harry.salary = “30K” #Adding instance attributes

Note: Instance attributes take preference over class attributes during assignment and retrieval.


‘self’ parameter:

self refers to the instance of the class.

It is automatically passed with a function call from an object.

harry.getSalary()

here, self is harry and above line of code is equivalent to Employee.getSalary(harry)

This function getsalary is defined as:

class Employee:

company = “Google”

def getSalary(self):

print(“Salary is not there”)

Static method:

Sometimes we need a function that doesn’t use the self-parameter. We can define a static method like this:

@staticmethod #decorator to mark greet as a static method

def greet():

print(“Hello user”)


__init__() constructor:

  • __init__() is a special method which runs as soon as the object is created.
  • __init__() method is also known as constructor.
  • It takes self-argument and can also take further arguments.

For Example:

class Employee:

def __init__(self,name):

self.name = name

def getSalary(self):

#Some code…

harry = Employee(“Harry”) #Object can be instantiated using constructor like this!

 


Practice:

Create a class programmer for storing information of a few programmers working at Microsoft.

class Programmer:
    company = "Microsoft"
    def __init__(self,name,product):
        self.name=name
        self.product=product

    def getInfo(self):
        print(f"name of the companty {self.company} and name is {self.name} and product is {self.product}")

sri=Programmer("Sri","Skype")
nanda=Programmer("Nannda","Outlook")
print(sri.getInfo())
print(nanda.getInfo())

Write a class calculator capable of finding square, cube and the square root of a number.

class Calculator:

    def __init__(self,num):
        self.num=num
    def getSquare(self):
        return self.num * self.num

    def getCube(self):
        return self.num ** 3

    def getSqrRoot(self):
        return  self.num * 0.5

c=Calculator(5)
print(c.getSquare())
print(c.getCube())
print(c.getSqrRoot())

Create a class with a class attribute a; create an object from it and set a directly using object.a=0 Does this change the class attribute?

class Sample:
    a=23

s = Sample()
s.a=0
print(Sample.a)
print(s.a)

Answer: No, This will not change the class attribute.

Add a static method in problem 2 to greet the user with hello.

class Calculator:

    def __init__(self,num):
        self.num=num
    def getSquare(self):
        return self.num * self.num

    def getCube(self):
        return self.num ** 3

    def getSqrRoot(self):
        return  self.num * 0.5
    
    @staticmethod
    def greetUser():
        print("Hello user")

c=Calculator(5)
c.greetUser()
print(c.getSquare())
print(c.getCube())
print(c.getSqrRoot())

Write a class Train which has methods to book a ticket, get status(no of seats), and get fare information of trains running under Indian Railways.

class Train:

    def __init__(self, name, fare, seats):

        self.name = name

        self.fare = fare

        self.seats = seats


    def getStatus(self):

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

        print(f"The name of the train is {self.name}")

        print(f"The seats available in the train are {self.seats}")

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


    def fareInfo(self):

        print(f"The price of the ticket is: Rs {self.fare}")


    def bookTicket(self):

        if(self.seats>0):

            print(f"Your ticket has been booked! Your seat number is {self.seats}")

            self.seats = self.seats - 1

        else:

            print("Sorry this train is full! Kindly try in tatkal")


    def cancelTicket(self, seatNo):

        pass


intercity = Train("Intercity Express: 14015", 90, 2)

intercity.getStatus() 

intercity.bookTicket()

intercity.bookTicket()

intercity.bookTicket()

intercity.getStatus()


 


Python - File I/O

The random access memory is volatile and all its contents are lost once a program terminates. In order to persist the data forever, we use files. A file is data stored in a storage device. A python program can talk to the file by reading content from it and writing content to it.

Types of Files:

  • Text files (.txt, .c, etc)
  • Binary files (.jpg, .dat, etc)

Python has a lot of functions for reading, updating, and deleting files.

Opening a file:

Python has an open() function for opening files. It takes 2 parameters: filename and mode.

open(“this.txt”, “r”)

Here, “this” is the file name and “r” is the mode of opening (read mode)

Reading a file in Python:

f = open(“this.txt”, “r”)     #Opens the file in r mode

text = f.read()          #Read its content

print(text)     #Print its contents

f.close()         #Close the fie

We can also specify the number of characters in read () function:

f.read(2)       #Reads first 2 characters


Other methods to read the file

We can also use f.readline() function to read on full line at a time.

f.readline()               #Reads one line from the file


Modes of opening a file:

r - open for reading

w - open for writing

a - open for appending

+ - open for updating

‘rb’ will open for read in binary mode

‘rt’ will open for read in text mode


Writing Files in Python:

In order to write to a file, we first open it in write or append mode after which, we use the python’s f.write() method to write to the file!

f = open(“this.txt”, “w”)

f.write(“This is nice”)        #Can be called multiple times

f.close()


With statement:

The best way to open and close the file automatically is the “with” statement.

with open(“this.txt”) as f:

            f.read()

#There is no need to write f.close() as it is done automatically


Practice:

Write a program to read the text from a given file “poems.txt” and find out whether it contains the word ‘twinkle’.

The game() function in a program lets a user play a game and returns the score as an integer. You need to read a file “Hiscore.txt” which is either blank or contains the previous Hi-score. You need to write a program to update the Hi-score whenever game() breaks the Hi-Score.

Write a program to generate multiplication tables from 2 to 20 and write it to the different files. Place these files in a folder for a 13- year old boy.

A file contains the word “Donkey” multiple times. You need to write a program which replaces this word with ###### by updating the same file.

Repeat program 4 for a list of such words to be censored.

Write a program to mine a log file and find out whether it contains ‘python’.

Write a program to find out the line number where python is present from question 6.

Write a program to make a copy of a text file “this.txt”.

Write a program to find out whether a file is identical and matches the content of another file.

Write a program to wipe out the contents of a file using python.

Write a python program to rename a file to “renamed_by_python.txt”.

dll file missing - followersmonolog.dll there is a problem starting

 Whenever I start my computer, I am getting this annoying prompt up - "followersmonolog.dll there is a problem starting".


To resolve this follow below steps:

  • Visit this official link (here) and click on Download Autoruns and Autorunsc. Once the archive is downloaded, use WinRar or WinZip to extract the utility into a folder that is easily accessible.
  • Open the folder that you’ve just created and open the Autoruns executable. Wait patiently until the Everything list is populated with startup items.
  • Once the list is fully populated, hit Ctrl + F to bring up the search function. In the search associated with Find what, type the name of the DLL file that is reported by the RunDLL error.
  • Right-click on the highlighted startup key and choose Delete to remove it. Once you do this, hit the Find Next button again and delete every other entry that matches your query.
  • Once all entries are deleter, close Autoruns and restart your computer.

Alternate solution:

An alternate method to resolve this issue is as follows:

1. Go to Start > Control Panel > Administrative Tools.

2. Open Task Scheduler and click on Task Scheduler Library.

3. Look through the list for an entry related to BackgroundContainer.

4. If found, right-click on it and select Delete.

5. Exit all programs and reboot the computer when done.

References:

https://support.mozilla.org/bm/questions/984294

https://appuals.com/fix-rundll-error-at-windows-startup/

Thursday, June 3, 2021

OIC - Target REST endpoint response payload processing failed.[Content received of length XXX bytes exceeds the maximum allowed threshold of 10485760 bytes

ERROR

Target REST endpoint response payload processing failed.[Content received of length XXX bytes exceeds the maximum allowed threshold of 10485760 bytes]

CAUSE

The issue occurred due to a large payload. The payload was over the allowed limit (>10 MB) and the issue can reoccur at any time if you have large payloads. It is expected behavior.

 SOLUTION

Recommendation:

Reduce the payload size for a request as the limitation is 10 MB. We can't change the limit. It's the customer's responsibility to design the flow by taking into account the oic limitations

Suggestion:

Make multiple requests with smaller time intervals in order to reduce the payload


REFERENCE:

support.oracle.com




Wednesday, June 2, 2021

Python - Functions and Recursions

Function: 

  • A function is a group of statements performing a specific task.
  • When a program gets bigger in size and its complexity grows, it gets difficult for a programmer to keep track of which piece of code is doing what!
  • A function can be reused by the programmer in a given program any number of times.

Example and Syntax of a function

The syntax of a function looks as follows:

def func1():

print(“Hello”)

This function can be called any number of times, anywhere in the program.

Function call:

Whenever we want to call a function, we put the name of the function followed by parenthesis as follows:

func1()          #This is called function call


Function definition:

The part containing the exact set of instructions that are executed during the function call.


Types of functions:

There are two types of functions in Python:

  • Built-in functions #Already present in Python
  • User-defined functions #Defined by the user

Examples of built-in function includes len(), print(), range(), etc.

The func1() function we defined is an example of user-defined function.


Functions with arguments:

A function can accept some values it can work with. We can put these values in the parenthesis. A function can also return values as shown below:

def greet(name):

gr = “Hello” + name

return gr

a = greet(“Tom”) #“Tom” is passed to greet in name

# a will now contain “Hello Tom”


Default Parameter Value:

We can have a value as default argument in a function.

If we specify name = “stranger” in the line containing def, this value is used when no argument is passed.

For Example:

def greet(name=’stranger’):

#function body

greet()                       #Name will be ‘stranger’ in function body(default)

greet(“Tom”)        #Name will be “Tom” in function body(passed)


Recursion:

Recursion is a function which calls itself.

It is used to directly use a mathematical formula as a function. For example:

factorial(n) = n * factorial(n-1)

This function can be defined as follows:

def factorial(n):

if i == 0 or i == 1 : #Base condition which doesn’t call the function any further

return i

else:

return n*factorial(n-1) #Function calling itself

The programmer needs to be extremely careful while working with recursion to ensure that the function doesn’t infinitely keep calling itself.

Recursion is sometimes the most direct way to code an algorithm.

 

Practice:

Write a program using the function to find the greatest of three numbers.

n1=int(input("Enter 1st num:"))
n2=int(input("Enter 2nd num:"))
n3=int(input("Enter 3rd num:"))
def greatestNumber(a,b,c):
    if a>b:
        if a>c:
            return a
        else:
            return c
    else:
        if b>c:
            return b
        else:
            return c

g=greatestNumber(n1,n2,n3)
print(f"Greatest of {n1}{n2} and {n3} is: {g}")

Write a python program using the function to convert Celsius to Fahrenheit.

# (0°C × 9/5) + 32 = 32°F
def celsiusToFahrenheit(c):
    return (c * (9/5) + 32)

c=11
f=celsiusToFahrenheit(c)

How do you prevent a python print() function to print a new line at the end?

print("something", end="")

Write a recursive function to calculate the sum of first n natural numbers.

# sum of n natural numbers
# sum(n)= n + sum(n-1)

def sumOfNaturalNumbers(n):
    if n==1:
        return 1
    else:
        return n + sumOfNaturalNumbers(n-1)

num = int(input("Enter n number to sum for natural numbers:"))

sum=sumOfNaturalNumbers(num)
print(sum)

Write a python function to print the first n lines of the following pattern.

***

**       #For n = 3

*

Write a python function to remove a given word from a string and strip it at the same time.

def removeWordStrp(string,word):
    newString = string.replace(word,"").strip()
    return newString

string = "      Joy is a good boy       "
print(string)
print(removeWordStrp(string,"Joy"))



 

Tuesday, June 1, 2021

Python - Loops

A loop statement allows us to execute a statement or group of statements multiple times.

Types of loops:

Primarily there are two types of loops in Python

  • While loop
  • For loop

We will look into these one by one!

While loop:

The syntax of a while loop looks like this:

''' while condition:

    #Body of the loop '''

The block keeps executing until the condition is true/false

In while loops, the condition is checked first. If it evaluates to true, the body of the loop is executed, otherwise not! If the loop is entered, the process of condition check and execution is continued until the condition becomes false.

An Example:

i = 0

while i<5:

    print(“Sri”)

    i = i+1

(Above program will print Sri 5 times)

Note: if the condition never becomes false, the loop keeps getting executed.


For loop

A for loop is used to iterate through a sequence like list, tuple or string (iterables)

The syntax of a for loop looks like this:

l = [1, 7, 8]

for item in l:

print(item)

(Above program will print 1, 7 and 8)


Range function:

The range function in python is used to generate a sequence of numbers.We can also specify the start, stop and step-size as follows:

 range(start, stop, step_size)

step size is usually not used with range()

An example demonstrating range() function

for i in range(0, 7): #range(7) can also be used

print(i) #prints 0 to 6

For loop with else

An optional else can be used with a for loop if the code is to be executed when the loop exhausts.

Example:

l = [1, 7, 8]

for item in l:

print(item)

else:

print(“Done”) #This is printed when the loop exhausts!

Output:

1

7

8

Done


The break statement

‘break’ is used to come out of the loop when encountered. It instructs the program to – Exit the loop now

Example:

for i in range(0, 80):

print(i) #This will print 0, 1, 2 and 3

if i == 3:

break

The continue statement

‘continue’ is used to stop the current iteration of the loop and continue with the next one. It instructs the program to “skip this iteration”.

Example:

for i in range(4):

print(“printing”)

if i == 2: #if i is 2, the iteration is skipped

continue

print(i)

pass statement

pass is a null statement in python. It instructs to “Do nothing”.

Example:

l = [1, 7, 8]

for item in l:

pass #without pass, the program will throw an error

 

Practice:

Write a program to print the multiplication table of a given number using for loop.

num = int(input("Enter a number:\n"))
for i in range(1,11):
    n=num * i
    print(f"{num} * {i} : {n}")

Here, I used f string format.

Write a program to greet all the person names stored in a list l1 and which starts with S.

l1 = [“Harry”, “Sohan”, “Sachin”, “Rahul”]

l1 = ["Harry""Sohan""Sachin""Rahul"]
for name in l1:
    if name.startswith('S'):
        print("hello",name)

Write a program to find whether a given number is prime or not.

num=int(input("Enter a number:"))
prime=False
if num==1:
    prime=True
for i in range(2,num):

    if num%i==0:
        prime=True          
        break
    else:
        prime=False
        
if prime==True:
    print("The number is not prime")
else:
    print("The number is prime")

Write a program to find the sum of first n natural numbers using a while loop.

n=int(input("Enter a number:"))
sum=0
for i in range(1,n+1):
    sum+=i
print(f"Sum of 1st {n} numbers is: {sum}")

Write a program to calculate the factorial of a given number using for loop.

num=int(input("Enter a number:"))
t=num
fact=1
while num >0:
    fact*=num
    num-=1
print(f"factorial of {t} is : {fact}")


Write a program to print the following star pattern.

    *

  ***  

***** for n=3

TBD:

Write a program to print the following star pattern:

*

**

*** for n = 3

n=3
for i in range(1,n+1):
    print("*" * i)

or

n=3
for i in range(1,n+1):
    for j in range(1,i+1):
        print("*"end="")
    print("")

Python - Conditional Expressions or Decision making statements

Python has some decision making conditional statements on which we can take some further steps. If the condition is TRUE then it perform some specific steps ELSE or FALSE it executes other specific statements.

Types of Condition statements:

  • if Statement
  • If else 
  • if elif ...and else 

If else and elif statements are a multiway decision taken by our program due to certain conditions in our code.

Syntax:

if (condition1): // if condition 1 is true

print(“yes”)

elif (condition2): // if condition 2 is true

print(“No”)

else: // otherwise

print(“May be”)

Code example:

a = 22

if (a>9):

    print(“Greater”)

else:

    print(“lesser”)


Relational Operators:

Relational operators are used to evaluate conditions inside if statements. Some examples of relational operators are:

= = -> equals

>=  -> greater than/equal to

<=, etc.

Logical Operators:

In python, logical operators operate on conditional statements. Example:

and -> true if both operands are true else false

or -> true if at least one operand is true else false

not -> inverts true to false and false to true


elif clause

elif in python means [else if]. if statement can be chained together with a lot of these elif statements followed by an else statement.

if (condition1):

    #code

elif (condition 2):

    #code

elif (condition 2):

    #code

….

else:

    #code

Above ladder will stop once a condition in an if or elif is met.

Important Notes:

  • There can be any number of elif statements.
  • Last else is executed only if all the conditions inside elifs fail. 

Practice:

Write a program to print yes when the age entered by the user is greater than or equal to 18.

age=int(input("Enter your age:\n"))
if age >=18:
    print("Yes")
else:
    print("No")

Write a program to find the greatest of four numbers entered by the user.

n1=int(input("Enter number 1:"))
n2=int(input("Enter number 2:"))
n3=int(input("Enter number 3:"))
n4=int(input("Enter number 4:"))

if n1>n2:
    g1=n1
else:
    g1=n2

if n3>n4:
    g2=n3
else:
    g2=n4

if g1>g2:
    greatest=g1
else:
    greatest=g2

print("Greatest number is: "greatest)


Write a program to find out whether a student is pass or fail if it requires a total of 40% and at least 33% in each subject to pass. Assume 3 subjects and take marks as an input from the user.

m1=int(input("Enter mark 1:"))
m2=int(input("Enter mark 2:"))
m3=int(input("Enter mark 3:"))


if (m1 <33 or m2<33 or m3<33):
    print("the Student failed as less than 33 in one of the subject")
elif ((m1+m2+m3)/3) <40:
    print("the Student failed as total is less than 40 parcentile")
else:
    print("The student has passed with ",(m1+m2+m3)/3)

A spam comment is defined as a text containing the following keywords:

“make a lot of money”, “buy now”, “subscribe this”, “click this”. Write a program to detect these spams.

text = input("Enter the text\n")

if("make a lot of money" in text):
    spam = True
elif("buy now" in text):
    spam = True
elif("click this" in text):
    spam = True
elif("subscribe this" in text):
    spam = True
else:
    spam = False

if(spam):
    print("This text is spam")
else:
    print("This text is not spam")

Write a program to find whether a given username contains less than 10 characters or not.

username=input("Enter your name:\n")
if len(username)<10:
    print("Username contains less than 10 chars")
else:
     print("Username contains more than or equal to 10 chars")

Write a program that finds out whether a given name is present in a list or not.

myList=['sri','ananda','joy','lilu']

name =input("Enter a name:\n")
if name in myList:
    print("Yes")
else:
    print("No")

Write a program to calculate the grade of a student from his marks from the following scheme:

90 – 100 -> Ex

80 - 90 -> A

70 – 80 -> B

60 – 70 -> C

50 – 60 -> D

<50 – F

mark=int(input("Enter your mark:"))
if mark >=90:
    print("Ex")
elif mark >=80:
    print("A")
elif mark >=70:
    print("B")
elif mark >=60:
    print("C")
elif mark >=50:
    print("D")
else:
    print("F")

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...