Sunday, 5 April 2020

Try Except in python with example

Error handling in Python using Try.. Except..

Consider the below example for your reference, you can see the TRY block followed by the EXCEPT and below that there are two additional blocks ELSE and FINALLY.

Try:
The try block will get executed first and will perform the operations given under it. If there is any exception  during the operation then the try block will be stopped else the try block will completed its execution and by pass the EXCEPT block. Compulsory block 

Except:
This block will get executed only if there is any exception in the try block. This Except block will handle the exception and provide a useful message to user regarding the error that has been occurred. Compulsory block 

Else:
This block will be performed if there are no exception and over successful completion of the try block. This is an optional block.

Finally:
This is a final block and this block will definitely get executed even though if there is any exception and optional block in try except.

Example:

students =[
    {"name":"Ram", "marks":[50,40,80]},
    {"name":"Raju", "marks":[]},
    {"name":"Babu", "marks":[90,80,70]}
]

try:
    for student in students:
        name = student["name"]
        marks = student["marks"]
        total = sum(marks)
        average = sum(marks)/len(marks)

        print(f"{name} has scored: Total={total} & Average={average}")
except Exception as e:
    print("There is error in student")
    print(e)
else:
    print("Student list completed")
finally:
    print("done")

Output:
Ram has scored: Total=170 & Average=56.666666666666664
There is error in student
division by zero
done

Dunder or Magic methods in python with example

Magic methods are usually represented by two underscores at front and two at the back of method names. The name Dunder is because of these underscores. Also mainly used for operator overloading.

In the below example you can see two methods "str" and "repr" with two underscore at the front and two at the back. These two methods are used to give user a output if there are no proper return methods in a class. These can also be used to give a message on the function that has been performed in a class.

Example:

class Cars:
    def __init__(self, name, model):
        self.name = name
        self.model = model

    def __str__(self):
        return (f"{self.name} is manufactured in the year {self.model}")

    def __repr__(self):
        return (f"<{self.name} is manufactured in the year {self.model}/>")


car = Cars("Ferrari", "2019")
print(car)

Output:
Ferrari is manufactured in the year 2019

list indices must be integers or slices, not str error in python

Below is an example to elaborate the error and for an better understanding.

Eg:

shops = [{
    "name": "Anand Motors",
    "cars": [
        {
            "name":"Ferrari",
            "Price": 25000
        },
        {
            "name": "Benz",
            "price": 15000
        }
    ]}  
]

The above dictionary is referred as list, when to try to access the dictionary data using string.

name = "Anand Motors"
print(shops[name])

The above code gives error.

Solution or fix:

name = "Anand Motors"
print(next(shop for shop in shops if shop["name"] == name))

The above code will fix this error.


Friday, 3 April 2020

Difference between Method and Function in python with example

Function:

A function is a set of code or block of code which process data and return or create a output for the given input.

Eg:
def addValues(x, y):
    return x+y

x=int(input("Enter your x value:"))
y=int(input("Enter your y value:"))
print(addValues(x, y))

When you consider the above python code, addValues() is a function.

Method:

A method is similar to function where has a set of code or a block of code, which is represented by a name. When the name is called the entire block of code will be executed. 

Eg:
class mathis:
    def addValues(x, y):
        return x+y

x=int(input("Enter your x value:"))
y=int(input("Enter your y value:"))
print(mathis.addValues(x, y))

In the above python code, the same addValues() is defined into a class which is referred as a method.

Here the difference between method and function is:

  • If a function is defined inside a class then it is called as method.
(note: Method and function has similar properties where both is used to perform an operation with block of code.)

Tuesday, 31 March 2020

Error: No module named flask in python

Error: No Module named flask, for python application

(venv) C:\Python\sandbox>py -m flask run
C:\Python\sandbox\venv\Scripts\python.exe: No module named flask

When you try to run the python application using flask you may get the above error: 
root cause: There is no flask installation found in the directory you are currently trying to access the application.
Solution:
When you over come the above error first install flask using below command:
py -m pip install Flask

Then try: py -m flask run 

Now your system will recognize your command and run the flask application.

Sunday, 29 March 2020

Mat Autocomplete list in Angular 7

How to create an Autocomplete list in Angular 7:


Here I am going to show how to get and display an autocomplete list of contents based on the input given by user.

Create a Form with Input and Mat Autocomplete in the .html file:

<form [formGroup]="serviceForm" (ngSubmit)="addService()" data-automation-attribute="form-op-service">
    <mat-grid-list cols="12" rowHeight="65px">
       <mat-grid-tile [colspan]="9">
          <mat-form-field *ngIf="searchType == '1'" class="full-width" appearance="outline">
             <mat-label>Service Name</mat-label>
             <input                  
                    cdk-focus-initial
                    type="text"
                    placeholder="Service Name"
                    matInput
                    [matAutocomplete]="auto"
                    formControlName="serviceName"
                    [(ngModel)]="serviceName"
                    (input)="getserviceOnSearch()"
                    data-automation-attribute="text-service-name" />
                  <mat-autocomplete #auto="matAutocomplete" (optionSelected)="serviceOnSelect($event.option.value)">
                    <mat-option *ngFor="let service of filteredOptions | async"
                      [value]="service.serviceName">
                      {{ service.serviceName }}
                    </mat-option>
                  </mat-autocomplete>
                </mat-form-field>
</mat-grid-tile>
</mat-grid-list>
</Form>

Explanation:

Main code in the input field:
matAutocomplete set as auto.
input: to get the input entered by the user
under mat-option set the filtered option to get the latest list based on the user key.
Once the user enter the key then using ngModel it will be captured in the method getserviceOnSearch(). The functionality of this method is given below in detail.


Add below code into .TS file:

serviceName: string = "";

//This method is used to filter using the user key and return a customized list
searchedText: string = "";
  getserviceOnSearch() {
    let splitText: any;
    if (
      this.serviceName &&
      //this.searchedText != this.serviceName &&
      (this.serviceName.length == 3 ||
        this.serviceName.length == 5 ||
        this.serviceName.length > 7)
    ) {
      this.searchedText = this.serviceName;

      this.http.get<any>('https://api.io/')
        .getResource(
          "billing-masters/unit-wise-services?searchKey=" + this.serviceName
        )
        .subscribe(res => {
          if (res) {
            this.services = res;
            this.filteredOptions = this.serviceControl.valueChanges.pipe(
              startWith(""),
              map(value => this._filter(value))
            );
          }
        });
    } else if (this.serviceName.length <= 2) {
      this.filteredOptions = new Observable<string[]>();
    }
  }

private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();
    return this.services.filter(option =>
      option.serviceName.toLowerCase().includes(filterValue)
    );
  }

The above code is very simple just need to add this method and the list will populate based on the key entered. If you want to populate the complete list during the application start then add the below code in OnInit method to load the complete API response into the list.

ngOnInit() {
this.http.get<any>('https://api.io/')
        .getResource(
          "billing-masters/unit-wise-services?searchKey=" + this.serviceName=""
        )
        .subscribe(res => {
          if (res) {
            this.services = res;
            this.filteredOptions.next(this.services.slice());
          }
        });
    } else if (this.serviceName.length <= 2) {
      this.filteredOptions = new Observable<string[]>();
    }
}

The above code will add the complete response into the list which will show user all the options that are available and once the key is entered it will filter the options and refresh the list based on the key.

Cannot read property 'nativeElement' of undefined angular 7

This error is one of the common error which we get when there is a mismatch in the typescript and html in Angular 7.

To avoid this error kindly notice the below code for reference

In example.component.ts        
@ViewChild("nameField")nameField:ElementRef;

In example.component.html
<input                      
             cdk-focus-initial 
             #nameField
             type="text" 
             placeholder="Service Name" 
             matInput
             [matAutocomplete]="auto" 
             formControlName="serviceName" 
             [(ngModel)]="serviceName"
             (input)="getserviceOnSearch()" 
  data-automation-attribute="text-service-name" />

Expense Handler Application with advance technologies

Budget Planner  One of the application developed with Ionic 4 and Python-Flask.  Ionic 4 code:  https://github.com/logeshbuiltin/Expense...