python

 

Python some basic and some program(manikandan)

Python is a general-purpose interpreted, interactive, object-oriented and high-level programming language. Python was created by Guido van Rossum in the late eighties and early nineties. Like Perl, Python source code is also now available under the GNU General Public License (GPL).

Execute Python Programs

For most of the examples given in this tutorial you will find Try it option, so just make use of it and enjoy your learning.

Try following example using Try it option available at the top right corner of the below sample code box:

#!/usr/bin/python

print "Hello, Python!";

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python was designed to be highly readable which uses English keywords frequently where as other languages use punctuation and it has fewer syntactical constructions than other languages.

  • Python is Interpreted: This means that it is processed at runtime by the interpreter and you do not need to compile your program before executing it. This is similar to PERL and PHP.
  • Python is Interactive: This means that you can actually sit at a Python prompt and interact with the interpreter directly to write your programs.
  • Python is Object-Oriented: This means that Python supports Object-Oriented style or technique of programming that encapsulates code within objects.
  • Python is Beginner’s Language: Python is a great language for the beginner programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games.

History of Python:

Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands.

Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages.

Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL).

Python is now maintained by a core development team at the institute, although Guido van Rossum still holds a vital role in directing its progress.

Python Features:

Python’s feature highlights include:

  • Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language in a relatively short period of time.
  • Easy-to-read: Python code is much more clearly defined and visible to the eyes.
  • Easy-to-maintain: Python’s success is that its source code is fairly easy-to-maintain.
  • A broad standard library: One of Python’s greatest strengths is the bulk of the library is very portable and cross-platform compatible on UNIX, Windows and Macintosh.
  • Interactive Mode: Support for an interactive mode in which you can enter results from a terminal right to the language, allowing interactive testing and debugging of snippets of code.
  • Portable: Python can run on a wide variety of hardware platforms and has the same interface on all platforms.
  • Extendable: You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient.
  • Databases: Python provides interfaces to all major commercial databases.
  • GUI Programming: Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh and the X Window system of Unix.
  • Scalable: Python provides a better structure and support for large programs than shell scripting.

Apart from the above-mentioned features, Python has a big list of good features, few are listed below:

  • Support for functional and structured programming methods as well as OOP.
  • It can be used as a scripting language or can be compiled to byte-code for building large applications.
  • Very high-level dynamic data types and supports dynamic type checking.
  • Supports automatic garbage collection.
  • It can be easily integrated with C, C++, COM, ActiveX, CORBA and Java.

http://www.questionscompiled.com/python-interview-questions.html
1. Is python compiled based or interpretive based language?

Python mostly used in scripting, is general purpose programming language which supports OOP Object oriented programming principles as supported by C++, Java, etc.

Python programs are written to files with extension .py . These python source code files are compiled to byte code (python specific representation and not binary code), platform independent form stored in .pyc files. These byte code helps in startup speed optimization. These byte code are then subjected to Python Virtual Machine PVM where one by one instructions are read and executed. This is interpreter.
2. What built-in type does python provide?

Following are the most commonly used built-in types provided by Python:
Immutable built-in types of python

Numbers
Strings
Tuples

Mutable built-in types of python

List
Dictionaries
Sets
3. What is module in python?

Modules are way to structure python program. A module would have set of related functionalities. Each python program file (.py file) is a module, which imports other modules (object) to use names (attributes) they define using object.attribute notation. All the top level names of a module are attributes, exported for use by the importer of this module.

Filename of a module turns out to be an object name where it is imported.

import re; statement imports all the names defined in module re.
from statements can be used to import specific names from a module.

Both the above statements finds, compiles and loads (if not yet loaded) the module.

Python by default imports modules only once per file per process, when the very first import statement is encountered.
With from statement, names can be directly used. module name is not required.

4. What is package in python?

A folder of python programs (modules) is a package of modules. A package can have subfolders and modules.

A import statement can import packages and each import package introduces a namespace.
import folder1.subfolder2.module1
OR
from folder1.subfolder2.module1 import names

To import a package, __init__.py file must be present in each of the folders, subfolders.
5. What is namespace in python?

Every name introduced in a python program has a place where it lives and can be looked for. This is its namespace. Consider it as a box where a variable name mapped to object is placed. Whenever the variable name is referenced, this box is looked out to get corresponding object.

For example, functions defined using def have namespace of the module in which it is defined. And so 2 modules can define function with same name.

Modules and namespace go hand in hand. Each module introduces a namespace. Namespace helps in reusing name by avoiding name collision. Classes and functions are other namespace constructs.
6. What is scope in python?

Scope for names introduced in a python program is a region where it could be used, without any qualification. That is, scope is region where the unqalified reference to a name can be looked out in the namespace to find the object.

During execution, when a name is referred, python uses LEGB rule to find out the object. It starts looking out first into the local namespace. Then it searches name in enclosed namespace created by nested def and lambda. Then into global namespace which is the module in which it is defined and then finally into built-in namespace.

Example 1:

>>> def addxy(x,y): # x, y are local. addxy is global
… temp=x+y # temp is local
… print temp
… return temp

>>> addxy(1,2)
3
3

Example 2:

>>> total = 0 # total is global
>>> def addxy(x,y):
… global total
… total = x+y

>>> x
100
>>> y
200
>>> addxy(x,y)
>>> total
300
7. What are the different ways of passing arguments to a function in python?

Different forms of calling function and passing arguments to functions in python:
Function definition Function Caller Function call mapping to function definition
def func(x,y) func(a,b) Positional matching of argument
func(y=b, x=a) Argument name matching
def func(x,y=10) func(a)
func(a,b) Default value for argument
def func(x,y, *tuple_arg) func(a,b)
func(a,b,c) and many other arguments can be passed as positional arguments

Function with varying positional arguments stored in a tuple

Example:

def add(x,y, *tup):
temp = x+y
for elem in tup:
temp = temp + elem
return temp

print add(1,2) # prints 3
print add(1,2,3,4) # prints 10
def func(x,y, **dict_arg) func(a,b)
func(a,b, c=10)
func(a,b, c=10,name=’abcd’ )

and many other arguments can be passed as keyword argument

Function with varying keyword arguments stored in dictionary.

Example:

def percentage(mks1, mks2, **dict):
total_mks = mks1 + mks2
return total_mks / float( dict[‘out_of’] )

print percentage(65, 50, out_of=150)
8. What is lambda in python?

lamda is a single expression anonymous function often used as inline function. It takes general form as:

lambda arg1 arg2 … : expression where args can be used
Example of lambda in python:

>>> triangle_perimeter = lambda a,b,c:a+b+c
>>> triangle_perimeter(2,2,2)
6
Difference between lamda and def :

a. def can contain multiple expressions whereas lamda is a single expression function
b. def creates a function and assigns a name so as to call it later. lambda creates a function and returns the function itself
c. def can have return statement. lambda cannot have return statements
d. lambda can be used inside list, dictionary.

9. What is shallow copy and deep copy in python?

Object assignment does not copy object, it gets shared. All names point to same object.

For mutable object types, modifying object using one name, reflects changes when accessed with other name.
Example :

>>> l=[1,2,3]
>>> l2 = l
>>> l2.pop(0)
1
>>> l2
[2, 3]
>>> l
[2, 3]

A copy module overcomes above problem by providing copy() and deepcopy(). copy() creates a copy of an object, creating a separate entity.
Example of shallow copy copy():

>>> import copy
>>> copied_l = copy.copy(l) # performs shallow copy
>>> copied_l.pop(0)
2
>>> copied_l
[3]
>>> l
[2, 3]

copy() does not perform recursive copy of object. It fails for compound object types.
Example program for shallow copy problems:

>>> l
[[1, 2, 3], [‘a’, ‘b’, ‘c’]]
>>> s_list=copy.copy(l) # performs shallow copy
>>> s_list
[[1, 2, 3], [‘a’, ‘b’, ‘c’]]
>>> s_list[0].pop(0)
1
>>> s_list
[[2, 3], [‘a’, ‘b’, ‘c’]]
>>> l
[[2, 3], [‘a’, ‘b’, ‘c’]] # problem of shallow copy on compund object types

To overcome this problem, copy module provides deepcopy(). deepcopy() creates and returns deep copy of compound object (object containing other objects)
Example for deep copy deepcopy():

>>> l
[[1, 2, 3], [‘a’, ‘b’, ‘c’]]
>>> deep_l = copy.deepcopy(l)
>>> deep_l
[[1, 2, 3], [‘a’, ‘b’, ‘c’]]
>>> deep_l[0].pop(0)
1
>>> deep_l
[[2, 3], [‘a’, ‘b’, ‘c’]]
>>> l
[[1, 2, 3], [‘a’, ‘b’, ‘c’]]
10. How exceptions are handle in python?

Exceptions are raised by Python when some error is detected at run time. Exceptions can be caught in the program using try and except statments. Once the exceptions is caught, it can be corrected in the program to avoid abnormal termination. Exceptions caught inside a function can be transferred to the caller to handle it. This is done by rethrowing exception using raise. Python also provide statements to be grouped inside finally which are executed irrespective of exception thrown from within try .
Example of handling exception and rethrowing exception:

def func2(a,b):
try:
temp = a/float(b)
except ZeroDivisionError:
print “Exception caught. Why is b = 0? Rethrowing. Please handle”
raise ZeroDivisionError
finally:
print “Always executed”
def func1():
a=1
b=1

print “Attempt 1: a=”+str(a)+”, b=”+str(b)
func2(a,b)

b=a-b
print “Attempt 2: a=”+str(a)+”, b=”+str(b)
try:
func2(a,b)
except ZeroDivisionError:
print “Caller handling exception”

func1()

Output:

Attempt 1: a=1, b=1
Always executed
Attempt 2: a=1, b=0
Exception caught. Why is b = 0? Rethrowing. Please handle
Always executed
Caller handling exception
11. Give a regular expression that validates email id using python regular expression module re

Python provides a regular expression module re

Here is the re that validates a email id of .com and .co.in subdomain:

re.search(r”[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$”,”micheal.pages@mp.com”)
12. Explain file opertaions in python

Python provides open() to open a file and open() returns a built-in type file object. The default mode is read.

fread = open(“1.txt”) is equivalent to fread = open(“1.txt”, “r”), where fread is where the file object returned by open() is stored.

Python provides read(), readline() and readlines() functions to read a file. read() reads entire file at once. readline() reads next line from the open file. readlines() returns a list where each element is a line of a file.

The file can also be open in write mode. Python provides write() to write a string in a file, writelines() to write a sequence of lines at once.

The built-in type file object has close() to which is called for all open files.
13. What standard do you follow for Python coding guidlines?

PEP 8 provides coding conventions for the Python code. It describes rules to adhere while coding in Python. This helps in better readability of code and thereby better understanding and easy maintainability. It covers from code indentation, amount of space to use for indentation, spaces v/s tabs for indentation, commenting, blank lines, maximum line length, way of importing files, etc.
14. What is pass in Python ?

pass is no-operation Python statement. It indicates nothing is to be done. It is just a place holder used in compund statements as they cannot be left blank.
Example of using pass statement in Python:

>>> if x==0:
… pass
… else:
… print “x!=0”
15. What are iterators in Python?

Iterators in Python are used to iterate over a group of elements, containers, like list. For a container to support iterator, it must provide __iter__().

container.__iter__() :
This returns an iterator object.
Iterator protocol:

The iterator object is required to support the iterator protocol. Iterator protocol is implemented by an iterator object by providing definition of the following 2 functions:

1. iterator.__iter__() :
It returns the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements.

2. iterator.__next__() :
It returns the next item from the container. If there are no further items, raise the StopIteration exception.

Example of iterator on list:

>>> a=[1,2,3]
>>> i1= a.__iter__() # creating an iterator using __iter__() on container
>>> i1
<listiterator object at 0x7f5192ccbd10>
>>> i2= iter(a) # creating another iterator using iter() which calls __iter__() on container
>>> i2
<listiterator object at 0x7f5192ccbcd0>
>>> i1.next()
1
>>> next(i1) # calls i1.next()
2
>>> next(i2)
1

Iterators are required to implement __iter__ which returns the iterator (self) . Hence it can be used with for in

>>> for x in i1:
… print x

3
16. What are generators in Python?

Generators are way of implementing iterators. Generator function is a normal function except that it contains yield expression in the function definition making it a generator function. This function returns a generator iterator known as generator. To get the next value from a generator, we use the same built-in function as for iterators: next() . next() takes care of calling the generator’s __next__() method.

When a generator function calls yield, the “state” of the generator function is frozen; the values of all variables are saved and the next line of code to be executed is recorded until next() is called again. Once it is, the generator function simply resumes where it left off. If next() is never called again, the state recorded during the yield call is (eventually) discarded.
Example of generators:

def gen_func_odd_nums():
odd_num = 1
while True:
yield odd_num # saves context and return from function
odd_num = odd_num + 2

generator_obj = gen_func_odd_nums();
print “First 10 odd numbers:”
for i in range(10):
print next(generator_obj) # calls generator_obj.__next__()

Output:

First 10 odd numbers:
1
3
5
7
9
11
13
15
17
19
17. How do you perform unit testing in Python?

Python provides a unit tesing framework called unittest . unittest module supports automation testing, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework.
18. What is slicing in Python?

Slicing in Python is a mechanism to select a range of items from Sequence types like strings, list, tuple, etc.
Example of slicing:

>>> l=[1,2,3,4,5]
>>> l[1:3]
[2, 3]
>>> l[1:-2]
[2, 3]
>>> l[-3:-1] # negative indexes in slicing
[3, 4]

>>> s=”Hello World”
>>> s[1:3]
‘el’
>>> s[:-5]
‘Hello ‘
>>> s[-5:]
‘World’

19. Explain OOP principle inheritance in Python

Classes can derive attributes from other classes via inheritance. The syntax goes:

class DeriveClass( BaseClass):
<statement 1>
<statement 2>

<last statement >

If the base class is present in other module, the syntax for derivation changes to:

class DeriveClass( module.BaseClass):

Python supports overriding of base class functions by derive class. This helps in adding more functionality to be added in overriden function in derived class if required.

Python supports limited form of multiple inheritance as:

class DeriveClass( BaseClass1, BaseClass2, …):
<statement 1>
<statement 2>

<last statement >

where an attribute if not found in DeriveClass are then searched in BaseClass1 and their parent then BaseClass2 and their parents and so on. With new style, Python avoids diamond problem of reaching common base class from multiple paths by lineraly searching base classes in left to right order.
20. What is docstring in Python?

docstring or Python documentation string is a way of documenting Python modules, functions, classes. PEP 257 standardize the high-level structure of docstrings. __doc__ attribute can be used to print the docstring.
Example of defining docstring:

>>> def test_doc_string():
… “”” this is a docstring for function test_doc_string “””

>>> test_doc_string.__doc__
‘ this is a docstring for function test_doc_string ‘

 

print “hello world”

if(1>2):
print “asd”
else:
print “aaaaaaaaa”
###################
def student(a):
if(a<=-1):
print “invalid mark”
elif(a<50):
print “this is student fail mark”
elif(a <70):
print “this is student just pass mark”
elif(a<=100):
print “this is student pass in first class”
else:
print “absent”
print student(-40)
###############################################
def stud(b):
if(-1>=b):
print “invalid mark”
elif(50>b):
print “this is student fail mark”
elif(70>b):
print “this is stydent pass mark”
elif(100>=b):
print “this is student first class”
else:
print “abscent”
print stud(70)
##################################################
if(1>0):
print “siva”
else:
print “mani”
###########
if(12>1):
print “this is true”
###################
def st(a,b):
if(b==student):
if(-1>=a):
print “invalid mark”
elif(50>a):
print “this is stuent fail mark”
elif(70>a):
print “this is student pass mark”
elif(100>=a):
print “this is student good mark”
else:
print “this is above hundred”
else:
print “this is not student list”
print st(101,”studen”)
############################
def smallnum(a,b,c):
if(a<b)&(a<c):
print a
elif(b<c):
print b
else:
print c
print smallnum(10,20,30)
def small(a,b,c,d,e):
if(a<b)&(a<c)&(a<d)&(a<e):
print a
elif(b<c)&(b<d)&(b<e):
print b
elif(c<d)&(c<e):
print c
elif(d<e):
print d
else:
print e
print small(101,220,303,404,95)
############

#i want open file
f = open(“E:/poem.txt”,’r’)
out = f.readlines() # will append in the list out
for line in out:
print line
print line
a=[‘dssf’,’asdfsaf’,’asdfsaf’]
a.insert(0,’love’)
print a
print a.index(‘love’)
new=[1,2,4,5,3]
new.sort()
print new
print sorted(‘manikandan’)
#join
s=[‘i’,’love’,’you’]
asa=”mani”
q = asa.join(s)
print q
#replace
see=’i love mani’
print see.replace(‘mani’, ‘siva’)
#copy
book={‘one’:1,’two’:2}
print book[‘one’]
seenu =book.copy()
print seenu
#for
z=[‘apple’,’milk’,’mango’]
for fruit in z:
print (“i want:” + fruit)
#switch statement in python
#while 1:
# name=raw_input(‘enter your name:’)
# if name == ‘mani’: break
#this is * means single variable mulitiple parameter using
def list(*fruit):
print(fruit)
list(‘aplple’,’mango’,’lemon’)
#this is ** means convert into string
def item(**items):
print items
item(mango=10,apple=100)
################
def profile(first,last,*age,**item1):
print(‘%s %s’%(first,last))
print(age)
print(item1)
profile(‘mani’,’siva’,23,15,14,19,apple=100,mango=120)
##this is single variable adding multiple value
def exam(a,b,c):
return (a+b*c)
lis=(1,2,3)
print exam(*lis)
###class and object
class name:
var=1
var2=12
lit=name()

print lit.var

large value python
def big(a,b,c):
if a > b:
if a > c:
return b
else:
return c
else:
if b > c:
print a
else:
print c
print big(12,142,3)

def compare(a,b):
if a == b:
print “equalwell”
else:
print “notequql”
print compare(1,2)

############if################
def num(a,b):
if a > b:
print a
else:
print b
print num(1,2)
##########elseif######
def num1(a,b,c,d):
if a == b:
print a
elif b == c:
print b
elif c == d:
print c
elif d == a:
print d
else:
print “there is no equal”
print num1(1,1,3,1)
#############nested else##########
def high(a,b,c):
if a > b:
if b > c:
print a
else:
print c
else:
print b
print high(501,96,33)
################while##########
def whie(n):
i = 1
while i <= n:
print i
i = i + 1

print whie(10)
#i want check number in list is there or not
list = [1,3,2,9,8,7,6]
print 3 in list
print 10 not in list
####i want found length#######
num=[1,2,3,4,5]
print len(num)
###i want found maximum number
print max(num)
#mininum number ##
print min(num)
#i want split in group of character to single char#3
#print list(“abcdeghijklmnopqrstuvwxtz”)
#t
import datetime
today = datetime.datetime.now()
print today.year
print today.day
print today.month
print today.second
print today.minute
print today.hour
print today.microsecond
#time delta using diff between two dates
q = datetime.timedelta(weeks=1)
print q
print datetime.timedelta(weeks=52)
print datetime.timedelta(weeks=1)
#i want before one week correct date
print (today-datetime.timedelta(weeks=1))
#i want before 30 days date
print (today – datetime.timedelta(days=30))
print today
# i want know how many days my birthday now its self
# this is my birthday and i mention year=1992,month=1,days=15,hour=10,minute=45,second=56
mybirthday = datetime.datetime(1992,1,15)
totaldays = today-mybirthday
print today
print mybirthday
print totaldays.days
#i want know after 100 date i want know
after100 = today + datetime.timedelta(days=100)
print after100
# i want know after 52 weeks
after52weeks = today + datetime.timedelta(weeks=100)
print after52weeks
## i want after i hours
hours = today + datetime.timedelta(hours=1)
print hours
# after one minutes 30
minute = today + datetime.timedelta(minutes=1)
print minute
#i want change date time week hours minute
change = today + datetime.timedelta(weeks=1,hours=3,minutes=29)
print change
##date time string format#
str=today.strftime(‘%d/%m/%y’)
print str
#if u mention B means full sentence come in month b means short sentence in str
mon = today.strftime(‘%d/%B/%y’)
print mon
mon1 = today.strftime(‘%d/%b/%y’)
print mon1
####
#string in a = sort day A = full order
day = today.strftime(‘%a/%m/%y’)
print day
day1 = today.strftime(‘%A/%m/%y’)
print day1
## i want know how many days going this year on today itself
yer = today.strftime(‘%j’)
print yer
print today.strftime(‘%c’)
print today.strftime(‘%m’)
#i want strftime am or pm check
print today.strftime(‘%H%p’)
#12 clock
print today.strftime(‘%I%p’)
###second means
print today.strftime(‘%S’)
print today.strftime(‘%U’)
print today.strftime(‘%W’)
print today.strftime(‘%X’)
print today.strftime(‘%Y’)
print today.strftime(‘%y’){\rtf1}

def big(a,b,c):
if a < b:
if b < c:
return b
else:
return c
else:
if a < c:
print a
else:
print c
print big(12,142,3)

def compare(a,b,c):
if a == b:
print a
elif b == c:
print b
elif c == a:
print c
else:
print “error”
print compare(9,2,1)

new=open(‘E:/mani.txt’,’w’)
new.write(‘i am manikandan i am  in vggvtgtgrvhthrtvvvvvvvvvvvetvyy’)
new.close()
#
#print “i am manikandan”
#####

#fob=open(‘F:/python.txt’,’w’)
#fob.write(‘i am manikandan’)
#fob.close()
#fob=open(‘F:/python.txt’,’r’)
#print fob.read(3)
#print fob.read()
#print fob.readline()
#print fob.readlines()
#fob.close()
#file write in new line
#fob=open(‘F:/python.txt’,’w’)
#fob.write(“this first life don’t waste time your enjoy all time\nthis is new line 2\nthis is new line3\nthis is life”)
#fob.close()
#i want modify list
#fob=open(‘F:/python.txt’,’r’)
#listme=fob.readlines()
#print listme
#fob.close()
#listme[0]=”this is first line”
#listme
#fob.writelines(listme)
#fob.close()

#fob=open(‘F:/python.txt’,’w’)

 

#####fibonacci series##########
n=144
i=1
a=0
b=1
while(i<=n):
print a
c=a+b
a=b
b=c
i=i+1
###############################
days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
def how_many_days(month):
return days_in_month[month-1]
print how_many_days(1)
###########this even number or add number########## n
n=210258
if(n%2==0):
print ‘even num’
else:
print ‘odd num’
#####################################
var1 = “manikandan”
print var1[-1:0]
##################
#i want search particular number#########
list = [1,3,4,5,6,3,4,3]
if 3 in list:
print(‘3 is prsent’)
########################
list = [1,3,4,5,6,3,4,3]
if 13 in list:
print(’13 is prsent’)
#######find duplicate value in list######################
t = [1, 2, 3, 1, 2, 5, 6, 7, 8]
s = []
for i in t:
if i not in s:
s.append(i)

print s

# Given the variable,

days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]

# define a procedure, how_many_days,
# that takes as input a number
# representing a month, and returns
# the number of days in that month.

def how_many_days(month):
return days_in_month[month-1]
print how_many_days(1)
print how_many_days(9)

reverse operation without using reverse function
a=abcdefghijklmnopqstuvwxyz
a[::-1]
2.list=[1,2,120,154,156]
i want check some record in list
156 in list = true
200 in list = false
dict={“one”:1,”two”:2,”three”:3}
dict[”
remove duplicate without union
a={1,2,1,2,4,5,6,5,70}
print a
i want add number particular direction
a={1,2,3,5}
a.add(4)
print a
i want join two list in number in sort order
a={1,2,3,5,6}
b={4,7,8,9}
print a|b
i want find out duplicate value two list
q={1,2,3,4}
w={2,3,4,5,6,7,8}
q&w
set([2, 3, 4])
i want remove full duplicate i want correct value
a={1,2,3,5,6,7,8,9}
b={2,3,4,5,6,7,8}
a-b
output=set([1, 9])

#i want check number in list is there or not
list = [1,3,2,9,8,7,6]
print 3 in list
print 10 not in list
####i want found length#######
num=[1,2,3,4,5]
print len(num)
###i want found maximum number
print max(num)
#mininum number ##
print min(num)
#i want split in group of character to single char#3
#print list(“abcdeghijklmnopqrstuvwxtz”)
#t
import datetime
today = datetime.datetime.now()
print today.year
print today.day
print today.month
print today.second
print today.minute
print today.hour
print today.microsecond
#time delta using diff between two dates
q = datetime.timedelta(weeks=1)
print q
print datetime.timedelta(weeks=52)
print datetime.timedelta(weeks=1)
#i want before one week correct date
print (today-datetime.timedelta(weeks=1))
#i want before 30 days date
print (today – datetime.timedelta(days=30))
print today
# i want know how many days my birthday now its self
# this is my birthday and i mention year=1992,month=1,days=15,hour=10,minute=45,second=56
mybirthday = datetime.datetime(1992,1,15)
totaldays = today-mybirthday
print today
print mybirthday
print totaldays.days
#i want know after 100 date i want know
after100 = today + datetime.timedelta(days=100)
print after100
# i want know after 52 weeks
after52weeks = today + datetime.timedelta(weeks=100)
print after52weeks
## i want after i hours
hours = today + datetime.timedelta(hours=1)
print hours
# after one minutes 30
minute = today + datetime.timedelta(minutes=1)
print minute
#i want change date time week hours minute
change = today + datetime.timedelta(weeks=1,hours=3,minutes=29)
print change
##date time string format#
str=today.strftime(‘%d/%m/%y’)
print str
#if u mention B means full sentence come in month b means short sentence in str
mon = today.strftime(‘%d/%B/%y’)
print mon
mon1 = today.strftime(‘%d/%b/%y’)
print mon1
####
#string in a = sort day A = full order
day = today.strftime(‘%a/%m/%y’)
print day
day1 = today.strftime(‘%A/%m/%y’)
print day1
## i want know how many days going this year on today itself
yer = today.strftime(‘%j’)

#reverse operation without using reverse function
a=’abcdefghijklmnopqstuvwxyz’
print a[::-1]
list=[1,2,120,154,156]
#i want check some record in list
print 156 in list
print 200 in list
dict={“one”:1,”two”:2,”three”:3}

#remove duplicate without union
a={1,2,1,2,4,5,6,5,70}
print a
# # i want add number particular direction
a={1,2,3,5}
a.add(4)
print a
#i want join two list in number in sort order
a={1,2,3,5,6}
b={4,7,8,9}
print a|b
#i want find out duplicate value two list
q={1,2,3,4}
w={2,3,4,5,6,7,8}
q&w
set([2, 3, 4])
#i want remove full duplicate i want correct value
a={1,2,3,5,6,7,8,9}
b={2,3,4,5,6,7,8}
a-b
output=set([1, 9])

#i want check number in list is there or not
list = [1,3,2,9,8,7,6]
print 3 in list
print 10 not in list
####i want found length#######
num=[1,2,3,4,5]
print len(num)
###i want found maximum number
print max(num)
#mininum number ##
print min(num)
#i want split in group of character to single char#3
#print list(“abcdeghijklmnopqrstuvwxtz”)
#t
import datetime
today = datetime.datetime.now()
print today.year
print today.day
print today.month
print today.second
print today.minute
print today.hour
print today.microsecond
#time delta using diff between two dates
q = datetime.timedelta(weeks=1)
print q
print datetime.timedelta(weeks=52)
print datetime.timedelta(weeks=1)
#i want before one week correct date
print (today-datetime.timedelta(weeks=1))
#i want before 30 days date
print (today – datetime.timedelta(days=30))
print today
# i want know how many days my birthday now its self
# this is my birthday and i mention
year=1992,month=1,days=15,hour=10,minute=45,second=56
mybirthday = datetime.datetime(1992,1,15)
totaldays = today-mybirthday
print today
print mybirthday
print totaldays.days
#i want know after 100 date i want know
after100 = today + datetime.timedelta(days=100)
print after100
# i want know after 52 weeks
after52weeks = today + datetime.timedelta(weeks=100)
print after52weeks
## i want after i hours
hours = today + datetime.timedelta(hours=1)
print hours
# after one minutes 30
minute = today + datetime.timedelta(minutes=1)
print minute
#i want change date time week hours minute
change = today + datetime.timedelta(weeks=1,hours=3,minutes=29)
print change
##date time string format#
str=today.strftime(‘%d/%m/%y’)
print str
#if u mention B means full sentence come in month b means short sentence in str
mon = today.strftime(‘%d/%B/%y’)
print mon
mon1 = today.strftime(‘%d/%b/%y’)
print mon1
####
#string in a = sort day A = full order
day = today.strftime(‘%a/%m/%y’)
print day
day1 = today.strftime(‘%A/%m/%y’)
print day1
## i want know how many days going this year on today itself
yer = today.strftime(‘%j’)
print yer

# We defined:

stooges = [‘Moe’,’Larry’,’Curly’]

# but in some Stooges films, Curly was
# replaced by Shemp.

# Write one line of code that changes
# the value of stooges to be:

[‘Moe’,’Larry’,’Shemp’]

# but does not create a new List
# object.
stooges[2] = ‘Shemp’
print stooges

###name = raw_input(“What is your name?”)
quest = raw_input(“What is your quest?”)
color = raw_input(“What is your favorite color?”)

print “Ah, so your name is %s, your quest is %s, ” \
“and your favorite color is %s.” % (name, quest, color)
###########

### Write your code below, starting on line 3!
my_string=’fsdgdfsg’

print len(my_string)

print my_string.upper()

print my_string.lower()
################
from datetime import datetime
#############################
from datetime import datetime
now = datetime.now()

a = str(now.month) + “/” + str(now.day) + “/” + str(now.year)
b = str(now.hour) + “:” + str(now.minute) + “:” + str(now.second)

print a, b
###############################
from datetime import datetime
now = datetime.now()
print now

##
pyg = ‘ay’
original = raw_input(‘Enter a word:’)
word=original.lower()
first=word[0]
if len(original) > 0 and original.isalpha():
print original
else:
print ’empty’
##########
pyg = ‘ay’
word=”python”[0]
word
original = raw_input(‘Enter a word:’)
original.lower()
if len(original) > 0 and original.isalpha():
print original
else:
print ’empty’
#########################################
pyg = ‘ay’
word=”hello”
original = raw_input(‘Enter a word:’)
if len(original) > 0 and original.isalpha():
word=original.lower()
first=word[0]
new_word = word+first+pyg
new_word[1:len(new_word)]
print new_word
else:
print ’empty’
[
def lion(name,age=35):
print ‘name:’,name
print ‘age:’,age
return
print lion(‘mani’,18)
find special charcter in strin
a=”manikandansaran”
print a.isalpha()

#specfic line print in file handling
fille=open(‘F:/life.txt’,’w’)
fille.write(‘this is first line python\nthis is second line python\nthis third line python\nthis is fourth line python’ )
fille=open(‘F:/life.txt’,’r’)
hi=fille.readlines()
print hi[0]
print hi[1]
print hi[2]
class sarn:
a=10
b=20
c=30
d=40
class miruna(sarn):
a=10
b=220
c=’hi’

child= sarn()
print child.a
print child.b
print child.c
print child.d
pare = miruna()
print pare.a
print pare.b
print pare.c
print pare.d
#===========================)
lion=raw_input(‘enter your name:’)
qw = list(lion)
print ‘_’ in qw
print ‘.’ in qw
def mani(*a):
return a+a
print mani(‘sddfsfdsf’)

####################
def whie(n):
i = 1
table = 5
e= i*table
while i <= n:
print “%d * %d = %d” %(i, table,e)
i= i + 1

e = e + table
whie(10)

###########without using sort
collection = [1,2,3,4,5,6,7,8,9]
print len(collection)
##########3
forest = [21,15,55,89,76,45,12,35]
for hi in forest:
print hi
########################
siva = {1:”aaas”,2:”bbbb”,3:”ccccc”,4:”ddddd”,5:”eeee”}
print siva.keys()
print siva.values()
print (siva.keys()[0])
print (siva.keys()[3])
print (len(siva.keys()))
#################################
mani = {1:”name”,2:”dept”,3:”place”}
print mani.keys()
print mani.values()
for lion in mani.keys():
print lion
value = len(lion)
value1 = len(mani.keys())
print value
print value1
######################

def mark(a):
if (a <= -1):
print “invalidmark1”
elif (a < 50)&(a > 0):
print “this stdent fail mark”
elif (a < 70):
print “this is student pass mark”
elif (a <= 100):
print “this is first class student ”
elif (a > 100):
print “invalid mark”
print mark(71)
###################
dict = {1,2,1,0,1,54,5,6,7,9}
print dict
#####################
dict1 = {1:0,2:1,3:1,3:1,1:1}
print dict1.keys()
#####################
def whie(table,n):
i = 1
while (i <= n):
#e=i*table
print “%d * %d = %d” %(i, table,(i*table))
i= i + 1

#e = e + table
whie(7,15)
#################
def whie(n):
i = 1
table = 5

while i <= n:
e=i*table
print “%d * %d = %d” %(i, table,e)
i= i + 1

#e = e + table
whie(10)

######################
###while pechasing cerainitems a discont of 10% pffered if the quanity purchased in more than 1000if
###quentity and price per item are input the though keyboardwrite program calculatethe total expanses##
qty = 1200
rate= 15.50
if(qty>1000):
dis = 10
tot =(qty * rate)-(qty*rate*dis/100)
print tot
#####################
#the current year and the the year in which the employee
#joined organization are entered through the keyboard if the number of year for which the employee has served the organization is greater than 3
#then a bonus of rs.2500/-is given to the employee if the years of service are not greater than 3 then the program should do nothing
cy=2008
yoi=2003
yos = cy – yoi
bonus = 2500
if(yos>3):
print bonus
else:
print “no bonus”
##############nested if else###########################
i=2
if(i==1):
print i
else:
if(i==2):
print i
else:
print “not equal”
########################
#mark obytained 5 student
#percentage above or equal to 60 – first division
#percentage btweeen 50 and 59 – second division
#percentage btweeen 40 and 49 – third division
# percntage less than fail
per = 30
if(per >= 60):
print “first division”
else:
if(per>=50):
print “second division”
else:
if(per>=40):
print “third division”
else:
print “less than fail”
#############this is problem i amdoing logical operator####
per = 79
if(per>60):
print “first division”
if(per>=50)&(per<60):
print “second division”
if(per>=40)&(per<40):
print “third division”
if(per<40):
print “less than fail”
###############elseif#################
per=50
if(per>60):
print “first division”
elif(per>=50):
print “second division”
elif(per>=40):
print “thrd division”
else:
print “less than fail”
###########################

###a company insures its diver in the follwingases
#if the driver is married
#if the driver is UNmarried,MALE&above30yearsof age
#if the driver is UNmarried,FEMALE&above25yearsof age
sex =”male”
ms =
age=
if(ms=”M”)
print “driver insure”
if(sex=”male)
if(age>30):
print “driver insure”
else:
print “driver not insure”
else:
if(age>25):
print “driver insure”
else:
print “driver not insure”
#################logical operator#############
ms=’m’
sex=’male’
age=20
if ((ms==’m’)|((ms==’um’)&(sex==’male’)&(age>30))|((ms==’um’)&(sex==’female’)&(age>25))):
print ‘driver insure’
else:
print ‘driver not insure’
###################################
####gender##yearofservice##qualification#######logical operator#############
####male ## >=10#PG#15000
####male ## >=10#G#10000
####male ## >10#PG#10000
####male ## <10#G#7000
####FEmale ## >=10#PG#12000
####female ## >=10#G#9000
####female ## >10#PG#10000
####female ## <10#G#6000
gen=’f’
qual=’g’
year = 9
if((gen==’m’)&(qual==’pg’)&(year>=10)):
print 15000
elif((gen==’m’)&(qual==’g’)&(year>=10)):
print 10000
if((gen==’m’)&(qual==’pg’)&(year<10)):
print 10000
if((gen==’m’)&(qual==’pg’)&(year<10)):
print 7000
if((gen==’m’)&(qual==’pg’)&(year>=10)):
print 15000
elif((gen==’f’)&(qual==’pg’)&(year>=10)):
print 12000
elif((gen==’f’)&(qual==’g’)&(year>10)):
print 9000
elif((gen==’f’)&(qual==’pg’)&(year<10)):
print 10000
elif((gen==’f’)&(qual==’g’)&(year<10)):
print 6000
########################
a = 300
b = 200
if(a>b):
a = 300
else:
b = 200
print a + 400
#################
a = 3
b = 3.0
if(a==b):
print True
else:
print False
#################
a=10
b=20
if(a==b):
print “equal”
else:
print “not equal”
##############
b=a=10
z=a<10
print b
print z
##############
a=10
b=20
c=30
d=40
if(a>5):
print a
if(b>10):
b=a+a
if(c>30):
c=b+a+a
if(d>10):
d=a+b+c+d
print b
print c
print d
######float#######
a=18.5
b=18.6
if(a==b):
print a
else:
print b
###########
i=586
k=452
if(i>=k):
i=k
k=i
print k
print i
##############false?##########
i=56
k=452
if(i>=k):
i=k
k=i
print k
print k
#####################
a=’x’
b= ‘X’
if(a==b):
print True
else:
print False
#####################
a=’x’
b= ‘x’
if(a==b):
print True
else:
print False
#####################
a=’10’
b=’10’
if(a==b):
print True
else:
print False
######################
a=’10’
b=’10.0′
if(a==b):
print True
else:
print False
####################
a=10
b=10.0
if(a==b):
print True
else:
print False
#################
######this is or operator###########
a=10
b=10
if(a==10)|(a!=10):
print True
else:
print False
#####this is and operator################
a=10
b=10
if(a==10)&(a!=10):
print True
else:
print False
#####this is or gate#########
a=0
b=0
z=a|b
a=0
b=1
z1=a|b
a=1
b=0
z2=a|b
a=1
b=1
z3=a|b
print z
print z1
print z2
print z3
#################this is and gate#############
a=0
b=0
z=a&b
a=0
b=1
z1=a&b
a=1
b=0
z2=a&b
a=1
b=1
z3=a&b
print z
print z1
print z2
print z3
##################THIS IS NOT GATE###########
a=255
b=200
if(a>b)&(a<b):
print True
else:
print False
###########
i=10
j=20
if(i|j==20):
print True
else:
print False
####################
def smallnum(a,b,c):
if(a<b)&(a<c):
print a
elif(b<c):
print b
else:
print c
print smallnum(10,20,30)
###########################
def small(a,b,c,d,e):
if(a<b)&(a<c)&(a<d)&(a<e):
print a
elif(b<c)&(b<d)&(b<e):
print b
elif(c<d)&(c<e):
print c
elif(d<e):
print d
else:
print e
print small(101,220,303,404,95)
######################
######welcome to while################
count = 0
while(count<100):
count=count+1
print count
############################
tot=0
while(tot<10):
tot=tot+1
print tot
######################

tot=0
while(tot<10):
tot=tot+1
print tot
tot=0
##############.
i=11
while(i>=1):
i=i-1
print i
##################
a=2
while(a<=10):
a=a+0.1
print a
####################
i=1
while(i<=3273):
i =i+1
print i
################
i = 0
while(i<=5):
i=i+1
print i
##################################
i = 0
while(i<=5):
print i
i=i+1
# # # # # # # # # # # # # # # # # # #
i=1
while(i<=3276):
print i
i=i+1
###########################################
######################3#
i=1
while(i<=10):
print i
i=i+1
#########################
i=1
while(i<=10):
print i
i+=1
###########################
##################################
fruits=[‘asas’,’asassas’,’agagagag’]
for lion in fruits:
print lion
############################
asp=[1,2,3,4,5]
for num in asp:
print num
##################““““““`
words=[‘ggggggfg’,’ygyg’,’hhhhhhhg’]
for q in words:
print q,len(q)
##########################################
print range(5,10)
#####################################
a=[‘a’,’bbb’,’vvvv’,’ddddddd’,’qqqwwwwe’]
for i in range(len(a)):
print i,a[i]
##################################
for tot in range(1,11):
print tot

#####
######isalpha it is check condition int means condition false
#char means true
a=”aaaaa”
print a.isalpha()
#########
pyg = ‘ay’
word=”hello”

original = raw_input(‘Enter a word:’)

if len(original) > 0 and original.isalpha():

word=original.lower()

first=word[0]

new_word = word+first+pyg

print new_word

else:

print ’empty’
################
pyg = ‘ay’
word=”Hello”
original = raw_input(‘Enter a word:’)
if len(original) > 0 and original.isalpha():
word=original.lower()
first=word[1]
new_word = first+word+pyg
new_word = new_word[1:len(new_word)]
new_word == first+word+pyg
print new_word
else:
print ’empty’
#######################
def tax(bill):
“””Adds 8% tax to a restaurant bill.”””
bill *= 1.08
print “With tax: %f” % bill
return bill

def tip(bill):
“””Adds 15% tip to a restaurant bill.”””
bill *= 1.15
print “With tip: %f” % bill
return bill

meal_cost = 100
meal_with_tax = tax(meal_cost)
meal_with_tip = tip(meal_with_tax)

 

#string character
var1 = “manikandan”
print var1[0]
print var1[:9]
print var1[2:9]
print “var1[0]:”,var1[0]
print “var1[:9]:”,var1[:9]
print “var1[2:9]:”,var1[2:9]
##update string its exsiting string reassisigning variable anther string
string = “life is beautiful”
print string[8:] + ‘not be beautiful’
print “string[8:]:”,string[8:]
print “udate string:-“,”life is” + string[8:]
print “update string:-“,string[:8] + “not beaytiful”
#############PYTHON FORMATTING STRING
###3PYTHON FORMAT OPERATOR IS UNIQUE TO STRING AND MAKEUP FORPACK OF HAVING FUNCTION
print “mani is %s of the best person %s this world” % (‘one’,’in’)
print “mani is %u of the best person %s this world” % (-1,’in’)
#########unicode string normaly string contain 8 bit
##but unicode string are stored 16 character
print u”gdtg, cfv”

print “hgggggggggggg”

#absolute value of x and positive
print “www(-45) :”, abs(-45)
#comparesion between two number if(a>b)-1=if(a<b)1=if(a=b)0
print “cmp(10,11):”, cmp(10,11)
print “cmp(10,11):”, cmp(10,10)
print “cmp(10,11):”, cmp(11,10)
#########fabs its contain real variable

###########
import math # This will import math module

print “math.fabs(-45.17) : “, math.fabs(-45.17)
print “math.fabs(100.12) : “, math.fabs(100.12)
print “math.fabs(100.72) : “, math.fabs(100.72)
print “math.fabs(119L) : “, math.fabs(119L)
print “math.fabs(math.pi) : “, math.fabs(math.pi)

##########
import math
print “math.fabs(1.23):”,math.fabs(1.23)

###def
def add(a):
return a
a=10
print add(a)
###keyword augument
def add1(name,age):
print ‘name:’,name
print ‘age:’,age
return
print add1(age=50,name=’mani’)
#default arugument assumedefault value
#the value can beasume default
def lion(name,age=35):
print ‘name:’,name
print ‘age:’,age
return
print lion(‘mani’,18)
print lion(‘siva’)
############lambda function
sum =lambda a,b:a+b*a*b

print sum(1,2)
###############
x=10
def manik(a,b,c):
global x
return a+b+c
print manik(1,2,3)
#object and class
class new:
line1=10
line2=20
line3=30
line4=40
lio=new()
print lio.line1
#class with function
class new1:
var1=1
var2=2
var3=3
var4=4
def mani(self):
return “life is beautiful”
lioa=new1()
print lioa.var1
print lioa.var2
print lioa.var3
print lioa.var4
print lioa.mani()
#class with sub super class
class sarn:
li1=10
li2=11
li3=12
li4=14
class miruna(sarn):
li1=11
value=miruna()
print value.li3
print value.li1

def mani(a):
if (a==50)&&(a)
print “this is syudent just pass mark”
elif (70 < a):
print “just pass mark”
elif (71 > a):
print “this is student first class mark”
elif (a ==100):
print “this is first mark”
print mani(69)
####################
def whie(n):
i = 1
table = 5
e= i*table
while i <= n:
print “%d * %d = %d” %(i, table,e)
i= i + 1

e = e + table
whie(10)

###########without using sort
collection = [1,2,3,4,5,6,7,8,9]
print len(collection)
##########3
forest = [21,15,55,89,76,45,12,35]
for hi in forest:
print hi
########################
siva = {1:”aaas”,2:”bbbb”,3:”ccccc”,4:”ddddd”,5:”eeee”}
print siva.keys()
print siva.values()
print (siva.keys()[0])
print (siva.keys()[3])
print (len(siva.keys()))
#################################
mani = {1:”name”,2:”dept”,3:”place”}
print mani.keys()
print mani.values()
for lion in mani.keys():
print lion
value = len(lion)
value1 = len(mani.keys())
print value
print value1
######################

def mark(a):
if (a <= -1):
print “invalidmark1”
elif (a < 50)&(a > 0):
print “this stdent fail mark”
elif (a < 70):
print “this is student pass mark”
elif (a <= 100):
print “this is first class student ”
elif (a > 100):
print “invalid mark”
print mark(71)
###################
dict = {1,2,1,0,1,54,5,6,7,9}
print dict
#####################
dict1 = {1:0,2:1,3:1,3:1,1:1}
print dict1.keys()
#####################
def whie(table,n):
i = 1
while (i <= n):
#e=i*table
print “%d * %d = %d” %(i, table,(i*table))
i= i + 1

#e = e + table
whie(7,15)
#################
def whie(n):
i = 1
table = 5

while i <= n:
e=i*table
print “%d * %d = %d” %(i, table,e)
i= i + 1

#e = e + table
whie(10)

#################what is string#####################
#a string is text information##
##this is upper case letter##
str=”LIFE is beautiful”
print str
##this is string i have do upper case letter##
largechr = str.upper()
print largechr
###this is small char##
smallchar = str.lower()
print smallchar
#########i want replace particular char###############
love = ‘hi everybody pls love in your life’
love1 = love.replace(‘your’, ‘our’)
print love1
#############find option in string########
string = ‘hi love is very great feeling’
stringfind = string.find(‘love’)
print stringfind
##############i want add particular string in string#########
hum = ‘hi i am manikandan i got only %s in degree’ %(70)

 

print hum

bool_one = False
bool_two = not 3**4<4**3
bool_three = not 10 % 3 <= 10 % 2
bool_four = not 3**2+4**2!=5**2
bool_five = not not False
################
bool_one = False or not True and True
bool_two = False and not True or True
bool_three = True and not (False or False)
bool_four = not not True or False and not True
bool_five = False or not (True and True)
################
# Use boolean expressions as appropriate on the lines below!
# Make me false!

bool_one = (2 <= 2) and “Alpha” == “Bravo”
# We did this one for you!

# Make me true!

bool_two = (23 <= 24) and “mani” == “mani”
# Make me false!

bool_three = (56 >= 23) and “mani” == “siva”
# Make me true!

bool_four = (12 == 12) and “naveen” == “naveen”
# Make me true!

bool_five = (12 != 11) or “asasas” == “cvxvx”
##################

response =”Y”

answer = “Left”
if answer == “Left”:
print “This is the Verbal Abuse Room, you heap of parrot droppings!”

# Will the above print statement print to the console?
# Set response to ‘Y’ if you think so, and ‘N’ if you think not
####################
def using_control_once():
if(10>2):
return “Success #1”

def using_control_again():
if(12<13):
return “Success #2”

print using_control_once()
print using_control_again()
################################
answer = “‘Tis but a scratch!”

def black_knight():
if answer == “‘Tis but a scratch!”:
return True
else:
return # Make sure this returns False

def french_soldier():
if answer == “Go away, or I shall taunt you a second time!”:
return True
else:
return # Make sure this returns False
#####################################
def greater_less_equal_5(answer):
if(answer>5):
return 1
elif(answer<5):
return -1
else:
return 0

print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)
###########
def the_flying_circus():
# Start coding here!
if(1 == 1) and (5 == 5):
return True
elif(1 != 1) or (5 == 6):
return True
else:
return False
print the_flying_circus()
#######################

def whie(n):
i = 1
while i <= n:
print i
i = i + 1
print whie(10)
###################.
factorial
“#############
def fact(n):
result = 1
while n >= 1:
result = result * n
n = n – 1
return result
print fact(8)
##############
def fact(n):
sum = 0
while n >= 1:
sum = sum + n
n = n – 1
return sum
print fact(5)
def fact(n):
sum = 0
while n >= 1:
sum = sum + n
n = n – 1
return sum

print fact(5)

 

class a:
b=1
c=2
d=3
e=4
print a.b
print a.c
print a.d
print a.e
class a:
mani=12
siva=13
arun=23
live=45
class b(a):
lion=110
lop=234
liop=333
print b.mani
print b.lion
def add(var):
var+=10
return var
x=12
y=add(x)
print x,y
var=”mani”
def mani():
global var
var=”siva”
return var
print mani()
def func():
”’i love my friends”’
#only my friend
pass
print func.__doc__
def mul(x,y):
return x*y
#factorial
print reduce(mul,range(1,11))
print reduce(lambda x, y: x+y, range(1, 11))
a,b=0,1
while b<200:
print b
a,b=b,a+b
a=[‘abcd’,’bfffdf’,’sfsfsc’]
for x in a:
print x, len(x)
a,b=0,1
c=input(“enter input num:”)
while(b<c):
print b
a,b=b,a+b
\
for n in range(1, 1000):
for x in range(2, n):
if n % x == 0:
break
else:
# loop fell through without finding a factor
print n, ‘is a prime number’
z=input(“enter input num:”)
for n in range(1,z):
for x in range(2,n):
if n%x==0:
break
else:
print n
#===============================================================================
def perm(l):
# Compute the list of all permutations of l
if len(l) <= 1:
return [l]
r = [] # here is new list with all permutations!
for i in range(len(l)):
s = l[:i] + l[i+1:]
p = perm(s)
for x in p:
r.append(l[i:i+1] + x)
return r
a=[1,2,3,4]
print perm(a)
def fact(n):
if n==0:
return 1
else:
return n*fact(n-1)
print fact(5)
num=1
while(n>=1):
num=num*n
n=n-1
return num
print a(5)