Python Doc (2)
Python Doc (2)
Introduction to Python
Python Print Statement
Python Variable
Python Data Type
Python Operators
Python If elif else
Python For Loop
Python While Loop
Python break, continue
Python String
Python Lists
Python Dictionary
Python Tuples
Python Sets
Python User define function
Python Classes
Python Built-in Functions
Introduction to Python
Python is an open source, object-oriented, high-level powerful programming language.
Developed by Guido van Rossum in the early 1990s. Named after Monty Python
Python runs on many Unix variants, on the Mac, and on Windows 2000 and later.
Available for download from http://www.python.org.
Features of Python
Open source: Python is publicly available open source software, any one can use source
code that doesn't cost anything.
Easy-to-learn: Popular (scripting/extension) language, clear and easy syntax, no type
declarations, automatic memory management, high-level data types and operations, design to
read (more English like syntax) and write (shorter code compared to C, C++, and Java) fast.
High-level Language:
High-level language (closer to human) refers to the higher level of concept from machine
language (for example assembly languages). Python is an example of a high-level language
like C, C++, Perl, and Java with low-level optimization.
Portable:
High level languages are portable, which means they are able to run across all major
hardware and software platforms with few or no change in source code. Python is portable
and can be used on Linux, Windows, Macintosh, Solaris, FreeBSD, OS/2, Amiga, AROS,
AS/400 and many more.
Object-Oriented: Python is a full-featured object-oriented programming language, with
features such as classes, inheritance, objects, and overloading.
Python is Interactive :
Python has an interactive console where you get a Python prompt (command line) and
interact with the interpreter directly to write and test your programs. This is useful for
mathematical programming.
Interpreted: Python programs are interpreted, takes source code as input, and then compiles
(to portable byte-code) each statement and executes it immediately. No need to compiling or
linking
Extendable: Python is often referred to as a "glue" language, meaning that it is capable to
work in mixed-language environment. The Python interpreter is easily extended and can add
a new built-in function or modules written in C/C++/Java code.
The final 2.x version 2.7 release came out in mid-2010, with a statement of extended support
for this end-of-life release. Python 3.0 was released in 2008. The 2.x release will see no new
major releases after that. 3.x is under active development and has already seen over several
years of stable releases, including version 3.3 in 2012, 3.4 in 2014, and 3.5 in 2015.
If you're new to programming or an experienced developer, it's easy to learn and use Python
3. Python 3 represents the future of the language as all development has stopped with Python
2.x, save for security and bug fixes.
Comments in Python:
A comment begins with a hash character(#) which is not a part of the string literal and ends at the end
of the physical line. All characters after the # character up to the end of the line are part of the
comment and the Python interpreter ignores them. See the following example. It should be noted that
Python has no multi-lines or block comments facility.
Indentation:
Python uses whitespace (spaces and tabs) to define program blocks whereas other
languages like C, C++ use braces ({}) to indicate blocks of codes for class, functions or flow
control. The number of whitespaces (spaces and tabs) in the indentation is not fixed, but all
statements within the block must be the indented same amount. In the following program,
the block statements have no indentation.
as el if or yield
The print statement has been replaced with a print() function, with keyword arguments to replace most
of the special syntax of the old print statement.
The print statement can be used in the following ways:
print("Good Morning")
print("Good", <Variable Containing the String>)
print("Good" + <Variable Containing the String>)
print("Good %s" % <variable containing the string>)
In Python, single, double and triple quotes are used to denote a string. Most use single quotes when
declaring a single character. Double quotes when declaring a line and triple quotes when declaring a
paragraph/multiple lines.
print('Hello')
print("Python is very simple language")
print("""Python is very popular language.
It is also friendly language.""")
Variable Use:
Strings can be assigned to variable say string1 and string2 which can called when using the print
statement.
str1 = 'Wel'
print(str1,'come')
str1 = 'Welcome'
str2 = 'Python'
print(str1, str2)
String Concatenation:
String concatenation is the "addition" of two strings. Observe that while concatenating there will be no
space between the strings.
str1 = 'Python'
str2 = ':'
print('Welcome' + str1 + str2)
Using as String:
%s is used to refer to a variable which contains a string.
str1 = 'Python'
print("Welcome %s" % str1)
Using other data types:
Similarly, when using other data types
%d -> Integer
%e -> exponential
%f -> Float
%o -> Octal
%x -> Hexadecimal
print("Exponential equivalent of the number = %e" %15)
print("Hexadecimal equivalent of the number = %x" %15)
Using multiple variables:
When referring to multiple variables parenthesis is used.
str1 = 'World'
str2 = ':'
print("Python %s %s" %(str1,str2))
\n is used for Line Break
print("Sunday\nMonday\nTuesday\nWednesday\nThursday\nFriday\
nSaturday")
Example-3:
Any word print multiple times.
print('-w3r'*5)
\t is used for tab.
print("""
Language:
\t1 Python
\t2 Java\n\t3 JavaScript
""")
Multiple Assignment
The basic assignment statement works for a single variable and a single expression. You can also
assign a single value to more than one variables simultaneously.
var1=var2=var3...varn= = <expr>
>>> x = y = z = 1
Swap variables
Python swap values in a single line and this applies to all objects in python.
Syntax:
var1, var2 = var2, var1
Example:
>>> x = 10
>>> y = 20
>>> print(x)
10
>>> print(y)
20
>>> x, y = y, x
>>> print(x)
20
>>> print(y)
10
>>>
In Python, variables that are only referenced inside a function are implicitly global. If a variable is
assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly
declared as global.
Example:
var1 = "Python"
def func1():
var1 = "PHP"
print("In side func1() var1 = ",var1)
def func2():
print("In side func2() var1 = ",var1)
func1()
func2()
Output:
In side func1() var1 = PHP
In side func2() var1 = Python
You can use a global variable in other functions by declaring it as global keyword :
Example:
def func1():
global var1
var1 = "PHP"
print("In side func1() var1 = ",var1)
def func2():
print("In side func2() var1 = ",var1)
func1()
func2()
Output:
In side func1() var1 = PHP
In side func2() var1 = PHP
Numbers
Numbers are created by numeric literals. Numeric objects are immutable, which means when an
object is created its value cannot be changed.
Python has three distinct numeric types: integers, floating point numbers, and complex numbers.
Integers represent negative and positive integers without fractional parts whereas floating point
numbers represents negative and positive numbers with fractional parts. In addition, Booleans are a
subtype of plain integers. See the following statements in Python shell.
Output:
8
>>> count **=4
>>> count
Output:
4096
>>> count /=4
>>> count
Output:
1024.0
>>> count//=4
>>> count
Output:
256.0
>>> 15.0 //2
Output:
7.0
Order of operations
>>> (3+12) / 3
>>> 15 / (3 + 2)
Output:
5.0
3.0
Boolean (bool)
The simplest build-in type in Python is the bool type, it represents the truth values False and True.
See the following statements in Python shell.
Strings
In Python, a string type object is a sequence (left-to- right order) of characters. Strings start and end
with single or double quotes Python strings are immutable. Single and double quoted strings are
same and you can use a single quote within a string when it is surrounded by double quote and vice
versa. Declaring a string is simple, see the following statements.
Special characters in strings
The backslash (\) character is used to introduce a special character. See the following table.
Escape sequence Meaning
\n Newline
\t Horizontal Tab
\\ Backslash
Index (from 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
left)
See the following statements to access single character from various positions.
Strings are immutable
Strings are immutable character sets. Once a string is generated, you cannot change any
character within the string. See the following statements.
The 'in' operator is used to check whether a character or a substring is present in a string or
not. The expression returns a Boolean value. See the following statements.
String Slicing
To cut a substring from a string is called string slicing. Here two indices are used separated
by a colon (:). A slice 3:7 means indices characters of 3rd, 4th, 5th and 6th positions. The
second integer index i.e. 7 is not included. You can use negative indices for slicing. See the
following statements.
Conversion
>>> float("4.5")
>>> int("25")
>>> int(5.625)
>>> float(6)
>>> int(True)
>>> float(False)
>>> str(True)
>>> bool(0)
>>> bool('Hello world')
>>> bool(223.5)
Output:
4.5
25
5
6.0
1
0.0
'True'
False
True
True
Tuples
A tuple is a container which holds a series of comma-separated values (items or elements) between
parentheses. Tuples are immutable (i.e. you cannot change its content once created) and can hold
mix data types.
Creating Tuples
To create an empty tuple or create a tuple with single element use the following commands.
Elements of a tuple are indexed like other sequences. The tuple indices start at 0. See the
following statements.
Tuples are immutable which means it's items values are unchangeable. See the following
statements.
Slicing a tuple
Like other sequences like strings, tuples can be sliced. Slicing a tuple creates a new tuple
but it does not change the original tuple.
Creating Lists
A list without any element is called an empty list. See the following statements.
List indices
List indices work the same way as string indices, list indices start at 0. If an index has a
positive value it counts from the beginning and similarly it counts backward if the index has a
negative value. As positive integers are used to index from the left end and negative integers
are used to index from the right end, so every item of a list gives two alternatives indices. Let
create a list called color_list with four items.
If you give any index value which is out of range then interpreter creates an error message.
See the following statements.
List Slices
Lists can be sliced like strings and other sequences. The syntax of list slices is easy :
sliced_list = List_Name[startIndex:endIndex]
This refers to the items of a list starting at index startIndex and stopping just before index
endIndex. The default values for list are 0 (startIndex) and the end (endIndex) of the list. If
you omit both indices, the slice makes a copy of the original list. See the following
statements.
Sets
A set is an unordered collection of unique elements. Basic uses include dealing with set theory (which
support mathematical operations like union, intersection, difference, and symmetric difference) or
eliminating duplicate entries. See the following statements.
Python Operators
Operators commands
Arithmetic Operators
Comparison Operators
Logical Operators
Assignment Operators
Bitwise Operator
Conditional Operators
Operator: Commands
Module of functions that provide the functionality of operators.
from operator import add, sub, mul, truediv, floordiv, mod, pow,
neg, abs
from operator import eq, ne, lt, le, gt, ge
from operator import and_, or_, not_
from operator import itemgetter, attrgetter, methodcaller
import operator as op
sorted_by_second = sorted(<collection>, key=op.itemgetter(1))
sorted_by_both = sorted(<collection>, key=op.itemgetter(1, 0))
product_of_elems = functools.reduce(op.mul, <collection>)
LogicOp = enum.Enum('LogicOp', {'AND': op.and_, 'OR' :
op.or_})
last_el = op.methodcaller('pop')(<list>)
// Floor Division x/ y The division of operands where the result is the quotient in which
the digits after the decimal point are removed.
not (x not y) If a condition is true then Logical not operator will make false.
+= x+=y x=x+y Adds 2 numbers and assigns the result to left operand.
*= x*= y x = x*y Multiplies 2 numbers and assigns the result to left operand.
/= x/= y x = x/y Divides 2 numbers and assigns the result to left operand.
%= x%= y x = x%y Computes the modulus of 2 numbers and assigns the result
to left operand.
//= x//=y x = x//y Performs floor division on operators and assign value to
the left operand.
& And x&y Bits that are set in both x and y are set.
^ Xor x^y Bits that are set in x or y but not both are set.
~ Not ~x Bits that are set in x are not set, and vice versa.
<< Shift left x <<y Shift the bits of x, y steps to the left
>> Shift right x >>y Shift the bits of x, y steps to the right.
# Each step means 'multiply by two'
* Each step means 'divide by two'
Conditional Operators
Conditional expressions or ternary operator have the lowest priority of all Python operations. The
expression x if C else y first evaluates the condition, C (not x); if C is true, x is evaluated and its value
is returned; otherwise, y is evaluated and its value is returned.
if..elif..else
The if-elif-else statement is used to conditionally execute a statement or a block of
statements. Conditions can be true or false, execute one thing when the condition is true, something
else when the condition is false.
Contents:
if statement
if .. else statement
Nested if .. else
Define a negative if
if statement
The Python if statement is same as it is with other programming languages. It executes a set of
statements conditionally, based on the value of a logical expression.
Here is the general form of a one way if statement.
Syntax:
if expression :
statement_1
statement_2
....
In the above case, expression specifies the conditions which are based on Boolean
expression. When a Boolean expression is evaluated it produces either a value of true or
false. If the expression evaluates true the same amount of indented statement(s) following if
will be executed. This group of the statement(s) is called a block.
if .. else statement
In Python if .. else statement, if has two blocks, one following the expression and other following the
else clause. Here is the syntax.
Syntax:
if expression :
statement_1
statement_2
....
else :
statement_3
statement_4
....
In the above case if the expression evaluates to true the same amount of indented statements(s)
following if will be executed and if the expression evaluates to false the same amount of indented
statements(s) following else will be executed. See the following example. The program will print the
second print statement as the value of a is 10.
a=10
if(a>10):
print("Value of a is greater than 10")
else :
print("Value of a is 10")
Output:
Value of a is 10
Flowchart:
if .. elif .. else statement
Sometimes a situation arises when there are several conditions. To handle the situation Python allows
adding any number of elif clause after an if and before an else clause. Here is the syntax.
Syntax:
if expression1 :
statement_1
statement_2
....
elif expression2 :
statement_3
statement_4
....
elif expression3 :
statement_5
statement_6
....................
else :
statement_7
statement_8
In the above case Python evaluates each expression (i.e. the condition) one by one and if a true
condition is found the statement(s) block under that expression will be executed. If no true condition is
found the statement(s) block under else will be executed. In the following example, we have applied if,
series of elif and else to get the type of a variable.
var1 = 1+2j
if (type(var1) == int):
print("Type of the variable is Integer")
elif (type(var1) == float):
print("Type of the variable is Float")
elif (type(var1) == complex):
print("Type of the variable is Complex")
elif (type(var1) == bool):
print("Type of the variable is Bool")
elif (type(var1) == str):
print("Type of the variable is String")
elif (type(var1) == tuple):
print("Type of the variable is Tuple")
elif (type(var1) == dict):
print("Type of the variable is Dictionaries")
elif (type(var1) == list):
print("Type of the variable is List")
else:
print("Type of the variable is Unknown")
Output:
Type of the variable is Complex
Flowchart:
Nested if .. else statement
In general nested if-else statement is used when we want to check more than one conditions.
Conditions are executed from top to bottom and check each condition whether it evaluates to true or
not. If a true condition is found the statement(s) block associated with the condition executes
otherwise it goes to next condition. Here is the syntax :
Syntax:
if expression1 :
if expression2 :
statement_3
statement_4
....
else :
statement_5
statement_6
....
else :
statement_7
statement_8
In the above syntax expression1 is checked first, if it evaluates to true then the program control goes
to next if - else part otherwise it goes to the last else statement and executes statement_7,
statement_8 etc.. Within the if - else if expression2 evaluates true then statement_3, statement_4 will
execute otherwise statement_5, statement_6 will execute. See the following example.
age = 38
else:
else:
Output :
You are eligible to see the Football match.
Tic kit price is $20
In the above example age is set to 38, therefore the first expression (age >= 11) evaluates to True
and the associated print statement prints the string "You are eligible to see the Football match". There
after program control goes to next if statement and the condition ( 38 is outside <=20 or >=60) is
matched and prints "Tic kit price is $12".
Flowchart:
Define a negative if
If a condition is true the not operator is used to reverse the logical state, then logical not operator will
make it false.
#create a integer
x = 20
print(x)
#uses the not operator to reverse the result of the logical expression
if not x == 50:
print('the value of x different from 50')
else:
print('the value of x is equal to 50')
Output:
20
the value of x different from 50
for loop
Like most other languages, Python has for loops, but it differs a bit from other like C or Pascal. In
Python for loop is used to iterate over the items of any sequence including the Python list, string, tuple
etc. The for loop is also used to access elements from a container (for example list, string, tuple)
using built-in function range().
Syntax:
for variable_name in sequence :
statement_1
statement_2
....
Parameter:
Name Description
variable_name It indicates target variable which will set a new value for each iteration of
the loop.
Red
Blue
Green
Black
>>>
In the above example color_list is a sequence contains a list of various color names. When the for
loop executed the first item (i.e. Red) is assigned to the variable c. After this, the print statement will
execute and the process will continue until we reach the end of the list.
The range() function returns a list of consecutive integers. The function has one, two or three
parameters where last two parameters are optional. It is widely used in for loops. Here is the syntax.
range(a)
range(a,b)
range(a,b,c)
range(a) : Generates a sequence of numbers from 0 to a, excluding a, incrementing by 1.
Syntax:
for <variable> in range(<number>):
Example:
>>> for a in range(4):
print(a)
0
1
2
3
>>>
range(a,b): Generates a sequence of numbers from a to b excluding b, incrementing by 1.
Syntax:
for "variable" in range("start_number", "end_number"):
Example:
>>> for a in range(2,7):
print(a)
2
3
4
5
6
>>>
range(a,b,c): Generates a sequence of numbers from a to b excluding b, incrementing by c.
Example:
>>> for a in range(2,19,5):
print(a)
2
7
12
17
>>>
The for loop iterates through the tuple and we test modulus of x % 2 is true or not, for every item in
the tuple and the process will continue until we rich the end of the tuple. When it is true count_even
increase by one otherwise count_odd is increased by one. Finally, we print the number of even and
odd numbers through print statements.
In the following example for loop iterates through the list "datalist" and prints each item and its
corresponding Python type.
datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12],
{"class":'V', "section":'A'}]
In the following example for loop iterates through the dictionary "color" through its keys and prints
each key.
print(key)
c2
c1
c3
>>>
print(value)
Green
Red
Orange
>>>
You can attach an optional else clause with for statement, in this case, syntax
will be -
for variable_name in sequence :
statement_1
statement_2
....
else :
statement_3
statement_4
....
The else clause is only executed after completing the for loop. If a break
statement executes in first program block and terminates the loop then the
else clause does not execute.
While loop
Loops are used to repeatedly execute a block of program statements. The basic loop structure in
Python is while loop. Here is the syntax.
Syntax:
while (expression) :
statement_1
statement_2
....
The while loop runs as long as the expression (condition) evaluates to True and execute the program
block. The condition is checked every time at the beginning of the loop and the first time when the
expression evaluates to False, the loop stops without executing any remaining statement(s). The
following example prints the digits 0 to 4 as we set the condition x < 5.
x = 0;
print(x)
x += 1
Output:
0
1
2
3
4
One thing we should remember that a while loop tests its condition before the body of the loop (block
of program statements) is executed. If the initial test returns false, the body is not executed at all. For
example the following code never prints out anything since before executing the condition evaluates
to false.
x = 10;
while (x < 5):
print(x)
x += 1
Flowchart:
The following while loop is an infinite loop, using True as the condition:
x = 10;
while (True):
print(x)
x += 1
Flowchart:
Python: while and else statement
There is a structural similarity between while and else statement. Both have a block of statement(s)
which is only executed when the condition is true. The difference is that block belongs to if statement
executes once whereas block belongs to while statement executes repeatedly.
You can attach an optional else clause with while statement, in this case, syntax will be -
while (expression) :
statement_1
statement_2
......
else :
statement_3
statement_4
......
The while loop repeatedly tests the expression (condition) and, if it is true, executes the first block of
program statements. The else clause is only executed when the condition is false it may be the first
time it is tested and will not execute if the loop breaks, or if an exception is raised. If a break
statement executes in first program block and terminates the loop then the else clause does not
execute. In the following example, while loop calculates the sum of the integers from 0 to 9 and after
completing the loop, else statement executes.
x = 0;
s = 0
s = s + x
x = x + 1
else :
Output:
x = 1;
s = 0
s = s + x
x = x + 1
if (x == 5):
break
else :
Output:
Flowchart:
break statement
The break statement is used to exit a for or a while loop. The purpose of this statement is to end the
execution of the loop (for or while) immediately and the program control goes to the statement after
the last statement of the loop. If there is an optional else statement in while or for loop it skips the
optional clause also. Here is the syntax.
Syntax:
while (expression1) :
statement_1
statement_2
......
if expression2 :
break
for variable_name in sequence :
statement_1
statement_2
if expression3 :
break
Example: break in for loop
In the following example for loop breaks when the count value is 5. The print statement after the for
loop displays the sum of first 5 elements of the tuple numbers.
num_sum = 0
count = 0
for x in numbers:
num_sum = num_sum + x
count = count + 1
if count == 5:
break
Output:
In the following example while loop breaks when the count value is 5. The print statement after the
while loop displays the value of num_sum (i.e. 0+1+2+3+4).
num_sum = 0
count = 0
while(count<10):
count = count + 1
if count== 5:
break
Output:
continue statement
The continue statement is used in a while or for loop to take the control to the top of the loop without
executing the rest statements inside the loop. Here is a simple example.
for x in range(7):
if (x == 3 or x==6):
continue
print(x)
Output:
0
1
2
4
5
In the above example, the for loop prints all the numbers from 0 to 6 except 3 and 6 as the continue
statement returns the control of the loop to the top
Python String
String
Python has a built-in string class named "str" with many useful features. String literals can be
enclosed by either single or double, although single quotes are more commonly used.
Backslash escapes work the usual way within both single and double quoted literals -- e.g. \n \' \". A
double quoted string literal can contain single quotes without any fuss (e.g. "I wouldn't be a painter")
and likewise single quoted string can contain double quotes.
A string literal can span multiple lines, use triple quotes to start and end them. You can use single
quotes too, but there must be a backslash \ at the end of each line to escape the newline.
Contents :
String commands
String length
String slices
String: Commands
Char
>>> print(s)
Python string
>>> print(s)
>>> print(s)
>>> print(s)
JavaScript tutorial
>>> print(s)
jQuery exercises
JavaScript tutorial
>>> print(s)
jQuery exercises
JavaScript tutorial
>>>
Characters in a string can be accessed using the standard [ ] syntax, and like Java and C++, Python
uses zero-based indexing, so if str is 'hello' str[2] is 'l'. If the index is out of bounds for the string,
Python raises an error.
Python string
>>> b = a[2]
>>> print(b)
>>> a[0]
'P'
>>>
Explanation :
The above statement selects character at position number 2 from a and assigns it to b.
The expression in brackets is called an index that indicates which character we are
interested.
The index is an offset from the beginning of the string, and the offset of the first letter is zero.
>>> print(b)
>>>
>>> a[2.3]
>>>
Negative indices:
Alternatively, we can use negative indices, which count backward from the end of the
>>> a[-2]
'n'
>>> a[-8]
'n'
>>>
Python strings are "immutable" which means they cannot be changed after they are created
>>> a = "PYTHON"
>>> print(b)
XYTHON
>>> print(a)
PYTHON
>>>
>>> print(a)
PythonString
>>>
>>> a = "Java"
>>> b = "Script"
>>> a+=b
>>> print(a)
JavaScript
>>> print(b)
<PythonStringPythonStringPythonString>
>>>
String length:
>>> len(a)
13
>>> a[13]
>>> a[12]
'g'
They start at the beginning, select each character, in turn, do something to it, and continue
until the end.
Code:
a = "STRING"
i = 0
c = a[i]
print(c)
i = i + 1
Output:
>>>
S
T
R
I
N
G
>>>
Traversal with a for loop :
Code:
a = "Python"
i = 0
new=" "
b=a[i]
new = new+b
i = i + 1
print(b)
print(new)
Output:
>>>
P
P
y
Py
t
Pyt
h
Pyth
o
Pytho
n
Python
>>>
String slices:
A segment of a string is called a slice. The "slice" syntax is used to get sub-parts of a string. The slice
s[start:end] is the elements beginning at the start (p) and extending up to but not including end (q).
The operator [p:q] returns the part of the string from the pth character to the qth character,
including the first but excluding the last.
If we omit the first index (before the colon), the slice starts at the beginning of the string.
If you omit the second index, the slice goes to the end of the string:
If the first index is greater than or equal to the second the result is an empty string,
represented by two quotation marks.
Example-1
>> s = "Python"
s[1:4] is 'yth' -- chars starting at index 1 and extending up to but not including index 4
s[1:] is 'ython' -- omitting either index defaults to the start or end of the string
s[1:100] is 'ython' -- an index that is too big is truncated down to the string length
Python uses negative numbers to give easy access to the chars at the end of the string. Negative
index numbers count back from the end of the string:
s[-3:] is 'hon' -- starting with the 3rd char from the end and extending to the end of the string.
Example-2
Pytho
>>> print(a[6:11])
Stri
>>> print(a[5:13])
n String
>>>
>>> print(a[:8])
Python S
>>> print(a[4:])
on String
>>> print(a[6:3])
Example-3
>>> a = "PYTHON"
>>> a[3]
'H'
>>> a[0:4]
'PYTH'
>>> a[3:5]
'HO'
...
>>> a[:2]
'PY'
...
>>> a[3:]
'HON'
>>>
Code:
def search(char,str):
L=len(str)
print(L)
i = 0
while i < L:
if str[i]== char:
return 1
i = i + 1
return -1
print(search("P","PYTHON"))
Output:
>>>
6
1
>>>
It takes a character and finds the index where that character appears in a string.
If the character is not found, the function returns -1.
Another example
def search(char,str):
L=len(str)
print(L)
i = 0
while i < L:
if str[i]== char:
return 1
i = i + 1
return -1
print(search("S","PYTHON"))
Output:
>>>
6
-1
>>>
Python String Formatting
String Formatting
The format() method is used to perform a string formatting operation. The string on which this method
is called can contain literal text or replacement fields delimited by braces {}. Each replacement field
contains either the numeric index of a positional argument or the name of a keyword argument.
Syntax:
str.format(*args, **kwargs)
Returns a copy of the string where each replacement field is replaced with the string value of the
corresponding argument.
Contents:
Basic formatting
Value conversion
Numbers
Padding numbers
Signed numbers
Named placeholders
Datetime
Basic formatting:
Example-1:
'Python Format'
>>>
'10 30'
>>>
This following statement allows re-arrange the order of display without changing the arguments.
Example-2:
>>> '{1} {0}'.format('Python', 'Format')
'Format Python'
>>>
Value conversion:
The new-style simple formatter calls by default the __format__() method of an object for its
representation. If you just want to render the output of str(...) or repr(...) you can use the !s or !r
conversion flags.
In %-style you usually use %s for the string representation but there is %r for a repr(...) conversion.
Setup:
class Data(object):
def __str__(self):
return 'str'
def __repr__(self):
return 'repr'
Example-1:
class Data(object):
def __str__(self):
return 'str'
def __repr__(self):
return 'repr'
x='{0!s} {0!r}'.format(Data())
print (x)
Output:
str repr
In Python 3 there exists an additional conversion flag that uses the output of repr(...) but uses ascii(...)
instead.
Example-2:
class Data(object):
def __repr__(self):
return 'räpr'
x='{0!r} {0!a}'.format(Data())
print(x)
Output:
räpr r\xe4pr
Padding and aligning strings:
A value can be padded to a specific length. See the following examples where the value '15' is
encoded as part of the format string.
Note: The padding character can be spaces or a specified character.
Example:
Align right:
>>> '{:>15}'.format('Python')
' Python'
>>>
Align left:
>>> '{:15}'.format('Python')
'Python '
>>>
By argument:
In the previous example, the value '15' is encoded as part of the format string. It is also possible to
supply such values as an argument.
Example:
>>> '{:<{}s}'.format('Python', 15)
'Python '
>>>
Copy
In the following example we have used '*' as a padding character.
Example:
>>> '{:*<15}'.format('Python')
'Python*********'
>>>
Align center:
Example:
>>> '{:^16}'.format('Python')
>>>
In the following example, we have truncated ten characters from the left side of a specified string.
Example:
>>> '{:.10}'.format('Python Tutorial')
'Python Tut'
>>>
By argument:
Example:
>>> '{:.{}}'.format('Python Tutorial', 10)
'Python Tut'
>>>
Combining truncating and padding
Example:
>>> '{:10.10}'.format('Python')
'Python '
>>>
Numbers:
Integers:
>>> '{:d}'.format(24)
'24'
>>>
Floats:
>>> '{:f}'.format(5.12345678123)
'5.123457'
>>>
Padding numbers:
Example-1:
>>> '{:5d}'.format(24)
' 24'
>>>
The padding value represents the length of the complete output for floating points. In the following
example '{:05.2f}' will display the float using five characters with two digits after the decimal point.
Example-2:
>>> '{:05.2f}'.format(5.12345678123)
'05.12'
>>>
Signed numbers:
By default only negative numbers are prefixed with a sign, but you can display numbers prefixed with
the positive sign also.
Example-1:
>>> '{:+d}'.format(24)
'+24'
>>>
You can use a space character to indicate that negative numbers (should be prefixed with a minus
symbol) and a leading space should be used for positive numbers.
Example-2:
'-24'
>>>
Example-3:
' 24'
>>>
You can control the position of the sign symbol relative to the padding.
Example-4:
'- 24'
>>>
Named placeholders:
Example-1:
'Place Holder!'
>>>
Example-2:
'Place Holder!'
>>>
Datetime:
You can format and print datetime object as per your requirement.
Example:
'2016-07-26 03:57'
>>>
Python List
List
A list is a container which holds comma-separated values (items or elements) between square
brackets where items or elements need not all have the same type.
In general, we can define a list as an object that contains multiple data items (elements). The contents
of a list can be changed during program execution. The size of a list can also change during
execution, as elements are added or removed from it.
Note: There are much programming languages which allow us to create arrays, which are objects
similar to lists. Lists serve the same purpose as arrays and have many more built-in capabilities.
Traditional arrays can not be created in Python.
Examples of lists:
Contents:
List commands
Create a Python list
List indices
Remove the item at the given position in the list, and return it
Return the index in the list of the first item whose value is x
Lists: Commands
<list> = <list>[from_inclusive : to_exclusive : ±step_size]
<list>.append(<el>)
# Or: <list> += [<el>]
<list>.extend(<collection>)
# Or: <list> += <collection>
<list>.sort()
<list>.reverse()
<list> = sorted(<collection>)
<iter> = reversed(<list>)
sum_of_elements = sum(<collection>)
elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
sorted_by_second = sorted(<collection>, key=lambda el: el[1])
sorted_by_both = sorted(<collection>, key=lambda el: (el[1], el[0]))
flatter_list = list(itertools.chain.from_iterable(<list>))
product_of_elems = functools.reduce(lambda out, x: out * x, <collection>)
list_of_chars = list(<str>)
List indices
List indices work the same way as string indices, list indices start at 0. If an index has a positive value
it counts from the beginning and similarly it counts backward if the index has a negative value. As
positive integers are used to index from the left end and negative integers are used to index from the
right end, so every item of a list gives two alternatives indices. Let create a list called color_list with
four items.
color_list=["RED", "Blue", "Green", "Black"]
If you give any index value which is out of range then interpreter creates an error message. See the
following statements.
>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four
elements
indices start at 0 and end at 3
>>> color_list[0] # Return the First Element
'Red'
>>> print(color_list[0],color_list[3]) # Print First and Last Elements
Red Black
>>> color_list[-1] # Return Last Element
'Black'
>>> print(color_list[4]) # Creates Error as the indices is out of range
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>>
>>> print(color_list)
>>> print(color_list)
>>>
>>> print(color_list)
>>> print(color_list)
>>>
>>> print(color_list)
>>> color_list.remove("Black")
>>> print(color_list)
>>> print(color_list)
>>> color_list.clear()
>>> print(color_list)
[]
>>>
Copy
List Slices
Lists can be sliced like strings and other sequences.
Syntax:
sliced_list = List_Name[startIndex:endIndex]
This refers to the items of a list starting at index startIndex and stopping just
before index endIndex. The default values for list are 0 (startIndex) and the
end (endIndex) of the list. If you omit both indices, the slice makes a copy of
the original list.
['Red', 'Blue']
>>>
Copy
Cut second item from a list:
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four
elements
>>> print(color_list[1:2])
['Blue']
>>> print(color_list[1:-2])
['Blue']
>>>
Copy
Cut second and third elements from a list:
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four
elements
>>> print(color_list[1:-1])
['Blue', 'Green']
>>>
Copy
Cut first three items from a list:
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four
elements
>>>
Copy
Creates copy of original list:
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"] # The list have four
elements
>>>
Copy
return it
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"]
>>> print(color_list)
'Green'
>>> print(color_list)
>>>
Copy
Return the index in the list of the first item whose value
is x
See the following statements:
>>> color_list=["Red", "Blue", "Green", "Black"]
>>> print(color_list)
>>> color_list.index("Red")
>>> color_list.index("Black")
>>>
Copy
>>> print(color_list)
>>> print(color_list)
>>> color_list.count("Blue")
>>>
Copy
>>> print(color_list)
>>> print(color_list)
>>>
Copy
>>> print(color_list)
>>> color_list.reverse()
>>> print(color_list)
['Black', 'Green', 'Blue', 'Red']
>>>
Copy
>>> print(color_list)
>>> color_list.copy()
>>>
Copy
>>> print(color_list)
>>> color_list.index("Green")
>>>
Copy
>>> print(color_list[0])
Red
>>> color_list[0]="White" # Change the value of first item "Red" to "White"
>>> print(color_list)
>>> print(color_list[0])
White
>>>
Copy
>>> print(listx)
[1, 2, 3, 4]
>>> print(tuplex)
(1, 2, 3, 4)
>>>
Copy
>>> print(listx)
[1, 5, 7, 3, 2, 4, 6]
>>> print(sublist)
[7, 2, 6]
>>> print(sublist)
[1, 3, 6]
>>> sublist=listx[6:2:-2] #when step is negative the jump is made back
>>> print(sublist)
[6, 2]
>>>
Copy
>>> print(listx)
25
>>>
Copy
True
>>> listx1, listx2=[9, 7, 5, 3], [3, 5, 7, 9] #create two lists equal, but
unsorted.
False
False
True
>>>
Copy
>>> print(listx)
>>> print(listx)
World
>>> print(listx)
>>> listx[1][2]=4
>>> print(listx)
>>>
Copy
How can I get the index of an element contained in the
list?
>>> listy = list("HELLO WORLD")
>>> print(listy)
['H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D']
>>> index = listy.index("L") #get index of the first item whose value is
passed as parameter
>>> print(index)
>>> print(index)
>>> print(index)
>>>
Copy
>>> print(color_list)
>>> color_list.append("White")
>>> color_list.append("Yellow")
>>> print(color_list)
>>> color_list.pop()
'Yellow'
>>> color_list.pop()
'White'
>>> color_list.pop()
'Black'
>>> color_list
>>>
Copy
>>> print(color_list)
>>> print(color_list)
'Red'
>>> print(color_list)
'Blue'
>>> print(color_list)
Python Dictionary
Dictionary
Python dictionary is a container of the unordered set of objects like lists. The
objects are surrounded by curly braces { }. The items in a dictionary are a
comma-separated list of key:value pairs where keys and values are Python
data type.
Each object or value accessed by key and keys are unique in the dictionary.
As keys are used for indexing, they must be the immutable type (string,
number, or tuple). You can create an empty dictionary using empty curly
braces.
Contents :
Dictionary commands
Dictionary: Commands
# Coll. of keys that reflects changes.
<view> = <dict>.keys()
# Coll. of values that reflects changes.
<view> = <dict>.values()
# Coll. of key-value tuples.
<view> = <dict>.items()
<dict>.update(<dict>)
# Creates a dict from coll. of key-value pairs.
<dict> = dict(<collection>)
# Creates a dict from two collections.
<dict> = dict(zip(keys, values))
# Creates a dict from collection of keys.
<dict> = dict.fromkeys(keys [, value])
Counter
>>> new_dict = {}
>>> print(new_dict)
{}
>>> color
>>>
Copy
Get value by key in Python dictionary
>>> #Declaring a dictionary
>>> dict[1]
20.5
>>> dict[3]
23.22
>>> dict.get(1)
20.5
>>> dict.get(3)
23.22
>>>
Copy
Add key/value to a dictionary in Python
>>> #Declaring a dictionary with a single element
>>>print(dic)
{'pdy1': 'DICTIONARY'}
>>> print(dic)
>>>
>>> print(d)
>>> d.update({2:30})
>>> print(d)
>>>
Copy
Iterate over Python dictionaries using for loops
Code:
d = {'Red': 1, 'Green': 2, 'Blue': 3}
Copy
Output:
>>>
Green corresponds to 2
Red corresponds to 1
Blue corresponds to 3
>>>
Remove a key from a Python dictionary
Code:
myDict = {'a':1,'b':2,'c':3,'d':4}
print(myDict)
if 'a' in myDict:
del myDict['a']
print(myDict)
Copy
Output:
>>>
{'d': 4, 'a': 1, 'b': 2, 'c': 3}
{'d': 4, 'b': 2, 'c': 3}
>>>
Sort a Python dictionary by key
Code:
color_dict = {'red':'#FF0000',
'green':'#008000',
'black':'#000000',
'white':'#FFFFFF'}
Copy
Output:
>>>
black: #000000
green: #008000
red: #FF0000
white: #FFFFFF
>>>
Find the maximum and minimum value of a Python dictionary
Code:
my_dict = {'x':500, 'y':5874, 'z': 560}
Copy
Output:
>>>
Maximum Value: 5874
Minimum Value: 500
>>>
Concatenate two Python dictionaries into a new one
Code:
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic4 = {}
print(dic4)
Copy
Output:
>>>
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
>>>
Test whether a Python dictionary contains a specific key
Code:
fruits = {}
fruits["apple"] = 1
fruits["mango"] = 2
fruits["banana"] = 4
# Use in.
if "mango" in fruits:
print("Has mango")
else:
print("No mango")
# Use in on nonexistent key.
if "orange" in fruits:
print("Has orange")
else:
print("No orange")
Copy
Output
>>>
Has mango
No orange
>>>
Find the length of a Python dictionary
Code:
fruits = {"mango": 2, "orange": 6}
print("Length:", len(fruits))
Copy
Output:
>>>
Length: 2
>>>
Python Tuples
Tuples
A tuple is a container which holds a series of comma-separated values (items
or elements) between parentheses such as an (x, y) co-ordinate. Tuples are
like lists, except they are immutable (i.e. you cannot change its content once
created) and can hold mix data types. Tuples play a sort of "struct" role in
Python -- a convenient way to pass around a little logical, fixed size bundle of
values.
Contents:
Tuple commands
Create a tuple
List to tuple
Clone a tuple
Slice a tuple
Tuple: Commands
To create a tuple, just list the values within parenthesis separated by commas.
The "empty" tuple is just an empty pair of parenthesis
>>> #create an empty tuple
>>> tuplex = ()
()
>>> tuplex = 4, 7, 3, 8, 1
(4, 7, 3, 8, 1)
>>> tuplex = 4,
(4,)
()
>>> #create a tuple from a iterable object
(True, False)
>>>
Copy
How to get an item of the tuple in Python?
>>> #create a tuple
>>> tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e")
>>> print(tuplex)
>>> print(item)
>>> print(item1)
>>>
Copy
How to know if an element exists within a tuple in Python?
>>> #create a tuple
>>> tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e")
>>> print(tuplex)
True
>>>
Copy
List to tuple
>>> #create list
>>> print(listx)
>>> #use the tuple() function built-in Python, passing as parameter the
list
>>> print(tuplex)
>>>
Copy
Unpack a tuple in several variables
>>> #create a tuple
>>> tuplex = 4, 8, 3
>>> print(tuplex)
(4, 8, 3)
15
>>> #the number of variables must be equal to the number of items of the
tuple
>>>
Copy
Add item in Python tuple!
>>> #create a tuple
>>> print(tuplex)
(4, 6, 2, 8, 3, 1)
>>> #tuples are immutable, so you can not add new elements
>>> #using merge of tuples with the + operator you can add an element and
it will create a new tuple
>>> print(tuplex)
(4, 6, 2, 8, 3, 1, 9)
>>> print(tuplex)
>>> listx.append(30)
>>> print(tuplex)
>>>
Copy
Clone a tuple
>>> from copy import deepcopy
>>> print(tuplex)
('HELLO', 5, [], True)
>>> tuplex_clone[2].append(50)
>>> print(tuplex_clone)
>>> print(tuplex)
>>>
Copy
In Python how to know the number of times an item has repeated
>>> #create a tuple
>>> tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7
>>> print(tuplex)
(2, 4, 5, 6, 2, 3, 4, 4, 7)
>>> print(count)
>>> print(count)
>>>
Copy
Remove an item from a tuple
>>> #create a tuple
>>> tuplex = "w", 3, "d", "r", "e", "s", "l"
>>> print(tuplex)
>>> #using merge of tuples with the + operator you can remove an item and
it will create a new tuple
>>> print(tuplex)
>>> listx.remove("l")
>>> print(tuplex)
>>>
Copy
Slice a tuple
>>> #create a tuple
>>> #used tuple[start:stop] the start index is inclusive and the stop index
#is exclusive.
>>> print(_slice)
(5, 4)
>>> #if the start index isn't defined, is taken from the beg inning of the
tuple.
>>> print(_slice)
(2, 4, 3, 5, 4, 6)
>>> #if the end index isn't defined, is taken until the end of the tuple
>>> print(_slice)
(6, 7, 8, 6, 1)
>>> print(_slice)
(2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
>>> print(_slice)
(3, 5, 4, 6)
>>>
Copy
Find the index of an item of the tuple
>>> #create a tuple
>>> print(tuplex)
('i', 'n', 'd', 'e', 'x', ' ', 't', 'u', 'p', 'l', 'e')
>>> #get index of the first item whose value is passed as parameter
>>> print(index)
>>> print(index)
>>> #if item not exists in the tuple return ValueError Exception
>>>
Copy
The size of a tuple
>>> tuplex = tuple("w3resource") #create a tuple
>>> print(tuplex)
('w', '3', 'r', 'e', 's', 'o', 'u', 'r', 'c', 'e')
>>> print(len(tuplex))
10
>>>
Copy
How operators + and * are used with a Python tuple?
>>> #create a tuple
>>> print(tuplex * 6)
(5, 5, 5, 5, 5, 5)
>>> print(tuplex)
>>> #The + operator allow create a tuple joining two or more tuples
>>> print(tuplex)
(3, 6, 9, 12, 15, 'w', 3, 'r', 's', 'o', 'u', 'r', 'c', 'e', True, False)
>>>
Copy
Slice of a tuple using step parameter
>>> #create a tuple
>>> print(tuplex)
('H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D')
>>> #step specify an increment between the elements to cut of the tuple.
>>> print(_slice)
>>> print(_slice)
>>> print(_slice)
>>> print(_slice)
>>>
Copy
Modify items of a tuple
>>> #create a tuple
>>> print(tuplex)
>>> #tuples are immutable, so you can not modify items which are also
immutable, as str, boolean, numbers etc.
>>> tuplex[3].append(200)
>>> print(tuplex)
>>>
Python Sets
Sets
A set object is an unordered collection of distinct hashable objects. It is
commonly used in membership testing, removing duplicates from a sequence,
and computing mathematical operations such as intersection, union,
difference, and symmetric difference.
Sets support x in the set, len(set), and for x in set like other collections. Set is
an unordered collection and does not record element position or order of
insertion. Sets do not support indexing, slicing, or other sequence-like
behavior.
There are currently two built-in set types, set, and frozenset. The set type is
mutable - the contents can be changed using methods like add() and
remove(). Since it is mutable, it has no hash value and cannot be used as
either a dictionary key or as an element of another set. The frozenset type is
immutable and hashable - its contents cannot be altered after it is created; it
can, therefore, be used as a dictionary key or as an element of another set.
Contents:
Set commands
Intersection of sets
Union of sets
Symmetric difference
Clear sets
Set: Commands
<set> = set()
<set>.add(<el>)
# Or: <set> |= {<el>}
<set>.update(<collection>)
# Or: <set> |= <set>
<set> = <set>.union(<coll.>)
# Or: <set> | <set>
<set> = <set>.intersection(<coll.>)
# Or: <set> & <set>
<set> = <set>.difference(<coll.>)
# Or: <set> - <set>
<set> = <set>.symmetric_difference(<coll.>)
# Or: <set> ^ <set>
<bool> = <set>.issubset(<coll.>)
# Or: <set> <= <set>
<bool> = <set>.issuperset(<coll.>)
# Or: <set> >= <set>
<el> = <set>.pop()
# Raises KeyError if empty.
<set>.remove(<el>)
# Raises KeyError if missing.
<set>.discard(<el>)
# Doesn't raise an error.
Frozen Set
>>> print(setx)
set()
>>> print(n)
{0, 1, 2, 3, 4, 5}
>>>
Copy
print(n)
2
3
>>>
Copy
>>> color_set.add("Red")
>>> print(color_set)
{'Red'}
>>> print(color_set)
>>>
Copy
pop() function:
>>> num_set = set([0, 1, 2, 3, 4, 5])
>>> num_set.pop()
>>> print(num_set)
{1, 2, 3, 4, 5}
>>> num_set.pop()
>>> print(num_set)
{2, 3, 4, 5}
>>>
Copy
remove() function:
>>> num_set = set([0, 1, 2, 3, 4, 5])
>>> num_set.remove(0)
>>> print(num_set)
{1, 2, 3, 4, 5}
>>>
Copy
discard() function:
>>> num_set = set([0, 1, 2, 3, 4, 5])
>>> num_set.discard(3)
>>> print(num_set)
{0, 1, 2, 4, 5}
>>>
Copy
Intersection of sets:
In mathematics, the intersection A ∩ B of two sets A and B is the set that
contains all elements of A that also belong to B (or equivalently, all elements
of B that also belong to A), but no other elements.
>>> #Intersection
{'blue'}
>>>
Copy
Union of sets:
In set theory, the union (denoted by ∪) of a collection of sets is the set of all
distinct elements in the collection. It is one of the fundamental operations
through which sets can be combined and related to each other.
>>> #Union
>>>
Copy
Set difference:
>>> setx = set(["green", "blue"])
>>> print(setz)
{'blue'}
>>> print(setb)
{'green'}
>>>
Copy
Symmetric difference:
>>> setx = set(["green", "blue"])
>>> print(setc)
{'yellow', 'green'}
>>>
Copy
>>> print(issubset)
False
>>> print(issuperset)
False
>>>
Copy
More Example:
>>> setx = set(["green", "blue"])
>>> print(issubset)
True
>>> issuperset = setx >= sety
>>> print(issuperset)
True
>>>
Copy
>>> print(setd)
{'blue', 'green'}
>>>
Copy
Clear sets:
>>> setx = set(["green", "blue"])
>>> sete.clear()
>>> print(sete)
set()
>>>
ntroduction
In all programming and scripting language, a function is a block of program
statements which can be used repetitively in a program. It saves the time of a
developer. In Python concept of function is same as in other languages. There
are some built-in functions which are part of Python. Besides that, we can
defines functions according to our need.
In Python, a user-defined function's declaration begins with the keyword def and followed
by the function name.
The function may take arguments(s) as input within the opening and closing parentheses,
just after the function name followed by a colon.
After defining the function name and arguments(s) a block of program statement(s) start
at the next line and these statement(s) must be indented.
Syntax:
def function_name(argument1, argument2, ...) :
statement_1
statement_2
....
Inside Function Call
<function>(<positional_args>)
# f(0, 0)
<function>(<keyword_args>)
# f(x=0, y=0)
<function>(<positional_args>, <keyword_args>)
# f(0, y=0)
Call a function
Calling a function in Python is similar to other programming languages, using
the function name, parenthesis (opening and closing) and parameter(s). See
the syntax, followed by an example.
Syntax:
function_name(arg1, arg2)
Argument combinations:
def f(a, b, c): # f(a=1, b=2, c=3) | f(1, b=2,
c=3) | f(1, 2, b=3) | f(1, 2, 3)
def f(*, a, b, c): # f(a=1, b=2, c=3)
def f(a, *, b, c): # f(a=1, b=2, c=3) | f(1, b=2,
c=3)
def f(a, b, *, c): # f(a=1, b=2, c=3) | f(1, b=2,
c=3) | f(1, 2, c=3)
avg_number(3, 4)
Copy
Output:
Average of 3 and 4 is 3.5
Explanation:
1. Lines 1-2 : Details (definition) of the function.
2. Line 3 : Call the function.
3. Line 1 : Pass parameters : x = 3, y = 4
4. Line 2 : Print the value of two parameters as well as their average value.
def function_name() :
statement_1
statement_2
....
Example:
def printt():
printt()
Copy
Output:
This is Python 3.2 Tutorial
This is Python 3.2 Tutorial
This is Python 3.2 Tutorial
Explanation:
function_name(arg1, arg2)
Example:
The following function returns the square of the sum of two numbers.
def nsquare(x, y):
Copy
Output:
The square of the sum of 2 and 3 is : 25
Explanation:
In function's parameters list we can specify a default value(s) for one or more
arguments. A default value can be written in the format "argument1 = value",
therefore we will have the option to declare or not declare a value for those
arguments. See the following example.
Example:
The following function returns the square of the sum of two numbers, where
default value of the second argument is 2.
def nsquare(x, y = 2):
Copy
Output:
The square of the sum of 2 and 2 is: 16
The square of the sum of 2 and 4 is : 36
Explanation:
Keyword Arguments:
We have already learned how to use default arguments values, functions can
also be called using keyword arguments. Arguments which are preceded with
a variable name followed by a '=' sign (e.g. var_name=") are called keyword
arguments.
All the keyword arguments passed must match one of the arguments
accepted by the function. You may change the order of appearance of the
keyword. See the following example.
Example:
def marks(english, math = 85, science = 80):
marks(71, 77)
Line 1: The function named marks has three parameters, there is no default
value in the first parameter (english) but remaining parameters have default
values (math = 85, science = 80).
Line 3: The parameter english gets the value of 71, math gets the value 77
and science gets the default value of 80.
Line 4: The parameter english gets the value of 65, math gets the default
value of 85 and science gets the value of 74 due to keyword arguments.
Line 5: Here we use three keyword arguments and the parameter english gets
the value 75, math gets the value 90 and science gets the value 70.
Example:
def sum(*numbers):
s = 0
for n in numbers:
s += n
return s
print(sum(1,2,3,4))
Copy
Output:
10
Lambda Forms:
In Python, small anonymous (unnamed) functions can be created with lambda
keyword. Lambda forms can be used as an argument to other function where
function objects are required but syntactically they are restricted to a single
expression. A function like this:
def average(x, y):
return (x + y)/2
print(average(4, 3))
Copy
may also be defined using lambda
Copy
Output:
3.5
Python Documentation Strings
Docstring Conventions :
- String literal literals must be enclosed with a triple quote. Docstring should
be informative
- The first line may briefly describe the object's purpose. The line should
begin with a capital letter and ends with a dot.
Copy
Built-in Functions
The Python interpreter has a number of functions and types built into it that
are always available. They are listed here in alphabetical order.
Name Description
abs() The abs() function is used to get the absolute (positive) value of a given number.
all() The all() function is used to test whether all elements of an iterable are true or not.
any() The any() function returns True if any element of the iterable is true. The function
returns False if the iterable is empty.
ascii() The ascii() function returns a string containing a printable representation (escape
the non-ASCII characters ) of an object.
bin() The bin() function is used to convert an integer number to a binary string. The
result is a valid Python expression.
callable() The callable() function returns True if the object argument appears callable, False if
not.
chr() The chr() function returns the string representing a character whose Unicode
codepoint is the integer.
classmethod() The classmethod() function is used to convert a method into a class method.
complie() The compile() function is used to compile the source into a code.
complex() The complex() function is used to create a complex number or convert a string or
number to a complex number.
delattr() The delattr() function is used to delete the specified attribute from the specified
object.
dir() The dir() function returns all properties and methods of the specified object,
without the values. The function will return all the properties and methods, even
built-in properties which are default for all object.
divmod() The divmod() function takes two non complex numbers as arguments and return a
pair of numbers consisting of their quotient and remainder when using integer
division. With mixed operand types, the rules for binary arithmetic operators
apply.
enumerate() The enumerate() function returns an enumerate object. iterable must be a
sequence, an iterator, or some other object which supports iteration.
eval() The eval() function is used to evaluate the specified expression. If the expression is
a correct Python statement, it will be executed.
exec() The exec() function is used to execute the specified Python code. object must be
either a string or a code object.
filter() The filter() function construct an iterator from those elements of iterable for which
function returns true.
float() The float() function is used to convert the specified value into a floating point
number.
format() The format() function is used to format a specified value into a specified format.
frozenset() The frozenset() function returns a new frozenset object, optionally with elements
taken from iterable.
getattr() The getattr() function returns the value of the named attribute of object and name
must be a string
globals() The globals() function returns a dictionary representing the current global symbol
table.
hash() The hash() function returns the hash value of the object (if it has one).
help() The help() function is used to execute the built-in help system.
hex() The hex() function converts an integer number to a lowercase hexadecimal string
prefixed with "0x".
int() The int() function converts the specified value into an integer number.
isinstance() The isinstance() function returns true if the object argument is an instance of the
classinfo argument, or of a subclass thereof.
issubclass() The issubclass() function returns true if the specified object is a subclass of the
specified object, otherwise false. A class is considered a subclass of itself.
list() The list() function is used to create a list object (list is actually a mutable sequence
type).
locals() The locals() function is used to get the local symbol table as a dictionary. Free
variables are returned by locals() when it is called in function blocks, but not in
class blocks.
map() The map() function is used to execute a specified function for each item in a
inerrable.
max() The max() function is used to find the item with the largest value in an iterable.
memoryview() The memoryview() function is used to get a memory view object from a specified
object.
min() The min() function is used to find the item with the smallest value in an iterable.
next() The next() function is used to get the next item in an iterator.
open() The open() function is used to open a file and returns it as a file object.
ord() The ord() function is used to get an integer representing the Unicode code point of
that character.
pow() The pow() function is used to get the value of x to the power of y (xy). If z is
present, return x to the power y, modulo z (computed more efficiently than pow(x,
y) % z).
print() The print() function is used to print objects to the text stream file, separated by
sep and followed by end. sep, end and file, if present, must be given as keyword
arguments.
range() The range() function is used to get a sequence of numbers, starting from 0 by
default, and increments by 1 by default, and ends at a specified number.
round() The round() function returns the rounded floating point value number, rounded to
ndigits digits after the decimal point. If ndigits is omitted, it defaults to zero.
setattr() The setattr() function is used to set the value of the specified attribute of the
specified object.
slice() The slice() function is used to get a slice object representing the set of indices
specified by range(start, stop, step).
sorted() The sorted() function is used to get a new sorted list from the items in iterable.
str() The str() function is used to convert the specified value into a string.
sum() The sum() function is used to get the sum of all items in an iterable.
tuple() The tuple() function is used to create a tuple in Python. Iterable may be a
sequence, a container that supports iteration, or an iterator object.
vars The vars() function is used to get the __dict__ attribute of the given object.
zip() The zip() function is used to make an iterator that aggregates elements from each
of the iterables.
Python Classes
Introduction
The basic idea behind an object-oriented programming (OOP) is to combine
both data and associated procedures (known as methods) into a
single unit which operate on the data. Such a unit is called an object.
We have already worked with some objects in Python, (See Python data type
chapter) for example strings, lists are objects defined by the string and list
classes which are available by default into Python. Let's declare two objects a
string and a list and test their type with type() function.
As string1 is an object, strings "Good Morning" can produce an uppercase or
lowercase version of themselves calling upper() and lower() methods
associated with the string. Check it in the Python IDLE.
Note : To see the list of string methods execute the following command in Python IDLE
>>>help(str)
Local Variables:
def function_local(a):
a = 50
a = 100
function_local(40)
print('Value of a is ->',a)
Copy
Output:
a is -> 40
After new value within the function a is -> 50
Value of a is -> 100
Explanation:
global statement:
def function_local():
global a
a = 50
a = 100
function_local()
print('Value of a is ->',a)
Copy
Output:
a is -> 100
After new value within the function a is -> 50
Value of a is -> 50
Explanation:
Line No.- 3 : The variable 'a' is declared as a global variable, therefore the
value of a is now 100.
Line No.- 5 : Assign the value 50 to 'a' and it will hold same value inside and
outside the function unless we assign a new value.
nonlocal statement
a = 10
def inside():
a = 20
print("Inside a ->", a)
inside()
print("outside a->", a)
outside()
Copy
In the above example the first print() statement simply print the value of 'a',
which is 20 as 'a' is local within inside() function. The second print() statement
prints the value 'a', which is 10 as the inside() function has no effect. Now we
introduce a nonlocal statement in inside() function and the code will be:
def outside():
a = 10
def inside():
nonlocal a
a = 20
inside()
outside()
Copy
The second print() statement prints the value 'a', which is 20 as the variable 'a'
is rebound..
- For example 'a' maps to [1, 2, 3] or 'a' maps to the value 25.
- The global namespace for a module is created when the module is called
and last until the interpreter quits.
- The local namespace for a function is created when the function is called
and deleted when the function returns.
Defining a class:
In object oriented programming classes and objects are the main features. A
class creates a new data type and objects are instances of a class which
follows the definition given inside the class. Here is a simple form of class
definition.
class Student:
Statement-1
Statement-1
....
....
....
Statement-n
A class definition started with the keyword 'class' followed by the name of the
class and a colon.
Creating a Class:
Here we create a simple class using class keyword followed by the class
name (Student) which follows an indented block of segments (student class,
roll no., name).
#studentdetails.py
class Student:
stu_class = 'V'
stu_roll_no = 12
stu_name = "David"
Copy
Class Objects:
There are two kind of operations class objects supports : attribute references
and instantiation. Attribute references use the standard syntax, obj.name for
all attribute references in Python. Therefore if the class definition (add a
method in previous example) look like this
#studentdetails1.py
class Student:
stu_class = 'V'
stu_roll_no = 12
stu_name = "David"
def messg(self):
Copy
__init__ method:
There are many method names in Python which have special importance. A
class may define a special method named __init__ which does some
initialization work and serves as a constructor for the class. Like other
functions or methods __init__ can take any number of arguments. The
__init__ method is run as soon as an object of a class is instantiated and class
instantiation automatically invokes __init__() for the newly-created class
instance. See the following example a new, initialized instance can be
obtained by:
#studentdetailsinit.py
class Student:
self.c = sclass
self.r = sroll
self.n = sname
def messg(self):
return 'New Session will start soon.'
Copy
Operators
Addition:
class School:
self.subjects = list(subjects)
class Subject:
F1 + F2
Copy
Output:
<__main__.School object at 0x0000000008B82470>
from pathlib import Path
Copy
Output:
WindowsPath('C:/Users/User/AppData/Local/Programs/Python/
Python37/data')
Greater / Equality:
class Person:
'''person entity'''
self.first_name = first_name
self.surname = surname
self.age = age
def __repr__(self):
return f'Person(first_name={self.first_name},
surname={self.surname}, age={self.age})'
data = [
print(results)
Copy
Output:
[Person(first_name=John, surname=Smith, age=13),
Person(first_name=Anne, surname=McNell, age=11),
Person(first_name=Mary, surname=Brown, age=14)]
Length:
class School:
self.subjects = list(subjects)
def __len__(self):
return len(self.subjects)
print(len(Sub))
Copy
Output:
2
Getitem:
class School:
self.subjects = list(subjects)
return self.subjects[i]
print(Sub[0])
Copy
Output:
<__main__.Subject object at 0x0000000007ACC5F8>
Inheritance:
Example:
In a company Factory, staff and Office staff have certain common properties -
all have a name, designation, age etc. Thus they can be grouped under a
class called CompanyMember. Apart from sharing those common features,
each subclass has its own characteristic - FactoryStaff gets overtime
allowance while OfficeStaff gets traveling allowance for an office job. The
derived classes ( FactoryStaff & OfficeStaff) has its own characteristic and, in
addition, they inherit the properties of the base class (CompanyMember). See
the example code.
# python-inheritance.py
class CompanyMember:
self.name = name
self.designation = designation
self.age = age
def tell(self):
'''Details of an employee.'''
class FactoryStaff(CompanyMember):
self.overtime_allow = overtime_allow
CompanyMember.tell(self)
self.marks = travelling_allow
CompanyMember.tell(self)
Copy
Now execute the class in Python Shell and see the output.
Variables:
Variables are the programming constructs used to store and name data of any type. The
name of a variable must start with an alphabet or an underscore. A variable is created by
assigning it a value. Ex: x=5. The name of variable is ‘x’ and it stores an integer ‘5’ in it.
Indentation in Python:
Indentation in python is similar to the use of ‘{…}’ in C/C++. The opening and closing of
control loops, conditional statements, functions, objects and classes is done with
indentation only. Within a function only the statements or expressions indented w.r.t to its
definition will be evaluated. Indentation also makes the programs easy to read and
understand.
Strings:
Strings are the data types that store characters. The strings can be initialised to a variable in
either single quotes or double quotes. Ex: x = ‘hi’ and x = “hi” are same.
Lists:
Lists are Python objects which store ordered sequence of information, which can be
accessed by list name and index. A list is denoted by [ ]. The elements of the list are usually
homogeneous but, they can be of mixed data types as well. Unlike strings, lists are mutable
i.e., some part of the list can be changed without changing the other part. Two lists can be
concatenated like that of strings. The elements of list can be accessed using their index.
When a list is multiplied by an integer, then the list is concatenated at the end that many
no. of times.
List Operations:
Let L be a list containing elements of any data type.
The table shown here describes different functions and their operations on the lists with
examples wherever required.
6. L.sort() The list L is updated with all its elements sorted (L must have
only numbers)
7. sorted(L) Returns the sorted list but ‘L’ remains same
9. ‘_’.join(L) Joins all the elements of L with an ‘_’. (The character joining
can be anything.
10. L.index(x) Returns the index of the element ‘x’ in the list if it exists.
The expected output is [3,4]. As the element of list L1 is removed in first iteration, its length
gets changed but the index count does not change. As-a-result element ‘2’ is in position ‘0’
and never seen by the iterator.
3. Cloning is the method of copying the elements of the lists so that it can avoid the side
effects due to mutation and aliasing. This is done by the statement: L_copy = L[ : ]. Now, a
change in one of them does not change the other list.
Dictionaries:
A dictionary is an unordered collection of data values which holds key: value pair unlike
other data structures. The dictionary in python works similar to the dictionary in real world.
An empty dictionary can be created using the statement: a_dict = {}.
The conditions on values of the dictionary are:
They can be of any type (mutable or not).
They can be lists, tuples, even other dictionaries as well.
The keys must be unique and they must be of immutable type (int, string, tuple). Let us take
an example: grades = {‘X’: ‘A’, ‘Y’: ‘B’, ‘Z’: ‘A+’}. grades[‘W’] = ‘A’ adds to the dictionary,
hence they are mutable.
Some operations:
‘X in grades’ returns True and ‘K in grades’ returns False.
An empty dictionary can be initialized using the statement: d = dict{}.
del(grades[‘Z’]) deletes ‘Z’ and its value from the dictionary.
grades.keys() gives all the keys in the dictionary.
grades.values() gives all the values in the dictionary.
grades.items() gives all the keys and respective values in the dictionary.
grades.pop(‘X’) removes the element with key ‘X’.
grades.update(d) adds the dictionary ‘d’ at the end of ‘grades’.
Example: This example shows the advantage of use of a dictionary in computing
Fibonacci(n). In normal computation, we compute Fibonacci(n-1) and Fibonacci(n-2) using
recursion. And, in Fibonacci(n-1) we again compute Fibonacci(n-2) and Fibonacci(n-3), this
increases the no. of function calls as we are computing the known value again and again.
When ‘n’ is more than 10, number of function calls will be in millions. To avoid this, we store
the value we compute in a dictionary, so that we can directly get those values from the
dictionary.
Program:
Output when n=20, 30, 34:
As we can see from the output of the example, the number of recursive calls in the first
function are 1.66 million for n=30, whereas in second function we only require 57 recursive
calls as we are using a dictionary. From 3 rd output sample it is clear that with slight increase
in ‘n’, recursive calls in first function reached 10 million. So, use of dictionary improves the
efficiency of computation to a large extent.
Sets:
Set is an unordered and unindexed collection of unique elements. Sets can be initialized
within curly brackets as shown:
new = {‘x’, ‘y’}
Unlike dictionaries, sets are immutable. Some basic operations that can be performed on
sets are shown below:
new.add(‘z’) adds the item ‘z’ into the set. Only one item can be added at a time.
To add more than one item we use, new.update(‘a’, ‘b’).
len(new) returns the value of number of items in the set.
new.remove(‘x’) removes the item ‘x’ from the set.
new.pop() removes the last item from the set. As sets are unordered any item may
get removed.
del new deletes the entire set.
Whenever, we need the collection of unique elements/objects sets can be used. The
disadvantage of using sets is that they are unordered, as a result they can’t be accessed with
the index.
Example:
This example shows that sets are unordered and unique collection of items.
Control Structures:
Conditional Statements:
if statement:
Syntax: if condition:
expression
If the condition is True the expression is evaluated.
if-else statement:
Syntax: if condition:
expression-1
else:
expression-2
If the condition is True the expression-1 is evaluated, otherwise expression-2 is evaluated.
if-elif-…else statement: (Multiway Branching)
Syntax: if condition1:
expression-1
elif condition2
expression-2
else:
expression-3
If the condition1 is True the expression-1 is evaluated, else-if condition2 is True expression-2
is evaluated otherwise expression-3 is evaluated.
Example:
Control loops:
While loop:
The expressions inside the while loop are evaluated as long as the condition is True. The
conditional variable must be changed within the loop to prevent the occurrence of an
infinite loop. All the expressions are evaluated in every iteration. Initialization of variable
determining the condition must be done before the loop.
Syntax: while condition:
expression1
expression2
…
expression-n
Example: (Sum of first 5 whole numbers)
For loop:
While ‘i’ runs from ‘0’ to ‘n-1’ all the expressions within the loop are evaluated. Instead of
range, we can use a list, dictionary, string etc… As shown in the slicing function of strings the
range function can also be given the arguments (start, stop, step). By default, start = 0 and
step = 1.
Syntax: for i in range(n):
expression-1
…
expression-n
Example: (The sum of all even numbers from 2 to 10 (both included).)
Functions in Python:
Function definition and structure:
A function in Python is a black box that returns a value when it is called in expressions with
required arguments. This black box contains the program (algorithm) to do the required
operations and return the output. In python, functions are defined using the ‘def’
statement. The def statement creates a function object and assigns it to a name. Its general
format is as follows:
def name(arg1, arg2,... argN):
statements
return value
Here, def consists of a header line followed by a block of statements. The statement block
becomes the function’s body i.e., the code Python executes each time the function is later
called. In the header line of def, the name and arguments of the function are specified.
Function bodies often contain a return statement. When the function reaches the return
statement it ends the function and returns the value to the caller. If there is no return
statement, then the function returns ‘None’.
Function Call:
A function call is an expression consisting of the function name followed by arguments
enclosed in parentheses. If there is more than one argument, the arguments are separated
by commas. A function call is an expression that can be used like any other expression of the
type specified for the value returned by the function.
SYNTAX
Function_Name ( Argument_List )
where the Argument_List is a comma-separated list of arguments: Argument_1 ,
Argument_2 , . . . , Argument_Last
Example: x = max(5,10)
Here, the built-in function ‘max(a,b)’ is called and the value returned is assigned to x. This
function returns the maximum value of 5 and 10. So, x = 10.
Scope of Variables:
All the code we write in Python which is not inside a ‘def’ block, is said to be global to the
program. Global means that all the variables in this scope can be accessed and used
anywhere in the program. Functions define a local scope and modules define a global scope.
By default, all the names assigned inside a function definition are put in the local scope i.e.,
those variables which are assigned in the function can’t be used outside it.
Functions can be nested: Unlike to ‘C/C++’, a function can be enclosed within another
function or a loop or a conditional statement. The variables declared in an enclosing
function can be used in all the functions enclosed within it.
In order to use a global variable in a function, it must be declared as a global variable within
the function. All the changes made will be in global scope. If we need to assign a name that
lives in an enclosing def, we can do so by declaring it in a nonlocal statement.
The LEBG Rule: (Within a def statement)
Name assignments create or change local names by default.
Name references search at most four scopes: local, then enclosing functions (if any),
then global, then built-in.
Names declared in global and nonlocal statements map assigned names to enclosing
module and function scopes, respectively.
An Example:
Recursive functions:
Functions that call themselves either directly or indirectly in order to loop are called
Recursive functions. Recursion allows programs to traverse structures that have arbitrary
and unpredictable shapes and depths like travelling routes etc… Recursion is an alternative
to loops but may not be the efficient one. Always, a condition must be provided to stop the
recursion
Analysis of problems becomes easier with recursion. For example, computing sum of first n
natural numbers using recursion won’t differ much w.r.t iterative method. While solving
arbitrary structures like Towers of Hanoi, becomes handy. In Towers of Hanoi, it becomes
difficult to solve the problem using stacks. Recursion, makes this problem easy.
1. If there is one CD then directly move it.
2. If they are ‘n’, move ‘n-1’ to auxiliary tower and repeat step 1.
3. Repeat steps 1 and 2 for remaining CDs until all CDs are moved to the required
tower.
Program: (Towers of Hanoi)