Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Sunday, October 27, 2019

Python Program to retrieve all words having 5 characters length.


import re
str = 'one two three four five six seven 8 9 10'
result = re.findall(r'\b\w{5}\b' , str)
print(result)


Ouptut:
['three', 'seven']

instead of using the findall() method,
if we use the search() method,
it will return the first occurrence of the result only.

Python program to retrieve all words staring with a numeric digit


import re
str = 'The meeting will be conducted 
on 1st and 21st of every month'
res = re.findall(r'\d[w]*' , str)
for word in res:
    print(word)

Output: 

1
2
1

Python program to fetch all words starting with a in a given string.

Ans:

import re
str ='an apple a day keeps the doctor awaya'
result = re.findall(r'a[\w]*' , str)

for word in result:
    print(word)

Oupput:

C:\Python_WorkSpace\TestProject\venv\Scripts\python.exe 
C:/Python_WorkSpace/TestProject/regdemo2.py
an
apple
a
ay
awaya

Tuesday, December 26, 2017

Object Oriented Approach in Python

So Classes and Why do we need them

In Java it require that you write code in inside class but in Python it does not required.you can write a code inside a class but you don't have to.In Python we define a class using class keyword similar to define a function using def keyword.

Let's take an complete object-oriented example:

classess.py

students =[]

class Student:

      school_name = "Abhinaw Demo"
     
      def __init__(self,name,student_id=1):
              self.name=name
               self.student_id=student_id
                students.append(self)

      def __str__(self):
            return "Student "+ self.name

     def get_name(self):
            return self.name.capitalize()
    
      def get_school_name(self):
             return self.school_name

class NewSchoolStudent(Student):

    school_name="Inheritance Abhinaw Demo"
 
    def get_school_name(self):
          return "This is inheritance"

     def get_name(self):
         original_value= supper().get_name()
          return original_value + "New School"

abhinaw= NewSchoolStudent("Abhinaw")
print(abhinaw.get_school_name())
print(abhinaw.get_name())

This demo code includes classes,adding methods to our classes,Constructor,Instance and Class Attributes and Inheritance and Polymorphism.













Lambda Functions in Python

So Lambda Functions are just an anonymous function.they are very simple just saves your space and time.they are useful in case of higher  order function.Lets take an example:

def double(a):
        return a*2

Convert to Lambda Function

double = lambda a: a*2

Friday, December 22, 2017

Opening,Reading and Writing Files Python

Let's save our data in a file and read from that file again when we re-open our app.
So let's take an example:

Let's take an example:

students =[]

def get_students_titlecase():
       students_titlecase = []
        for student in students:
           students_titlecase .append( student["name"].title())

def print_students_titlecase():
       students_titlecase = get_students_titlecase()
       print(students_titlecase)

def add_student(name,student_id=1):
        student ={"name:name", "student_id": student_id}
         students.append(student)

def save_file(student):
       try:
            f=open("students.txt","a")
            f.write(student + "\n")
             f.close()
       except Exception:
             print("Could not save")
       
def read_file():
       try:
             f=open("students.txt","r")
              for student in f.readlines():
                      add_student(student)
                f.close()
         except Exception:
              print("Could not read file")

read_file()
print_students_titlecase()

student_name=input("Enter student name: ")
student_id= input("Enter student ID: ")

add_student(student_name,student_id)
save_file(student_name)

where a= append some text
             r = reading text file

So when you run the program.the output will be something like this

Output:

Could not read file
[]
Enter student name:

Nested Functions and Closures in Python

Let's take an example:

def get_students():
      
       students=["Abhinaw","Aman"]

def get_students_titlecase():

       students_titlecase = []

       for student in students:
              students_titlecase.append(student.title())
     
        return student_titlecase

students_titlecase_names=get_students_titlecase()

print(students_titlecase_names)

This is called Nested function and basically the inner function can access the outer students So this is called closures.

Create a simple python console app

Let's create an app where user will provide the student name and Student I'd from the console.

eg: student.py

students =[]

def get_students_titlecase():
       students_titlecase = []
        for student in students:
           students_titlecase = student["name"].title()

def print_students_titlecase():
       students_titlecase = get_students_titlecase()
       print(students_titlecase)

def add_student(name,student_id=1):
        student ={"name:name", "student_id": student_id}
         students.append(student)

student_list = get_students_titlecase()

student_name=input("Enter student name: ")
student_id= input("Enter student ID: ")

add_student(student_name,student_id)
print_students_titlecase()

So in console you have to something like this and output will be

Enter student name: Abhinaw
Enter student ID:3455
Abhinaw

this is very simple Python app taking console input and also we can modify the program.

Thursday, December 21, 2017

Functions Arguments in Python

            Functions Arguments

So argument is parameters where you can  provide the values to functions and also useful in case you don't have to make variable global.So let's modify our existing code for input argument.

functions.py :

students = []

def get_students_titlecase():
        student_titlecase = []
        for student in students:
                students_titlecase = student.title()
          return students_titlecase

def print_students_titlecase():
       students_titlecase = get_students_titlecase()
       print(students_titlecase)

def add_student(name) :
        students.append(name)

student_list = get_students_titlecase()

add_student("Abhinaw")

So now modify our add_student method:

def add_student(name,student_id=332)

        students.append(name)

So here you will notice student_id=332 is basically a default or optional student_id if any user does not provide student_id then it will add the value automatically but if any user provides then in that case it will be overridden by the userinput value.

Now let's add student Dictionaries to our add_student method:

def add_student(name , student_id=222)
        student = {"name:" name, "student_id", student_id}
       students.append(student)

So call this function like this

add_student(name="Abhinaw" , student_id=14)

In Python there can be multiple variable arguments such as inbuild print function.

print("hello", "World", 34, None , "Wow')

you must have question here like how come it possible let me create our own function just to cater above.

def var_args(name, *args)
        print(name)
         print(args)

just to call the function

var_args("Abhine","Android Developer",None, True)

you can add any number of argument.

There is also a concept called kwargs.
let's have a look.

def var_args(name,**kwargs):
print(name)
print(kwargs["description"],kwrgs["feedback"])

var_args("Abhinaw" ,description="Loves Android", feedback=None,androidcodingworld_subscriber=True)

it is called kwargs argument and defined with **kwrgs.So it is not a list it is Dictionaries thats where it differs from above example.

basically it was an example of variable arguments you can add as much as you can in the form of list or can also make it  Dictionaries.


Functions in Python

                     Functions

A functions is a block organized and re-usable code and use to perform certain action.Pyhthon comes with lot of built in functions such as

print("hello world")

str(3) == "3"

int("5") == 15

username = input("Enter the user's name: ")

So now let's create our own functions.So for this you can use PyCharm editor I will provide the code here and you can run it directly using pycharm.

functions.py :

students = []

def get_students_titlecase():
        student_titlecase = []
        for student in students:
                students_titlecase = student.title()
          return students_titlecase

def print_students_titlecase():
       students_titlecase = []
       for student in students:
       students_titlecase=student.title()
       print(students_titlecase)

def add_student(name) :
        students.append(name)

student_list = get_students_titlecase()

add_student("Abhinaw")

So actually I have by knowingly added some repeated code in functions which can be removed.Lets see

def print_students_titlecase():
       students_titlecase = get_students_titlecase()
       print(students_titlecase)

So if you write functions for single responsibility then it will be very helpful to write Unit Testing cases and code will be organized too.

Other Data Types in Python

We went over some data types such as integers,strings,floats.ther are more types in python.i will give breife over view then.

For numbers we have gone through integers and float.we also have type called complex which denotes complex numbers.So other types are

complex
long # only in Python 2
bytes and bytearray

tuple = (3, 5, 1 ,"Abhinaw") similar to list but immutable.cannot change there values.

set and frozenset

set([3,2,3,1,5]) == (1,2,3,4,5)

So I tried to represent all data types but remember there are many things which I have not mentioned but in my next post .I will create Python app and provide source code.

Friday, December 15, 2017

Exceptions in Python

Exceptions are event occurred during your program execution.that normally cause your program to stop actually.it usually means some error has been encountered.And your program simply does not know how to deal with it.So take an example of exception code.

eg:

student = {

       "name": "Abhinaw"
       "student_id": 123
       "feedback": None
}

last_name = student["last_name"]

Output:
KeyError: 'last_name'

To handle this scenario grecfully.we use try and except blog to handle this code.
So let's take another example with exception handled.

eg:
student = {

       "name": "Abhinaw"
       "student_id": 123
       "feedback": None
}

try:
      last_name = student["last_name"]
except KeyError:
      print("Some error occurred")

print("this code executed!!!!")

Output:

Some error occurred
This code executed!!!

Note both try and except block can have more than one line of code.
There can be many error occurred  like TypeError.Can be many other too.

eg:
student = {

       "name": "Abhinaw"
       "student_id": 123
       "feedback": None
}

student["last_name"] = "Tripathi"

try:
      last_name = student["last_name"]
      number_last_name = 3 + last_name
except KeyError:
      print("Some error occurred")

print("this code executed!!!!")

Output:

TypeError unsupported operand types .if you have noticed  this code executed! does not execute because we are only catching KeyError.So let's take another example.

eg:

student = {

       "name": "Abhinaw"
       "student_id": 123
       "feedback": None
}

student["last_name"] = "Tripathi"

try:
      last_name = student["last_name"]
      number_last_name = 3 + last_name
except KeyError:
      print("Some error occurred")
except TypeError:
      print("I can add multiple together")

print("this code executed!!!!")

Output:

I can add multiple together
This code executed!!!

you can also generic exception like

eg:
student = {

       "name": "Abhinaw"
       "student_id": 123
       "feedback": None
}

student["last_name"] = "Tripathi"

try:
      last_name = student["last_name"]
      number_last_name = 3 + last_name
except Exception:
      print("Some error occurred")

print("this code executed!!!!")

And you can also add finally at the end of except block.

Python Dictionaris

So Dictionary allows me to store key-value pair of any data very easily.if you have used JSON in the past then you will be very familiar with the Dictionary in Python.

for example:

student = {

        "name": "Abhinaw"
        "student_id": 20042343
        "feedback": None
}

this is what dictionary looks like in Python.So it has key and value And the value can be of any type.Dictionaries are very helpfull in case ,when you want to store some kind of structured data.

   List of Dictionaries

all_student = [

    {"name:" "Abhinaw" ,"student_id": 20042343},
     {"name:" "Rajat" ,"student_id": 20042345},
{"name:"Gaurav" ,"student_id": 20042893},

]

      Dictionary Data

student["name"] == "Abhinaw"

suppose if you are using key which does not exists in the Dictionary then it will raise an exception called "KeyError" like

student["last_name"] == KeyError

but you can set the default value if key is not present like this

student.get("last_name", "Unknown") == "Unknown".

in case you do not find the last_name in the Dictionary.

if you want all keys in the Dictionary you can simply do like this

student.keys() =["name" ,"student_id" , "feedback"]

student.values() = ["Abhinaw" , 20042343,None]

Similarly you can delete like this

student["name"] = "James"
del student["name"]

While Loops in Python

So while loop is theoretically same like other programming language.take an example in Python.

x =0

while x < 10:

        print("Count is {0}".format(x))
         x+=1

        Infinite Loops

num =10

while True:
       if num == 42:
        break

   print("Hello World")

Wednesday, December 13, 2017

break and continue in Python

So break and continue theoretically same as other programming language.taking a small example to demonstrate both in Python.

break example:

student_names = ["james" ,"Mark", "Abhinaw", "Arudhra" ,"Rajat", "Gaurav"]

for name in student_names:
       if name == "Arudhra":
             print("Found him!" + name)
              break
         print("Currently testing " + name)

Output:

Currently testing james
Currently testing Marks
Currently testing Abhinaw
Found her! Arudhra

continue example:

student_names = ["james" ,"Mark", "Abhinaw", "Arudhra" ,"Rajat", "Gaurav"]

for name in student_names:
       if name == "Arudhra":
             print("Found him!" + name)
              continue
         print("Currently testing " + name)

Output:

Currently testing james
Currently testing Marks
Currently testing Abhinaw
Currently testing Rajat
Currently testing Gaurav

we see that except for Arudhra .it print all names.

Loops in Python

Loops: let's take a example of list.

eg: students_names = ["Abhinaw", "Aman", "Ashish", "Himanshu']

if you want to print single element then

print(student_names[0])

is fine but print every element of list we need some kind of loop.

There are two main loops in Python for loop and while loop.lets have a for loop example.

for name in student_names:

       print("Students name is {0}" .format(name))

So it will print all the elements of list student_names.Simply name is a variable.

other programming for loop:

for(var i=0; I<someArray.length; I++)
{
   var element=someArray[i];
   console.log(element);
}

However this is not the case with the Python.this is not the way Python for loop works.pyhton does hide many things.it automatically assumes that you want to start from the first element from the list and also it knows when to stop.Pyhton does not have foreach loop.

        range function

let's have an example.

x =0
for index in range(10):
       x+=10
        print("The value of a is {0}".format(x))

output will be

The value of a is 10
The value of a is 20
The value of a is 30
The value of a is 40
The value of a is 50
The value of a is 60
The value of a is 70
The value of a is 80
The value of a is 90
The value of a is 100

So whats the range function do.basically it takes a range value and kind of converts  it in list.it will execute 10 times.So in this case the index will be the element of the list.So if you don't want to start your for loop to start from 0 then range function also supports two argument like this

range(5,10)
in this case index value will be

[5,6,7,8,9]

And also if you want to increment the index value by 2 every time it execute it also supports such as

range(5,10,2)

in this case 2 denots the increment.So our list will be

[5,7,9]

you can also exit the loop in between based on some logic using break and continue.

Tuesday, December 12, 2017

If Statements in Python

If Statement is very simple in Python.Let me give you an example.

number = 5
if number == 5:
       print("Number is 5")
else:
       print("Number is NOT 5")

Remember one thing Python uses indentation rather than curly braces for any code blocks.notice that there is colon(:) at if and else both.this is required in python.we use == equal sign to check the  equality in Python.

in Python there is a concept of "Truthy and Falsy Values" for example.

number=5
if number:
 
     print("Number is defined and truthy")

text = "Python"
if text:
   
    print("Text is defined and truthy")

In many other programming language you have to check the length of the variable if it is value greater or less than zero but in Python you could just write like above.

okay in case of Boolean and None:it also has Truthy and Falsy Values.
eg:

pyhton_course = True

if python_course :

# Not python_course == True

    print("this will execute")

aliens_found = None

if aliens_found :
    print("This will NOT execute")

you can also set the same thing for None like I have done above.

               Not If

number = 5

if number !=5 :
      print("this will not execute")

python_course = True

if not python_course:

     print("this will also not excute")

Multiple If Conditions

number = 3

python_course = True

if number  == 3 and python_course:
   
    print("this will execute")

if number == 17 or python_course :

   print("this will also execute")

Note: in Python there is no && or || for and  and or like in other programming language.

           Ternary If Statements

a = 1
b = 2

"bigger" if a>b else "smaller"

This is called Ternary if Statement in Python.

Boolean and None in Python

As you know about boolean in other programming language. it is same in python too but with small differences .boolean can be  a true or false value.can be declared as either of them.

eg:

python_course = True
java_course = False

Simply type a name and assign a value "True" or False .

if you have noticed only difference with other programming language is that it starts with Capital letter T for True and Capital letter F for False .interestingly you can convert Boolean value to int and it will give you values 1 and 0 in case of True and False like below.

eg:

int(python_course) == 1
int (java_course) == 0
str(python_course) == "True"

And for string it will simply give textual representation "True" or "False".

Now coming to None: it is similar to null like other programming languages.

eg:

aliens_found = None

I find it useful as a place holder variable.Something that I will use later.However there is difference between variable you have defined None and other the  variable not defined at all.
Simply type k in idle and idle will tell you that k has not been defined but if I assign None to k then it will not give any result but normal for None and also it will not cause any error to show either.So None is called None type.

Monday, December 11, 2017

Strings in Python

We use string to represent text.by default it's Unicode text in Python 3 but ASCII text in Python 2.And this is one of  the big advantage in Python 3 by the way.Strings can be defined like below:

eg:

'hello world' == "Hello World" == " " "Hello World " " "

There is absolutely no difference which one you use.you can write multi-line string using 3 double quotes but this string  is not going to assign to any variable.it just to be sitting there as a comment.your editor will recognize it.it is a comment.Definning String is very simple just type a variable name and assign it a textual value  and done.
String in Python supports lot of utility methods.some of them are:

eg:

"hello" .capitalize() == "Hello"
"hello".replace("e" , "a") == "hallo"
"hello" .isalpha() == True
"123".isdigit() == true # Usefully when converting to int

"some ,CSV,values" .split(",") == ["Some" , "CSV" , "Values"]

String Format Function-

normally, use when you want to replace existing text in a given string with a variable value.

For example:

name = "pyhthonBO"
machine = "HAL"

Let's print it like this:

"Nice to meet you {0}.I am {1}".formate(name,machine)

So you must be thinking it of bit weird.So let me tell you here {0} and {1} meaning.
{0} represents the variable name argument position in format function.
you can add many argument to the formate function.
python 3.6 introduces string interpolation though So now you can do some thing like

f"Nice to meet you{name}.I am {machine}"

you can also pre-fix with r and u before the string.to deal with raw and Unicode text.its up to you.what you choose.
There are many other string properties like slicing and cutting etc.

Integers and Floats in Python

Defining integers in Python is very easy.
eg:
answer=42

pi=3.14159

Python 3 also introduces complex numbers as a type.There is no real need to worry about types in Python.atleast not in the beginning.

answer + pi = 45.14159 # Don't worry about conversion !

you can seamlessly add integers, float .pyhton does not complain about it.it will produce desired results.And to cast anything.just have to do something like this.

int(pi) == 3
float(answer) == 42.0

this is needed when we really want to cast the integer and float variables.