a = lambda x,y : x+y
print(a(5, 6))
11
class Person():#methoddef inputName(self,fname,lname): self.fname=fname self.lastname=lastname#methoddef showFullName() (self):print(self.fname+" "+self.lname)person1 = Person() #object instantiation person1.inputName("Ratan","Tata") #calling a method inputName person1. showFullName() #calling a method showFullName()
Note : whenever you define a method inside a class, the first argument to the method must be self (where self – is a pointer to the class instance).
a=2
def add():
b=3
c=a+b
print(c)
add()
5
import array as arr
My_Array=arr.array('i',[1,2,3,4])
My_list=[1,'abc',1.20]
print(My_Array)
print(My_list)
array(‘i’, [1, 2, 3, 4]) [1, ‘abc’, 1.2]
pass
keyword represents a null operation in Python. It is generally used for the purpose of filling up empty blocks of code which may execute during runtime but has yet to be written. Without the pass statement in the following code, we may run into some errors during code execution.def myEmptyFunc():
# do nothing
pass
myEmptyFunc() # nothing happens
# File "<stdin>", line 3
# IndentationError: expected an indented block
xrange()
and range()
are quite similar in terms of functionality. They both generate a sequence of integers, with the only difference that range()
returns a Python list, whereas, xrange()
returns an xrange object.range()
, xrange()
doesn't generate a static list, it creates the value on the go. This technique is commonly used with an object type generators and has been termed as "yielding".range()
can lead to a Memory Error in such conditions, while, xrange()
can handle it optimally by using just enough memory for the generator (significantly less in comparison).for i in xrange(10): # numbers from o to 9
print i # output => 0 1 2 3 4 5 6 7 8 9
for i in xrange(1,10): # numbers from 1 to 9
print i # output => 1 2 3 4 5 6 7 8 9
for i in xrange(1, 10, 2): # skip by two for next
print i # output => 1 3 5 7 9
xrange
has been deprecated as of Python 3.x.
Now range does exactly the same what xrange used to do in Python 2.x
, since it was way better to use xrange()
than the original range()
function in Python 2.x
.pickle.dump()
.pickle.load()
.## generate fibonacci numbers upto n
def fib(n):
p, q = 0, 1
while(p < n):
yield p
p, q = q, p + q
x = fib(10) # create generator object
## iterating using __next__(), for Python2, use next()
x.__next__() # output => 0
x.__next__() # output => 1
x.__next__() # output => 1
x.__next__() # output => 2
x.__next__() # output => 3
x.__next__() # output => 5
x.__next__() # output => 8
x.__next__() # error
## iterating using loop
for i in fib(10):
print(i) # output => 0 1 1 2 3 5 8
.py
files contain the source code of a program. Whereas, .pyc
file contains the bytecode of your program. We get bytecode after compilation of .py
file (source code). .pyc
files are not created for all the files that you run. It is only created for the files that you import..py
file. If found, compiles it to .pyc
file and then python virtual machine executes it..pyc
file saves you the compilation time.numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers[1 : : 2]) #output : [2, 4, 6, 8, 10]​
Arr[-1]
means last element of array Arr[]
arr = [1, 2, 3, 4, 5, 6]
#get the last element
print(arr[-1]) #output 6
#get the second last element
print(arr[-2]) #output 5​
_init__ ()
is the first method of a class. Whenever we try to instantiate an object __init__()
is automatically invoked by python to initialize members of an object. We can't overload constructors or methods in Python. It shows an error if we try to overload.class student:
def __init__(self,name):
self.name = name
def __init__(self, name, email):
self.name = name
self.email = email
# This line will generate an error
#st = student("chanti")
# This line will call the second constructor
st = student("chanti", "chanti@gmail.com")
print(st.name)
chanti
string = "IT IS IN LOWERCASE."
print(string.swapcase())
string = "it is in uppercase."
print(string.swapcase())
it is in lowercase.
IT IS IN UPPERCASE.
join()
is defined as a string method which returns a string value. It is concatenated with the elements of an iterable. It provides a flexible way to concatenate the strings. See an example below.str = "Chanti"
str2 = "ab"
# Calling function
str2 = str.join(str2)
# Displaying result
print(str2)
aChantib
Python 3
, the old Unicode type has replaced by "str
" type, and the string is treated as Unicode by default. We can make a string in Unicode by using art.title
.encode("utf-8
") function. # Decorator example
def decoratorfun():
return another_fun
>>> dict = {'Country': 'India', 'Hero': 'Sivaji', 'Cartoon': 'Chanti'}
>>>print dict[Country]
India
>>>print dict[Hero]
Sivaji
>>>print dict[Cartoon]
Chanti
Python 2.x
is an older version of Python. Python 3.x
is newer and latest version. Python 2.x
is legacy now. Python 3.x
is the present and future of this language.Hello
", and in Python 3, it is print ("Hello
").ASCII
implicitly, and in Python3 it is Unicode.xrange()
method has removed from Python 3 version. A new keyword as is introduced in Error handling.enumerate()
function is used to iterate through the sequence and retrieve the index position and its corresponding value at the same time.For i,v in enumerate(['Python','Java','C++']):
print(i,v)
0 Python
1 Java
2 C++
# enumerate using an index sequence
for count, item in enumerate(['Python','Java','C++'], 10):
>>> a,b=2,3
>>> min=a if a<b else b
>>> min
>>> print("Hi") if a<b else print("Bye")
>>> myname='Ramana'
>>> Myname
File “<pyshell#3>”, line 1, in <module>
Myname
’ is not defined.pythonrc.py
in Unix, and it contains commands that load utilities or modify PYTHONPATH.map()
function in Python has two parameters, function and iterable. The map()
function takes a function as an argument and then applies that function to all the elements of an iterable, passed to it as another argument. It returns an object list of results.def calculateSq(n):
return n*n
numbers = (2, 3, 4, 5)
result = map( calculateSq, numbers)
print(result)
for line in reversed(list(open(filename.txt))):
print(line.rstrip())
__init__
is a reserved method in Python classes. The __init__
method is called automatically whenever a new object is initiated. This method allocates memory to the new object as soon as it is created. This method can also be used to initialize variables. append()
and extend()
methods are methods used to add elements at the end of a list.append()
methodextend()
method# monkeyy.py
class X:
def func(self):
print "func() is being called"
monkeyy
) is used to change the behavior of a function at the runtime as shown below:import monkeyy
def monkey_f(self):
print "monkey_f() is being called"
func
” with “monkey_f
”monkeyy.X.func = monkey_f
obj = monk.X()
func
” whose address got replacedmonkey_f()
”obj.func()
re
.”re
” expression that can check the email id for .com
and .co.in
subdomain.import re
print(re.search(r"[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$","info@freetimelearning.com"))
call-by-value
, the argument whether an expression or a value gets bound to the respective variable in the function.call-by-reference
” and “pass-by-reference
” interchangeably. When we pass an argument by reference, then it is available as an implicit reference to the function, rather than a simple copy. In such a case, any modification to the argument will also be visible to the caller.id()
is one of the built-in functions in Python.Signature: id(object)
print()
function always prints a newline in the end. The print()
function accepts an optional parameter known as the ‘end.’ Its value is ‘\n
’ by default. We can change the end character in a print statement with the value of our choice using this parameter.# Example: Print a instead of the new line in the end.
print("Let's learn" , end = ' ')
print("Python")
# Printing a dot in the end.
print("Learn to code from freetimelearn" , end = '.')
print("com", end = ' ')
Let's learn Python
Learn to code from freetimelearn.com
rstrip()
method which duplicates the string but leaves out the whitespace characters from the end.rstrip()
escapes the characters from the right end based on the argument value, i.e., a string mentioning the group of characters to get excluded.rstrip()
is :str.rstrip([char sequence/pre>
#Example
test_str = 'Programming '
# The trailing whitespaces are excluded
print(test_str.rstrip())
[ expression(var) for var in iterable ]
>>> alist = [var for var in range(10, 20)]
>>> print(alist)
copy.copy()
function :copy.deepcopy()
function :Flask-WTF
offers simple integration with WTForms
. Features include for Flask WTF
are Integration with wtforms Secure form with csrf token Global csrf protection Internationalization integration Recaptcha supporting File upload that works with Flask Uploadsdir()
function of Python ,on an instance shows the instance variables asdir()
we can find all the methods & attributes of the object’s classhelp()
and dir()
both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions.help()
function is used to display the documentation string and also facilitates you to see the help related to modules, keywords, attributes, etc.dir()
function is used to display the defined symbols.%s
format specifier. The formatting operation in Python has the comparable syntax as the C function printf()
has.speeddel()
method.>>> site_stats = {'site': 'freetimelearning.com', 'traffic': 10000, "type": "organic"}
>>> del site_stats["type"]
>>> print(site_stats)
{'site': 'google.co.in', 'traffic': 1000000}
pop()
function. It accepts the key as the parameter. Also, a second parameter, we can pass a default value if the key doesn’t exist.>>> site_stats = {'site': 'freetimelearning.com', 'traffic': 10000, "type": "organic"}
>>> print(site_stats.pop("type", None))
organic
>>> print(site_stats)
{'site': 'freetimelearning.com', 'traffic': 10000}
default_statment
if Condition else another_statement
>>> no_of_days = 366
>>> is_leap_year = "Yes" if no_of_days == 366 else "No"
>>> print(is_leap_year)
Yes
func()
, then func()
in class B can override func()
in class A. Similarly, a method of class A can call another method defined in A that can invoke a method of B that overrides it. MySQLdb
Establish a connection to the database. db = MySQLdb.connect(“host”=”local host”, “database-user”=”user-name”, “password”=”password”, “database-name”=”database”)
Initialize the cursor variable upon the established connection: c1 = db.cursor()
Retrieve the information by defining a required query string. s = “Select * from dept”
Fetch the data using fetch()
methods and print it. data = c1.fetch(s)
Close the database connection. db.close()
list1 = [‘A’, ‘B’,’C’] and list2 = [10,20,30]. zip(list1, list2) # results in a list of tuples say [(‘A’,10),(‘B’,20),(‘C’,30)]
import pandas as pd
import numpy as np
df = pd.DataFrame({‘A’:[3,1,1],’B’:[1,3,2]})
sort = df.sort_values(by = ‘B’)
print(sort)
heap-max
the key at root should be maximum among all the keys present in the heap. The same property must be recursively true for all nodes.heap-min
the key at root should be minimum among all the keys present in the heap. The same property should be recursively true for all nodes.https://www.python.org/downloads/
PYTHON_NAME
then copy the path and paste it.edit
’.%PYTHON_NAME%
.class x:
pass
obj=x()
obj.id="123"
print("Id = ",obj.id)
123
start()
on the new thread. The thread is taken forward for scheduling purposes.join()
and sleep()
takes place. # Enter number of terms needed #0,1,1,2,3,5....
a=int(input("Enter the terms"))
f=0 #first element of series
s=1 #second element of series
if a<=0:
print("The requested series is
",f)
else:
print(f,s,end=" ")
for x in range(2,a):
next=f+s
print(next,end=" ")
f=s
s=next</pre>
Output : Enter the terms 5 0 1 1 2 3
a=input("enter sequence")
b=a[::-1]
if a==b:
print("palindrome")
else:
print("Not a Palindrome")
list = ["1", "4", "0", "6", "9"]
list = [int(i) for i in list]
list.sort()
print (list)
Django-admin.py
. It possesses the following usage :sys.path
.DJANGO_SETTING_MODULE
environment variable to point to your project's setting.py
file.Django-admin.py
is a command-line argument which is utilised for administrative tasks. server-side
at the interaction by the web application. By default, session reserves in the database and allows file-based
and cache-based
sessions. Set_cookie
: this method is used to set
the values of the cookieGet_cookie
: this method is used to get
the values of the cookie__init__()
and the __next__()
methods. When you are making use of iterators in Django, the best situation to do it is when you have to process results that will require a large amount of memory space. To do this, you can make use of the iterator()
method which basically evaluates a QuerySet and returns the corresponding iterator over the results.