Monday, 25 September 2017

The concept of if _ _name_ _ = = '_ _main_ _ condition

The concept of      if _ _name_ _ = =  '_ _main_ _ ' :

Example:  addition.py

def  add(x,y):

     z=x+y

     print(z)


add(4,5)

Output:

9

Example: adding.py

from addition import add


add(2,3)

Output:

9

5

Note:

  • here executing both main module and sub module add function.
  • in these cases we don't want execute imported module add function(sub module add function). 
  • i want execute only main module add function.
in this situation we are using   if  _ _name_ _ = = '_ _main_ _' :


Example:


def add(x,y):


    z=x+y

    print(z)

if __name__= = '__main__':

    add(4,5)

Example:

from addition import add


add(2,3)


Output:

5


Access modifiers in Python

Access modifiers in Python :

In C++ and Java, things are pretty straight-forward. There are 3 magical and easy to remember access modifiers, that will do the job (public, protected and private). 

But there’s no such a thing in Python. That might be a little confusing at first, but it’s possible too.

Public:

All member variables and methods are public by default in Python. So when you want to make your member public, you just do nothing.

Protected:

Protected member is (in C++ and Java) accessible only from within the class and it’s sub classes.

How to accomplish this in Python? 

The answer is _ by convention. By prefixing the name of your member with a single underscore, you’re telling others “don’t touch this, unless you’re a subclass”.

  • This changes virtually nothing, you’ll still be able to access the variable from outside the class, only if you see something like this.
  • you explain politely to the person responsible for this, that the variable is protected and he should not access it or even worse, change it from outside the class.

Private:

By declaring your data member private you mean, that nobody should be able to access it from outside the class, i.e. strong you can’t touch this policy. 

Python supports a technique called name mangling. This feature turns every member name prefixed with at least two underscores and suffixed with at most one underscore into 

_<className>_ _<memberName>  ------> Name Mangling


Example:

class test:
    def  __init__(self): #constructor
        self.x=10  #public

        self._y=20  #protected

        self.__z=30  #private

    def  m1(self): #method
        print(self.x)
 
        print(self._y) 

        print(self.__z) 
    
t1=test( )

t1.m1( )

print(t1.x)

print(t1._y)

print(t1._test__z)

print(dir(t1))

Output:

10

20

30

10

20

30

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_test__z', '_y', 'm1', 'x']


Tuesday, 19 September 2017

How to check whether number is prime number or not



Prime Number:
Any number divisible by 1 and itself that number is called prime number.

Example:

num = int(input("enter number: "))
if num > 1:
   for i in range(2,num):
       if (num % i) == 0:
           print(num,"is not a prime number")
           print(i,"times",num//i,"is",num)
           break
   else:
       print(num,"is a prime number")
       

else:
   print(num,"is not a prime number")


Output:

enter number: 5
5 is a prime number

Output:

enter number: 12
12 is not a prime number
2 times 6 is 12

Output:

enter number: 15
15 is not a prime number
3 times 5 is 15

Monday, 18 September 2017

how to calculate Age


write a program to calculate age in python:

import  datetime
year=datetime.datetime.now().year
year_of_birth=int(input("enter your birth year: "))
print("you are %i years old!"%(year-year_of_birth))

Output:

enter your birth year: 1991
you are 26 years old!

Saturday, 16 September 2017

check whether given number is Armstrong or not


Armstrong number: the sum of cubes of each digit in a number is equal to original number.

Example:
                     153=13 + 53 + 33
                                   1 +  125 + 27



Example:

num=int(input("enter a number: "))
sum = 0
temp = num
while temp > 0:
   digit = temp % 10
   sum += digit ** 3
   temp //= 10
if num == sum:
   print(num,"is an Armstrong number")
else:
   print(num,"is not an Armstrong number")

Output:

enter a number: 153

153 is an Armstrong number

Example 2: 
find the Armstrong numbers between given range

lower = 100
upper = 2000
for num in range(lower, upper + 1):  
   order = len(str(num))   
   sum = 0   
   temp = num
   while temp > 0:
       digit = temp % 10
       sum += digit ** order
       temp //= 10
   if num == sum:

       print(num)

Output:

153
370
371
407
1634

Sunday, 10 September 2017

how to check python version at run time



Example:

import sys

print(sys.version)

Output:

3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)]

Saturday, 9 September 2017

how to check given string is palindrome or not

Check whether given string is palindrome or not:

Example:

def palindrome(string):
    if string==string[ : : -1]:
        return True
    else:
        return False
print(palindrome("madam"))
print(palindrome("siva"))

print(palindrome("anna"))

Output:

True
False

True

for loop with else in python

for loop with else:

Example1:

for i in range(5):
    if i<5:
        print("hai")
else:

    print("hello")

Output:

hai
hai
hai
hai
hai

hello

Example2:

for i in range(5):
    if i==2:
        break
    print("hai")
else:

    print("hello")


Output:

hai
hai

Example3:

for i in range(5):
    if i==2:
        continue
    print("hai",i)
else:
    print("hello")

Output:

hai 0
hai 1
hai 3
hai 4
hello

switch case implementation in python

Switch Case:

def switch(operator,x,y):
    if operator=='add':
        z=x+y
        print("the addition of",x,"and",y,"is: ",z)
    elif operator=='sub':
        z=x-y
        print("the subtraction of",x,"and",y,"is: ",z)
    elif operator=='mul':
        z=x*y
        print("the multiplication of",x,"and",y,"is: ",z)
    elif operator=='div':
        z=x/y
        print("the division of",x,"and",y,"is: ",z)
    else:
        print("operation failed")
switch('add',4,5)
switch('sub',4,5)
switch('mul',4,5)
switch('div',4,5)
switch('mod',4,5)

Output:

        
the addition of 4 and 5 is:  9
the subtraction of 4 and 5 is:  -1
the multiplication of 4 and 5 is:  20
the division of 4 and 5 is:  0.8

operation failed

Sunday, 3 September 2017

Scope of the variables in python

Scope of the variables in python:

 we are following the rule: LEGB

L means Local

E means Enclosing

G means Global

B means Builtin

Example:

x="global x"
y="global y"
z="global z"
def f1(x):
    y="local y"
    z="local z"
    x="local x"
    print(y)
    print(z)
    print(x)

f1("enclosing z")

Output:

loacl y
local z

local x

Example:

x="global x"
y="global y"
z="global z"
def f1(z):
    y="local y"
    print(y)
    print(z)
    print(x)

f1("enclosing z")

Output:

loacl y
enclosing z

global x

Example:

x="global x"
y="global y"
z="global z"
def f1(z,x):
    y="loacl y"
    print(y)
    z=20
    print(z)
    print(x)

f1("enclosing z","enclosing x")

Output:

loacl y
20

enclosing x