Python Programming Notes - UNIT-I
Python Programming Notes - UNIT-I
1.1 INTRODUCTION:
1.2 FEATURES :
1) Easy to Learn and Use: Python is easy to learn and use. It is developer-friendly and high
level programming language.
2) Expressive Language: Python language is more expressive means that it is more
understandable and readable.
3) Free and Open Source: Python language is freely available at offical web address.The
source-code is also available. Therefore it is open source.
4) High level: Being a high-level language, Python code is quite like English. Looking at it,
you can tell what the code is supposed to do. Also, since it is dynamically-typed, it mandates
indentation. This aids readability.
5) Portable: Python language is also a portable language. for example, if we have python
code for windows and if we want to run this code on other platform such as Linux, Unix and
Mac then we do not need to change it, we can run this code on any platform.
6) Object-Oriented Language: Python supports object oriented language and concepts of
classes and objects come into existence.
7) Extensible: It implies that other languages such as C/C++ can be used to compile the code
and thus it can be used further in our python code.
8) Embeddable or Integrate : It can be easily integrated with languages like C, C++, JAVA
etc.
9) Interpreted Language: Python is an Interpreted Language. because python code is executed
line by line at a time. like other language c, c++, java etc there is no need to compile python
code this makes it easier to debug our code. The source code of python is converted into an
immediate form called byte code.
10) Large Standard Library: Python has a large and broad library and provides rich set of
module and functions for rapid application development.
11) GUI Programming Support: Graphical user interfaces can be developed using Python
12) Dynamically Typed: Python is dynamically-typed language. That means the type (for
example- int, double, long etc) for a variable is decided at run time not in advance because of
this feature we don’t need to specify the type of variable.
Python is known for its general purpose nature that makes it applicable in almost each
domain of software development. Python as a whole can be used in any sphere of
development. Here, we are specifying applications areas where python can be applied.
1) Web Applications:
We can use Python to develop web applications. It provides libraries to handle
internet protocols such as HTML and XML, JSON, Email processing, request, beautifulSoup,
Feedparser etc. It also provides Frameworks such as Django, Pyramid, Flask etc to design
and delelop web based applications. Some important developments are: PythonWikiEngines,
Pocoo, PythonBlogSoftware etc.
2) Desktop GUI Applications:
Python provides Tk GUI library to develop user interface in python based application.
Some other useful toolkits wxWidgets, Kivy, pyqt that are useable on several platforms. The
Kivy is popular for writing multitouch applications.
3) Software Development:
Python is helpful for software development process. It works as a support language
and can be used for build control and management, testing etc.
4) Scientific and Numeric:
Python is popular and widely used in scientific and numeric computing. Some useful
library and package are SciPy, Pandas, IPython etc. SciPy is group of packages of
engineering, science and mathematics.
5) Business Applications:
Python is used to build Bussiness applications like ERP and e-commerce systems.
Tryton is a high level application platform.
6) Console Based Application:
We can use Python to develop console based applications. For example: IPython.
7) Audio or Video based Applications:
Python is awesome to perform multiple tasks and can be used to develop multimedia
applications. Some of real applications are: TimPlayer, cplay etc.
8) 3D CAD Applications:
To create CAD application Fandango is a real application which provides full features
of CAD.
9) Enterprise Applications:
Python can be used to create applications which can be used within an Enterprise or
an Organization. Some real time applications are: OpenErp, Tryton, Picalo etc.
10) Applications for Images:
Using Python several application can be developed for image. Applications developed
are: VPython, Gogh, imgSeek etc.
There are four steps that python takes when you hit return: lexing, parsing, compiling,
and interpreting. Lexing is breaking the line of code you just typed into tokens. The parser
takes those tokens and generates a structure that shows their relationship to each other (in this
case, an Abstract Syntax Tree). The compiler then takes the AST and turns it into one (or
more) code objects. Finally, the interpreter takes each code object executes the code it
represents.
Compiler compiles your source code (the statements in your file) into a format
known as byte code. Compilation is simply a translation step!
The Python Virtual Machine(PVM) is the runtime engine of Python; it’s always
present as part of the Python system, and is the component that truly runs your scripts.
The bytecode (.pyc file) is loaded into the Python runtime and interpreted by a Python
Virtual Machine, which is a piece of code that reads each instruction in the
bytecode and executes.
Variables can hold values of different data types. Python is a dynamically typed
language hence we need not define the type of the variable while declaring it. The interpreter
implicitly binds the value with its type.
Python enables us to check the type of the variable used in the program. Python
provides us the type() function which returns the type of the variable passed.
Consider the following example to define the values of different data types and checking its
type.
A=10
b="Hi Python"
c = 10.5
print(type(a));
print(type(b));
print(type(c));
Output:
<type 'int'>
<type 'str'>
<type 'float'>
A variable can hold different types of values. For example, a person's name must be stored as
a string whereas its id must be stored as an integer.
Python provides various standard data types that define the storage method on each of them.
The data types defined in Python are given below.
1. Numbers
2. Sequences
1. String
2. List
3. Tuple
4. sets
3. Dictionary
1.5.1 Numbers:
Number stores numeric values. Python creates Number objects when a number is assigned to
a variable. For example;
Python allows us to use a lower-case L to be used with long integers. However, we must
always use an upper-case L to avoid confusion.
A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and
imaginary parts respectively).
1.5.2 Sequences:
In Python, sequence is the generic term for an ordered set. There are several types of
sequences in Python, the following three are the most important.
Strings are a special type of sequence that can only store characters, and they have a
special notation. However, all of the sequence operations described below can also be used
on strings.
Lists are the most versatile sequence type. The elements of a list can be any object,
and lists are mutable - they can be changed. Elements can be reassigned or removed, and
new elements can be inserted.
Tuples are like lists, but they are immutable - they can't be changed.
1.5.2.1 String:
The string can be defined as the sequence of characters represented in the quotation marks. In
python, we can use single, double, or triple quotes to define a string.
String handling in python is a straightforward task since there are various inbuilt functions
and operators provided.
In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
The operator * is known as repetition operator as the operation "Python " *2 returns "Python
Python ".
Output:
he
o
hello Ravihello Ravi
hello Ravi how are you
1.5.2.2 List:
Lists are similar to arrays in C. However; the list can contain data of different types. The
items stored in the list are separated with a comma (,) and enclosed within square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator (+)
and repetition operator (*) works with the list in the same way as they were working with the
strings.
Output:
[2]
[1, 'hi']
[1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
1.5.2.3 Tuple:
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and
enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a
tuple.
t = ("hi", "python", 2)
print (t[1:]);
print (t[0:1]);
print (t);
print (t + t);
print (t * 3);
print (type(t))
t[2] = "hi"; # tuple values are immutable
Output:
('python', 2)
('hi',)
('hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2, 'hi', 'python', 2)
<type 'tuple'>
Traceback (most recent call last):
File "main.py", line 8, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment
1.5.2.4 Sets:
A set is a collection of data types in Python, same as the list and tuple. However, it is
not an ordered collection of objects. The set is a Python implementation of the set in
Mathematics. A set object has suitable methods to perform mathematical set operations like
union, intersection, difference, etc.
A set object contains one or more items, not necessarily of the same type, which are separated
by comma and enclosed in curly brackets {}.
Syntax:
Set={value1,value2,value3,....valueN}
The following defines a set object.
A set doesn't store duplicate objects. Even if an object is added more than once inside the
curly brackets, only one copy is held in the set object. Hence, indexing and slicing operations
cannot be done on a set object.
>>> S1={1, 2, 2, 3, 4, 4, 5, 5}
>>> S1
{1, 2, 3, 4, 5}
1.5.3 Dictionary:
The items in the dictionary are separated with the comma and enclosed in the curly braces {}.
Output:
1.6 Operator:
1. Arithmetic operators
2. Comparison or Relational operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Special operators
a. Identity operators
b. Membership operators
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(exp)
print(mod)
Output:
13
5
36
2.25
6561
2
> Greater than: True if left operand is greater than the right x>y
< Less than: True if left operand is less than the right x<y
Greater than or equal to: True if left operand is greater than or equal to the
<= Less than or equal to: True if left operand is less than or equal to the right x <= y
Output:
False
True
False
True
False
True
3.Logical operators: Logical operators perform Logical AND, Logical OR and Logical
NOT operations.
OPERATOR DESCRIPTION SYNTAX
And Logical AND: True if both the operands are true x and y
Output:
False
True
False
4.Bitwise operators: Bitwise operators acts on bits and performs bit by bit operation.
OPERATOR DESCRIPTION SYNTAX
| Bitwise OR x|y
~ Bitwise NOT ~x
Output:
0
14
-11
14
2
40
5.Assignment operators: Assignment operators are used in Python to assign values to
variables.
a = 5 is a simple assignment operator that assigns the value 5 on the right to the
variable a on the left.
There are various compound operators in Python like a += 5 that adds to the variable
and later assigns the same. It is equivalent to a = a + 5.
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
6.Special Operators:
There are some special type of operators like-
1. Identity operators-
is and is not are the identity operators both are used to check if two values are
located on the same part of the memory. Two variables that are equal does not
imply that they are identical.
Output:
False
True
False
print('G' in x)
print('it-a' not in x)
print('AGI' not in x)
print(3 in y)
print('b' in y)
Output:
True
True
False
True
False
1.7. Expressions:
Expressions are representations of value. They are different from statement in the fact
that statements do something while expressions are representation of value. For example any
string is also an expressions since it represents the value of the string as well.
Python has some advanced constructs through which you can represent values and
hence these constructs are also called expressions.
Python expressions only contain identifiers, literals, and operators. So, what are these?
Identifiers: Any name that is used to define a class, function, variable module, or object is an
identifier.
Literals: These are language-independent terms in Python and should exist independently in
any programming language. In Python, there are the string literals, byte literals, integer
literals, floating point literals, and imaginary literals.
Operators: In Python you can implement the following operations using the corresponding
tokens.
Operator Token
Add +
subtract -
multiply *
Operator Token
Power **
Integer Division /
remainder %
decorator @
And &
Or \
Binary Xor ^
Operator Token
Check equality ==
List comprehension
For example, the following code will get all the number within 10 and put them in a list.
Dictionary comprehension
This is the same as list comprehension but will use curly braces:
{ k, v for k in iterable }
For example, the following code will get all the numbers within 5 as the keys and will keep
the corresponding squares of those numbers as the values.
Generator expression
For example, the following code will initialize a generator object that returns the values
within 10 when the object is called.
Conditional Expressions
Example:
Operators Usage
{} Parentheses (grouping)
f(args…) Function call
x[index:index] Slicing
x[index] Subscription
x.attribute Attribute reference
** Exponent
~x Bitwise not
+x, -x Positive, negative
*, /, % Product, division, remainder
+, – Addition, subtraction
<<, >> Shifts left/right
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
in, not in, is, is not, <, <=, >, >=,
<>, !=, == Comparisons, membership, identity
not x Boolean NOT
and Boolean AND
or Boolean OR
The associativity is the order in which Python evaluates an expression containing multiple
operators of the same precedence. Almost all operators except the exponent (**) support the
left-to-right associativity.
1.9.2 For:
The for loop in Python is used to iterate the statements or a part of the program several
times. It is frequently used to traverse the data structures like list, tuple, or dictionary.
Output:
List Iteration
Anurag
Information
Technology
Tuple Iteration
RaviRaju
Sekhar
Prudhvi
String Iteration
K
I
N
G
Dictionary Iteration
Example:2
i=1
n=int(input("Enter the number up to which you want to print the natural numbers?"))
for i in range(0,10):
print(i,end = ' ')
Output:
0 1 2 3 4 5 6 7 8 9
Example:3
for num in range(1,10,2):
print num
output:
1
3
5
7
9
Example:
n = int(input("Enter the number of rows you want to print?"))
i,j=0,0
for i in range(0,n):
print()
for j in range(0,i+1):
print("*",end="")
Output:
Enter the number of rows you want to print?5
*
**
***
****
*****
Syntax :
while expression:
statement(s)
In Python, all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements.
# prints Hello Anurag 3 Times
count = 0
while (count < 3):
count = count+1
print("Hello Anurag")
Output:
Hello Anurag
Hello Anurag
Hello Anurag
1.10.1 if statement:
if statement is the most simple decision making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e if a certain condition is
true then a block of statement is executed otherwise not. Python uses indentation to identify a
block.
Syntax:
if condition:
statement1
statement2
# Here if the condition is true, if block will consider only statement1 to be inside its block.
Flowchart:
i = 10
if (i > 15):
print ("10 is less than 15")
print ("I am Not in if")
output:
I am Not in if
1.10.2 if-else statement:
The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something else if
the condition is false. Here comes the else statement. We can use the else statement
with if statement to execute a block of code when the condition is false.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Flow chart:
Example:
# python program to illustrate If else statement
i = 20;
if (i < 15):
print ("i is smaller than 15")
print ("i'm in if Block")
else:
print ("i is greater than 15")
print ("i'm in else Block")
print ("i'm not in if and not in else Block")
Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
1.10.3 Nested-if
A nested if is an if statement that is the target of another if statement. Nested if
statements means an if statement inside another if statement. Yes, Python allows us to nest if
statements within if statements. i.e, we can place an if statement inside another if statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Flow chart:-
Example:
# python program to illustrate nested If statement
i = 10
if (i == 10):
# First if statement
if (i < 15):
print ("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print ("i is smaller than 12 too")
else:
print ("i is greater than 15")
output:
i is smaller than 15
i is smaller than 12 too
Syntax:-
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Flow Chart:-
Example:
# Python program to illustrate if-elif-else ladder
i = 20
if (i == 10):
print ("i is 10")
elif (i == 15):
print ("i is 15")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")
output:
i is 20
# Python program to find the largest number among the three input numbers
# take three numbers from user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
This program can explain as follows- Declare total unit consumed by the customer using the
variable unit. If the unit consumed less or equal to 100 units, calculates the total amount
of consumed =units*1.5. If the unit consumed between 100 to 200 units, calculates the total
amount of consumed=(100*1.5)+(unit-100)*2.5). If unit consumed between 200 to 300
units ,calculates total amount ofconsumed=(100*1.5)+(200-100)*2.5+(units-200)*4. If
unit consumed between 300-350 units ,calculates total amount of consumed=(100*1.5)+
(200-100)*2.5+(300-200)*4+(units-350)*5. If the unit consumed above 350 units, fixed
charge – 1500/=
additional charges
if units<=100 – 25.00, if 100< units and units<=200 – 50.00, if 200 < units and units<=300 –
75.00, if 300<units and units<=350 – 100.00, if units above 350 – No additional charges
fixedcharge=50.00
elif(units>300):
payAmount=2500;#fixed rate
fixedcharge=75.00
else:
payAmount=0;
Total= payAmount+fixedcharge
print("\nElecticity bill pay=%.2f: " %Total);
output:
Number of unit consumed: 234
Electricity bill pay=586.00:
1.11.1 Input():
Developers often have a need to interact with users, either to get data or to provide
some sort of result. Most programs today use a dialog box as a way of asking the user to
provide some type of input. While Python provides us with two inbuilt functions to read the
input from the keyboard.
input ( prompt )
raw_input ( prompt )
input ( ) : This function first takes the input from the user and then evaluates the expression,
which means Python automatically identifies whether user entered a string or a number or
list. If the input provided is not correct then either syntax error or exception is raised by
python. For example –
output:
Enter your value: 89
89
Code:
# Program to check input
# type in Python
output:
Enter number: 1234
1234
Enter name: Raja
Raja
Type of number <class ‘str’>
Type of name <class ‘str’>
raw_input ( ) : This function works in older version (like Python 2.x). This function takes
exactly what is typed from the keyboard, convert it to string and then return it to the variable
in which we want to store. For example –
Output:
Enter your name: Ravi Raju Bandlamudi
Ravi Raju Bandlamudi
Here, ch is a variable which will get the string value, typed by user during the execution of
program. Typing of data for the raw_input() function is terminated by enter key. We can
use raw_input() to enter numeric data also.
1.11.2 Output():
In order to print the output, python provides us with a built-in function called print().
Syntax:
print (expression/constant/variable)
Print evaluates the expression before printing it on the monitor. Print statement outputs an
entire (complete) line and then goes to next line for subsequent output (s). To print more than
one item on a single line, comma (,) may be used.
Example:
>>> print ("Hello")
Hello
>>> print (5.5)
5.5
>>> print (4+6)
10
Syntax : { } .format(value)
Parameters :
(value) : Can be an integer, floating point numeric constant, string, characters or even
variables.
Returntype : Returns a formatted string with the value passed as parameter in the
placeholder position.
Output:
Multiple pairs of curly braces can be used while formatting the string. Let’s say if another
variable substitution is needed in sentence, can be done by adding a second pair of curly
braces and passing a second value into the method. Python will replace the placeholders by
values in order.
Syntax :
{ } { } .format(value1, value2)
Parameters :
(value1, value2) : Can be integers, floating point numeric constants, strings, characters and
even variables. Only difference is, the number of values passed as parameters in format()
method must be equal to the number of placeholders created in the string.
Output:
Information Technology, is a best branch in Anurag
Hi! My name is RaviRaju and I am 35 years old
This is one two three four
1.12 Functions :
In Python, function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program
grows larger and larger, functions make it more organized and manageable.
It avoids repetition and makes code reusable.
Functions are a convenient way to divide your code into useful blocks, allowing us to
order our code, make it more readable, reuse it and save some time. Also functions are a key
way to define interfaces so programmers can share their code.
There are three types of functions in Python:
1. Built-in functions, such as help() to ask for help, min() to get the minimum
value, print()to print an object to the terminal, len(x) or type(y) or
even random.choice([1, 2, 3]), these functions are called predefined functions.
2. User-Defined Functions (UDFs), which are functions that users create to help
them out; And
3. Anonymous functions, which are also called lambda functions
Defining Functions
A function is defined in Python by the following format:
If a function takes no arguments, it must still include the parentheses, but without anything in
them:
def functionname():
statement1
statement2
...
The arguments in the function definition bind the arguments passed at function
invocation (i.e. when the function is called), which are called actual parameters, to the names
given when the function is defined, which are called formal parameters. The interior of the
function has no knowledge of the names given to the actual parameters; the names of the
actual parameters may not even be accessible (they could be inside another function).
def square(x):
return x*x
A function can define variables within the function body, which are considered 'local' to the
function. The locals together with the arguments comprise all the variables within the scope
of the function. Any names within the function are unbound when the function returns or
reaches the end of the function body.
You can return multiple values as follows:
def first2items(list1):
return list1[0], list1[1]
a, b = first2items(["Hello", "world", "hi", "universe"])
print a + " " + b
print(“sum is :” plus(10,50))
output:
sum is: 60
1.12.3 Arguments:
The arguments of a function are defined within the def statement. Like all other
variables in Python, there is no explicit type associated with the function arguments. This fact
is important to consider when making assumptions about the types of data that your function
will receive.
Function arguments can optionally be defined with a default value. The default value will be
assigned in the case that the argument is not present in the call to the function. All arguments
without default values must be listed before arguments with default values in the function
definition.
Declaring Arguments
When calling a function that takes some values for further processing, we need to send some
values as Function Arguments. For example:
Required arguments
Default argumengts
Key word arguments
Variable length arguments or Arbitrary Arguments
We can provide the arguments at the time of function calling. As far as the required
arguments are concerned, these are the arguments which are required to be passed at the time
of function calling with the exact match of their positions in the function call and function
definition. If either of the arguments is not provided in the function call, or the position of the
arguments is changed, then the python interpreter will show the error.
Example 1
#the argument name is the required argument to the function func
def func(name):
message = "Hi "+name;
return message;
name = input("Enter the name?")
print(func(name))
Output:
Example 2
#the function simple_interest accepts three arguments and returns the simple interest accordin
gly
def simple_interest(p,t,r):
return (p*t*r)/100
p = float(input("Enter the principle amount? "))
r = float(input("Enter the rate of interest? "))
t = float(input("Enter the time in years? "))
print("Simple Interest: ",simple_interest(p,r,t))
Output:
Enter the principle amount? 10000
Enter the rate of interest? 5
Enter the time in years? 2
Simple Interest: 1000.0
Example 3
#the function calculate returns the sum of two arguments a and b
def calculate(a,b):
return a+b
calculate(10) # this causes an error as we are missing a required arguments b.
Output:
TypeError: calculate() missing 1 required positional argument: 'b'
For some functions, you may want to make some parameters optional and use default values
in case the user does not want to provide values for them. This is done with the help of default
argument values. You can specify default argument values for parameters by appending to the
parameter name in the function definition the assignment operator ( =) followed by the default value.
Note that the default argument value should be a constant. More precisely, the default argument value
should be immutable – this is explained in detail in later chapters. For now, just remember this.
Example:
#!/usr/bin/python
# Filename: func_default.py
say('Hello')
say('World', 5)
Output:
$ python func_default.py
Hello
WorldWorldWorldWorldWorld
How It Works:
The function named say is used to print a string as many times as specified. If we
don’t supply a value, then by default, the string is printed just once. We achieve this by
specifying a default argument value of 1 to the parameter times.
In the first usage of say, we supply only the string and it prints the string once. In the second
usage of say, we supply both the string and an argument 5 stating that we want to say the
string message 5 times.
Important -Only those parameters which are at the end of the parameter list can be
given default argument values i.e. you cannot have a parameter with a default argument value
preceding a parameter without a default argument value in the function’s parameter list.This
is because the values are assigned to the parameters by position. For example, def func(a,
b=5) is valid, but def func(a=5, b) is not valid.
Example:
#!/usr/bin/python
# Filename: func_key.py
func(3, 7)
func(25, c=24)
func(c=50, a=100)
Output:
$ python func_key.py
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
How It Works:
The function named func has one parameter without a default argument value,
followed by two parameters with default argument values.
In the first usage, func(3, 7), the parameter a gets the value 3, the parameter b gets the
value 7 and c gets the default value of 10.
In the second usage func(25, c=24), the variable a gets the value of 25 due to the
position of the argument. Then, the parameter cgets the value of 24 due to naming i.e.
keyword arguments. The variable b gets the default value of 5.
In the third usage func(c=50, a=100), we use keyword arguments for all specified values.
Notice that we are specifying the value for parameter c before that for a even though a is
defined before c in the function definition.
Sometimes, we do not know in advance the number of arguments that will be passed
into a function.Python allows us to handle this kind of situation through function calls with
arbitrary number of arguments.
In the function definition we use an asterisk (*) before the parameter name to denote
this kind of argument.
Following is the syntax to create a function that can take variable length arguments.
def func(*args):
Where, func is the name of the function and *args holds variable length arguments.
In the following Python program we are recreating the sum function but this time we are
modifying it to take multiple arguments and print them.
Example:
# func
def sum(*args):
print(type(args))
print(args)
sum(10, 20)
sum(10, 20, 30)
sum(10, 20, 30, 40)
Output.
<class 'tuple'>
(10, 20)
<class 'tuple'>
(10, 20, 30)
<class 'tuple'>
(10, 20, 30, 40
So, we can see that the args variable is of type tuple and we are also able to print all
the values that were passed to the function as a tuple.
Since the multiple arguments passed to the function are tuple so we can access them using for
loop.
In the following Python program we are printing out the individual argument.
Example-2:
# func
def sum(*args):
for arg in args:
print(arg)
print('sum(10, 20)')
sum(10, 20)
print('sum(10, 20, 30)')
sum(10, 20, 30)
print('sum(10, 20, 30, 40)')
sum(10, 20, 30, 40)
Output:
sum(10, 20)
10
20
sum(10, 20, 30)
10
20
30
sum(10, 20, 30, 40)
10
20
30
40
So, now that we are able to access the individual argument passed to the function let's
go ahead and modify the sum function that we are working on to return us the sum of the
arguments.
Example -3:
# func
def sum(*args):
result = 0
for arg in args:
result = result + arg
return result
print(sum(10, 20)) # 30
print(sum(10, 20, 30)) # 60
print(sum(10, 20, 30, 40)) # 100
Dept. Of Information Technology Python Programming-UNIT-I - Page No. 37
ANURAG GROUP OF INSTITUTIONS
Let's add some checks to the sum function so that we only add arguments that are numbers.
# func
def sum(*args):
result = 0
for arg in args:
if type(arg) in (int, float):
result = result + arg
return result
print(sum(10, 20.10, "hello")) # 30.1
The scopes of the variables depend upon the location where the variable is being declared.
The variable declared in one part of the program may not be accessible to the other parts.
In python, the variables are defined with the two types of scopes.
1. Global variables
2. Local variables
The variable defined outside any function is known to have a global scope whereas the
variable defined inside a function is known to have a local scope.
Example 1
def print_message():
message = "hello !! I am going to print a message." # the variable message is local to the fu
nction itself
print(message)
print_message()
print(message) # this will cause an error since a local variable cannot be accessible here.
Output:
Example 2
def calculate(*args):
sum=0
for arg in args:
sum = sum +arg
print("The sum is",sum)
sum=0
calculate(10,20,30) #60 will be printed as the sum
print("Value of sum outside the function:",sum) # 0 will be printed
Output:
The sum is 60
Value of sum outside the function: 0
1.15 Lambda Functions:
In Python, we use the lambda keyword to declare an anonymous function, which is
why we refer to them as "lambda functions". An anonymous function refers to a function
declared with no name. Although syntactically they look different, lambda functions behave
in the same way as regular functions that are declared using the def keyword.
The anonymous function contains a small piece of code. It simulates inline functions
of C and C++, but it is not exactly an inline function.
A lambda function can take any number of arguments, but they contain only a single
expression. An expression is a piece of code executed by the lambda function, which
may or may not return any value.
Lambda functions can be used to return function objects.
Syntactically, lambda functions are restricted to only a single expression.
For example:
remainder = lambda num: num % 2
print(remainder(5))
Output:
1
In this code the lambda num: num % 2 is the lambda function. The num is the
argument while num % 2 is the expression that is evaluated and the result of the expression is
returned. The expression gets the modulus of the input parameter by 2. Providing 5 as the
parameter, which is divided by 2, we get a remainder of 1.
You should notice that the lambda function in the above script has not been assigned
any name. It simply returns a function object which is assigned to the identifier remainder.
However, despite being anonymous, it was possible for us to call it in the same way that we
call a normal function. The statement:
lambda num: num % 2
Is similar to the following:
def remainder(num):
return num % 2
print(product(2, 3))
Output
6
The main role of the lambda function is better described in the scenarios when we use
them anonymously inside another function. In python, the lambda function can be used as an
argument to the higher order functions as arguments. Lambda functions are also used in the
scenario where we need a Consider the following example.
Example 1:
#the function table(n) prints the table of n
def table(n):
return lambda a:a*n; # a will contain the iteration variable i and a multiple of n is returne
d at each function call
n = int(input("Enter the number?"))
b = table(n) #the entered number is passed into the function table. b will contain a lambda fun
ction which is called again and again with the iteration variable i
for i in range(1,11):
print(n,"X",i,"=",b(i)); #the lambda function b is called with the iteration variable i,
Output:
Example 2
List = {1,2,3,4,10,123,22}
Oddlist = list(filter(lambda x:(x%3 == 0),List)) # the list contains all the items of the list for
which the lambda function evaluates to true
Dept. Of Information Technology Python Programming-UNIT-I - Page No. 40
ANURAG GROUP OF INSTITUTIONS
print(Oddlist)
Output:
[3, 123]
Example 3
Output:
The most popular example of recursion is the calculation of the factorial. Mathematically
the factorial is defined as: n! = n * (n-1)!
We use the factorial itself to define the factorial. Hence, this is a suitable case to write
a recursive function. Let us expand the above definition for the calculation of the factorial
value of 5.
5! = 5 X 4!
5 X4 X 3!
5 X4 X 3 X 2!
5 X4 X 3 X 2 X 1!
5 X4 X 3 X 2 X 1
= 120
While we can perform this calculation using a loop, its recursive function involves
successively calling it by decrementing the number until it reaches 1. The following is a
recursive function to calculate the factorial.
>>> factorial(5)
5*4*3*2*1
120
When the factorial function is called with 5 as argument, successive calls to the same
function are placed, while reducing the value of 5. Functions start returning to their earlier
call after the argument reaches 1. The return value of the first call is a cumulative product of
the return values of all calls.
Example -2:
Problem Description
The program takes two numbers and finds the GCD of two numbers using recursion.
Program/Source Code
Here is source code of the Python Program to find the GCD of two numbers using recursion.
The program output is also shown below.
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
GCD=gcd(a,b)
print("GCD is: ")
print(GCD)
Program Explanation
1. User must enter two numbers.
2. The two numbers are passed as arguments to a recursive function.
3. When the second number becomes 0, the first number is returned.
4. Else the function is recursively called with the arguments as the second number and the
remainder when the first number is divided by the second number.
5. The first number is then returned which is the GCD of the two numbers.
6. The GCD is then printed.
Runtime Test Cases
Case 1:
Enter first number:5
Enter second number:15
GCD is:
5
Case 2:
Enter first number:30
Enter second number:12
GCD is:
6
Example-3:
Problem Description
The program takes the number of terms and determines the fibonacci series using recursion
upto that term.
Program/Source Code
Here is source code of the Python Program to find the fibonacci series using recursion. The
program output is also shown below.
def fibonacci(n):
if(n <= 1):
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
n = int(input("Enter number of terms:"))
print("Fibonacci sequence:")
for i in range(n):
print fibonacci(i),
Program Explanation
1. User must enter the number of terms and store it in a variable.
2. The number is passed as an argument to a recursive function.
3. The base condition is that the number has to be lesser than or equal to 1.
4. Otherwise the function is called recursively with the argument as the number minus 1
added to the function called recursively with the argument as the number minus 2.
5. The result is returned and a for statement is used to print the fibonacci series.
Runtime Test Cases
Case 1:
Enter number of terms:5
Fibonacci sequence:
01123
Dept. Of Information Technology Python Programming-UNIT-I - Page No. 43
ANURAG GROUP OF INSTITUTIONS
Case 2:
Enter number of terms:7
Fibonacci sequence:
0112358
A python module can be defined as a python program file which contains a python
code including python functions, class, or variables. In other words, we can say that our
python code file saved with the extension (.py) is treated as the module. We may have a
runnable code inside the python module.
Modules in Python provides us the flexibility to organize the code in a logical way.
To use the functionality of one module into another, we must have to import the
specific module.
Example
In this example, we will create a module named as file.py which contains a function func that
contains a code to print some message on the console.
Let's create the module named as file.py.
#displayMsg prints a message to the name being passed.
def displayMsg(name)
print("Hi "+name);
Here, we need to include this module into our main module to call the method displayMsg()
defined in the module named file.
We need to load the module in our python code to use its functionality. Python provides two
types of statements as defined below.
The import statement
The from-import statement
The import statement is used to import all the functionality of one module into another. Here,
we must notice that we can use the functionality of any python source file by importing that
file as the module into another python source file.
We can import multiple modules with a single import statement, but a module is loaded once
regardless of the number of times, it has been imported into our file.
Hence, if we need to call the function displayMsg() defined in the file file.py, we have to
import that file as a module into our module as shown in the example below.
Example:
import file;
name = input("Enter the name?")
file.displayMsg(name)
Output:
Instead of importing the whole module into the namespace, python provides the flexibility to
import only the specific attributes of a module. This can be done by using from? import
statement. The syntax to use the from-import statement is given below.
Consider the following module named as calculation which contains three functions as
summation, multiplication, and divide.
calculation.py:
Main.py:
Output:
The from...import statement is always better to use if we know the attributes to be imported
from the module in advance. It doesn't let our code to be heavier. We can also import all the
attributes from a module by using *.
Python provides us the flexibility to import some module with a specific name so that we can
use this name to use that module in our python source file.
Example
#the module calculation of previous example is imported in this example as cal.
import calculation as cal;
a = int(input("Enter a?"));
b = int(input("Enter b?"));
print("Sum = ",cal.summation(a,b))
Output:
Enter a?10
Enter b?20
Sum = 30
The dir() function returns a sorted list of names defined in the passed module. This list
contains all the sub-modules, variables and functions defined in this module.
Example
import json
List = dir(json)
print(List)
Output:
As we have already stated that, a module is loaded once regardless of the number of times it
is imported into the python source file. However, if you want to reload the already imported
module to re-execute the top-level code, python provides us the reload() function. The syntax
to use the reload() function is given below.
reload(<module-name>)
for example, to reload the module calculation defined in the previous example, we must use
the following line of code.
reload(calculation)
Python packages
The packages in python facilitate the developer with the application development
environment by providing a hierarchical directory structure where a package contains sub-
packages, modules, and sub-modules. The packages are used to categorize the application
level code efficiently.
Let's create a package named Employees in your home directory. Consider the following
steps.
2. Create a python source file with name ITEmployees.py on the path /home/Employees.
Dept. Of Information Technology Python Programming-UNIT-I - Page No. 47
ANURAG GROUP OF INSTITUTIONS
ITEmployees.py
def getITNames():
List = ["John", "David", "Nick", "Martin"]
return List;
3. Similarly, create one more python file with name BPOEmployees.py and create a function
getBPONames().
4. Now, the directory Employees which we have created in the first step contains two python
modules. To make this directory a package, we need to include one more file here, that is
__init__.py which contains the import statements of the modules defined in this directory.
__init__.py
5. Now, the directory Employees has become the package containing two python modules.
Here we must notice that we must have to create __init__.py inside a directory to convert this
directory to a package.
6. To use the modules defined inside the package Employees, we must have to import this in
our python source file. Let's create a simple python source file at our home directory (/home)
which uses the modules defined in this package.
Test.py
import Employees
print(Employees.getNames())
Output:
We can have sub-packages inside the packages. We can nest the packages up to any
level depending upon the application requirements.
1.18 DOCSTRING:
Python documentation strings (or docstrings) provide a convenient way of
associating documentation with Python modules, functions, classes, and methods.
Python Docstring is the documentation string which is string literal, and it occurs in
the class, module, function or method definition, and it is written as a first statement.
Docstrings are accessible from the doc attribute for any of the Python object and also with the
built-in help() function can come in handy.
Also, Docstrings are great for the understanding the functionality of the larger part of
the code, i.e., the general purpose of any class, module or function whereas the comments are
used for code, statement, and expressions which tend to be small. They are a descriptive text
written by a programmer mainly for themselves to know what the line of code or expression
does. It is an essential part that documenting your code is going to serve well enough for
writing clean code and well-written programs. Though already mentioned there are no
standard and rules for doing so.
There are two forms of writing a Docstring: one-line Docstrings and multi-line
Docstrings. These are the documentation that is used by Data Scientists/programmers in their
projects.
1.18.1 One-line Docstrings
The one-line Docstrings are the Docstrings which fits all in one line. You can use one of the
quotes, i.e., triple single or triple double quotes and opening quotes and closing quotes need
to be the same. In the one-line Docstrings, closing quotes are in the same line as with the
opening quotes. Also, the standard convention is to use the triple-double quotes.
Example:
def square(a):
'''Returns argument a is squared.'''
return a**a
print (square.__doc__)
help(square)
Returns argument a is squared.
square(a)
Returns argument a is squared.
Here in the above code, you get the printed result:
Returns argument a is squared.
Help on function square in module __main__:
square(a)
Returns argument a is squared.
In the above Docstrings, you can observe that:
The line begins with a capital letter, i.e., R in our case and end with a period(".").
The closing quotes are on the same line as the opening quotes. This looks better for
one-liners.
There's no blank line either before or after the Docstring. It is good practice.
The above line in quotes is more of command than a description which ends with a
period sign at last.
Parameters:
argument1 (int): Description of arg1
Returns:
int:Returning value
"""
return argument1
print(some_function.__doc__)
Parameters:
argument1 (int): Description of arg1
Returns:
int:Returning value
Parameters:
argument1 (int): Description of arg1
Returns:
int: Returning value
Dept. Of Information Technology Python Programming-UNIT-I - Page No. 50
ANURAG GROUP OF INSTITUTIONS
Example:
Let's look at the example which can show how the multi-line strings can be used in
detail:
def string_reverse(str1):
""" Returns the reversed String.
Parameters:
str1 (str):The string which is to be reversed.
Returns:
reverse(str1):The string which gets reversed.
"""
reverse_str1 = ''
i = len(str1)
while i > 0:
reverse_str1 += str1[ i - 1 ]
i = i- 1
return reverse_str1
print(string_reverse('projkal998580'))
output:
085899lakjorp
You can see above that the summary line is on one line and is also separated from
other content by a single blank line. This convention needs to be followed which is useful for
the automatic indexing tools.
Function Description
delattr() Deletes the specified attribute (property or method) from the specified
object
divmod() Returns the quotient and the remainder when argument1 is divided by
argument2
hasattr() Returns True if the specified object has the specified attribute
(property/method)
map() Returns the specified iterator with the specified function applied to each
item
1. abs()
The abs() is one of the most popular Python built-in functions, which returns the absolute
value of a number. A negative value’s absolute is that value is positive.
>>> abs(-7)
7
>>> abs(7)
7
>>> abs(0)
2. all()
The all() function takes a container as an argument. This Built in Functions returns True if all
values in a python iterable have a Boolean value of True. An empty value has a Boolean
value of False.
>>> all({'*','',''})
False
>>> all([' ',' ',' '])
True
Dept. Of Information Technology Python Programming-UNIT-I - Page No. 54
ANURAG GROUP OF INSTITUTIONS
3. any()
Like all(), it takes one argument and returns True if, even one value in the iterable has a
Boolean value of True.
>>> any((1,0,0))
True
>>> any((0,0,0))
False
4. ascii()
It is important Python built-in functions, returns a printable representation of a python
object (like a string or a Python list). Let’s take a Romanian character.
>>> ascii('ș')
“‘\\u0219′”
Since this was a non-ASCII character in python, the interpreter added a backslash (\) and
escaped it using another backslash.
>>> ascii('ușor')
“‘u\\u0219or'”
Let’s apply it to a list.
>>> ascii(['s','ș'])
“[‘s’, ‘\\u0219’]”
5. bin()
bin() converts an integer to a binary string. We have seen this and other functions in our
article on Python Numbers.
>>> bin(7)
‘0b111’
We can’t apply it on floats, though.
>>> bin(7.0)
Traceback (most recent call last):
File “<pyshell#20>”, line 1, in <module>
bin(7.0)
TypeError: ‘float’ object cannot be interpreted as an integer
6. bool()
bool() converts a value to Boolean.
>>> bool(0.5)
True
>>> bool('')
False
>>> bool(True)
True
7. bytearray()
bytearray() returns a python array of a given byte size.
>>> a=bytearray(4)
>>> a
bytearray(b’\x00\x00\x00\x00′)
>>> a.append(1)
>>> a
bytearray(b’\x00\x00\x00\x00\x01′)
>>> a[0]=1
>>> a
bytearray(b’\x01\x00\x00\x00\x01′)
>>> a[0]
1
Let’s do this on a list.
>>> bytearray([1,2,3,4])
bytearray(b’\x01\x02\x03\x04′)
8. bytes():
bytes() returns an immutable bytes object.
>>> bytes(5)
b’\x00\x00\x00\x00\x00′
>>> bytes([1,2,3,4,5])
b’\x01\x02\x03\x04\x05′
>>> bytes('hello','utf-8')
b’hello’
Here, utf-8 is the encoding.
Both bytes() and bytearray() deal with raw data, but bytearray() is mutable, while bytes() is
immutable.
>>> a=bytes([1,2,3,4,5])
>>> a
b’\x01\x02\x03\x04\x05′
>>> a[4]=
3
Traceback (most recent call last):
File “<pyshell#46>”, line 1, in <module>
a[4]=3
TypeError: ‘bytes’ object does not support item assignment
Let’s try this on bytearray().
>>> a=bytearray([1,2,3,4,5])
>>> a
bytearray(b’\x01\x02\x03\x04\x05′)
>>> a[4]=3
>>> a
bytearray(b’\x01\x02\x03\x04\x03′)
9. callable()
callable() tells us if an object can be called.
>>> callable([1,2,3])
False
>>> callable(callable)
True
>>> callable(False)
False
>>> callable(list)
True
A function is callable, a list is not. Even the callable() python Built In function is callable.
10. chr()
chr() Built In function returns the character in python for an ASCII value.
>>> chr(65)
‘A’
>>> chr(97)
‘a’
>>> chr(9)
‘\t’
>>> chr(48)
‘0’
11. classmethod()
classmethod() returns a class method for a given method.
>>> class fruit:
def sayhi(self):
print("Hi, I'm a fruit")
>>> fruit.sayhi=classmethod(fruit.sayhi)
>>> fruit.sayhi()
Hi, I’m a fruit
When we pass the method sayhi() as an argument to classmethod(), it converts it into a
python class method one that belongs to the class. Then, we call it like we would call any
static method in python without an object.
12. compile()
compile() returns a Python code object. We use Python in built function to convert a string
code into object code.
>>> exec(compile('a=5\nb=7\nprint(a+b)','','exec'))
12
Here, ‘exec’ is the mode. The parameter before that is the filename for the file form which
the code is read.
Finally, we execute it using exec().
13. complex()
complex() function creates a complex number. We have seen this is our article on Python
Numbers.
>>> complex(3)
(3+0j)
>>> complex(3.5)
(3.5+0j)
>>> complex(3+5j)
(3+5j)
14. delattr()
delattr() takes two arguments- a class, and an attribute in it. It deletes the attribute.
>>> class fruit:
size=7
>>> orange=fruit()
>>> orange.size
7
>>> delattr(fruit,'size')
>>> orange.size
Traceback (most recent call last):
File “<pyshell#95>”, line 1, in <module>
orange.size
AttributeError: ‘fruit’ object has no attribute ‘size’
15. dict()
dict(), as we have seen it, creates a python dictionary.
>>> dict()
{}
>>> dict([(1,2),(3,4)])
{1: 2, 3: 4}
This was about dict() Python Built In function
16. dir()
dir() returns an object’s attributes.
>>> class fruit:
size=7
shape='round'
>>> orange=fruit()
>>> dir(orange)
[‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’,
‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’,
‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’,
‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__weakref__’, ‘shape’, ‘size’]
17. divmod()
divmod() in Python built-in functions, takes two parameters, and returns a tuple of their
quotient and remainder. In other words, it returns the floor division and the modulus of the
two numbers.
>>> divmod(3,7)
(0, 3)
>>> divmod(7,3)
(2, 1)
If you encounter any doubt in Python Built-in Function, Please Comment.
18. enumerate()
This Python Built In function returns an enumerate object. In other words, it adds a counter to
the iterable.
>>> for i in enumerate(['a','b','c']):
print(i)
(0, ‘a’)
(1, ‘b’)
(2, ‘c’)
19. eval()
This Function takes a string as an argument, which is parsed as an expression.
>>> x=7
>>> eval('x+7')
14
>>> eval('x+(x%2)')
8
20. exec()
exec() runs Python code dynamically.
>>> exec('a=2;b=3;print(a+b)')
5
>>> exec(input("Enter your program"))
Enter your programprint(2+3)
5
21. filter()
Like we’ve seen in python Lambda Expressios, filter() filters out the items for which the
condition is True.
>>> list(filter(lambda x:x%2==0,[1,2,0,False]))
[2, 0, False]
22. float()
This Python Built In function converts an int or a compatible value into a float.
>>> float(2)
2.0
>>> float('3')
3.0
>>> float('3s')
Traceback (most recent call last):
File “<pyshell#136>”, line 1, in <module>
float(‘3s’)
ValueError: could not convert string to float: ‘3s’
>>> float(False)
0.0
>>> float(4.7)
4.7
23. format()
We have seen this Python built-in function, one in our lesson on Python Strings.
>>> a,b=2,3
>>> print("a={0} and b={1}".format(a,b))
a=2 and b=3
>>> print("a={a} and b={b}".format(a=3,b=4))
a=3 and b=4
24. frozenset()
frozenset() returns an immutable frozenset object.
>>> frozenset((3,2,4))
frozenset({2, 3, 4})
25. getattr()
getattr() returns the value of an object’s attribute.
>>> getattr(orange,'size')
7
26. globals()
This Python built-in functions, returns a dictionary of the current global symbol table.
>>> globals()
{‘__name__’: ‘__main__’, ‘__doc__’: None, ‘__package__’: None, ‘__loader__’: <class
‘_frozen_importlib.BuiltinImporter’>, ‘__spec__’: None, ‘__annotations__’: {},
‘__builtins__’: <module ‘builtins’ (built-in)>, ‘fruit’: <class ‘__main__.fruit’>, ‘orange’:
<__main__.fruit object at 0x05F937D0>, ‘a’: 2, ‘numbers’: [1, 2, 3], ‘i’: (2, 3), ‘x’: 7, ‘b’: 3}
27. hasattr()
Like delattr() and getattr(), hasattr() Python built-in functions, returns True if the object has
that attribute.
>>> hasattr(orange,'size')
True
>>> hasattr(orange,'shape')
True
>>> hasattr(orange,'color')
False
28. hash()
hash() function returns the hash value of an object. And in Python, everything is an object.
>>> hash(orange)
6263677
>>> hash(orange)
6263677
>>> hash(True)
1
>>> hash(0)
0
>>> hash(3.7)
644245917
>>> hash(hash)
25553952
This was all about hash() Python In Built function
29. help()
To get details about any module, keyword, symbol, or topic, we use the help() function.
>>> help()
If this is your first time using Python, you should definitely check out the tutorial on the
Internet at http://docs.python.org/3.6/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing Python programs and
using Python modules. To quit this help utility and return to the interpreter, just type "quit".
help> map
Help on class map in module builtins:
class map(object)
| map(func, *iterables) --> map object
|
| Make an iterator that computes the function using arguments from
| each of the iterables. Stops when the shortest iterable is exhausted.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
help> You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)". Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.
>>>
30. hex()
Hex() Python built-in functions, converts an integer to hexadecimal.
>>> hex(16)
‘0x10’
>>> hex(False)
‘0x0’
>>> id({1,2,3})==id({1,3,2})
True
32. input()
Input() Python built-in functions, reads and returns a line of string.
>>> input("Enter a number")
Enter a number7
‘7’
Note that this returns the input as a string. If we want to take 7 as an integer, we need to apply
the int() function to it.
>>> int(input("Enter a number"))
Enter a number7
7
33. int()
int() converts a value to an integer.
>>> int('7')
7
34. isinstance()
We have seen this one in previous lessons. isinstance() takes a variable and a class as
arguments. Then, it returns True if the variable belongs to the class. Otherwise, it returns
False.
>>> isinstance(0,str)
False
>>> isinstance(orange,fruit)
True
35. issubclass()
This Python Built In function takes two arguments- two python classes. If the first class is a
subclass of the second, it returns True. Otherwise, it returns False.
>>> issubclass(fruit,fruit)
True
>>> class fruit:
pass
>>> class citrus(fruit):
pass
>>> issubclass(fruit,citrus)
False
36. iter()
Iter() Python built-in functions, returns a python iterator for an object.
>>> for i in iter([1,2,3]):
print(i)
1
2
3
37. len()
We’ve seen len() so many times by now. It returns the length of an object.
>>> len({1,2,2,3})
3
Here, we get 3 instead of 4, because the set takes the value ‘2’ only once.
38. list()
list() creates a list from a sequence of values.
>>> list({1,3,2,2})
[1, 2, 3]
39. locals()
This function returns a dictionary of the current local symbol table.
>>> locals()
{‘__name__’: ‘__main__’, ‘__doc__’: None, ‘__package__’: None, ‘__loader__’: <class
‘_frozen_importlib.BuiltinImporter’>, ‘__spec__’: None, ‘__annotations__’: {},
‘__builtins__’: <module ‘builtins’ (built-in)>, ‘fruit’: <class ‘__main__.fruit’>, ‘orange’:
<__main__.fruit object at 0x05F937D0>, ‘a’: 2, ‘numbers’: [1, 2, 3], ‘i’: 3, ‘x’: 7, ‘b’: 3,
‘citrus’: <class ‘__main__.citrus’>}
40. map()
Like filter(), map() Python built-in functions, takes a function and applies it on an iterable. It
maps True or False values on each item in the iterable.
>>> list(map(lambda x:x%2==0,[1,2,3,4,5]))
[False, True, False, True, False]
41. max()
A no-brainer, max() returns the item, in a sequence, with the highest value of all.
>>> max(2,3,4)
4
>>> max([3,5,4])
5
>>> max('hello','Hello')
‘hello’
42. memoryview()
memoryview() shows us the memory view of an argument.
>>> a=bytes(4)
>>> memoryview(a)
<memory at 0x05F9A988>
>>> for i in memoryview(a):
print(i)
43. min()
min() returns the lowest value in a sequence.
>>> min(3,5,1)
1
>>> min(True,False)
False
44. next()
This Python Built In function returns the next element from the iterator.
>>> myIterator=iter([1,2,3,4,5])
>>> next(myIterator)
1
>>> next(myIterator)
2
>>> next(myIterator)
3
>>> next(myIterator)
4
>>> next(myIterator)
5
Now that we’ve traversed all items, when we call next(), it raises StopIteration.
>>> next(myIterator)
Traceback (most recent call last):
File “<pyshell#392>”, line 1, in <module>
next(myIterator)
StopIteration
45. object()
Object() Python built-in functions, creates a featureless object.
>>> o=object()
>>> type(o)
<class ‘object’>
>>> dir(o)
[‘__class__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’,
‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’,
‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’,
‘__sizeof__’, ‘__str__’, ‘__subclasshook__’] Here, the function type() tells us that it’s an
object. dir() tells us the object’s attributes. But since this does not have the __dict__ attribute,
we can’t assign to arbitrary attributes.
46. oct()
oct() converts an integer to its octal representation.
>>> oct(7)
‘0o7’
>>> oct(8)
‘0o10’
>>> oct(True)
‘0o1’
47. open()
open() lets us open a file. Let’s change the current working directory to Desktop.
>>> import os
>>> os.chdir('C:\\Users\\lifei\\Desktop')
Now, we open the file ‘topics.txt’.
>>> f=open('topics.txt')
>>> f
<_io.TextIOWrapper name=’topics.txt’ mode=’r’ encoding=’cp1252′>
>>> type(f)
<class ‘_io.TextIOWrapper’>
To read from the file, we use the read() method.
>>> print(f.read())
DBMS mappings
projection
union
rdbms vs dbms
doget dopost
how to add maps
OOT
SQL queries
Join
Pattern programs
Output
Default constructor in inheritance
48. ord()
The function ord() returns an integer that represents the Unicode point for a given Unicode
character.
>>> ord('A')
65
>>> ord('9')
57
This is complementary to chr().
>>> chr(65)
‘A’
49. pow()
pow() takes two arguments- say, x and y. It then returns the value of x to the power of y.
>>> pow(3,4)
81
>>> pow(7,0)
1
>>> pow(7,-1)
0.14285714285714285
>>> pow(7,-2)
0.02040816326530612
50. print()
We don’t think we need to explain this anymore. We’ve been seeing this function since the
beginning of this article.
>>> print("Okay, next function, please!")
Okay, next function, please!
51. property()
The function property() returns a property attribute. Alternatively, we can use the syntactic
sugar @property. We will learn this in detail in our tutorial on Python Property.
52. range()
We’ve taken a whole tutorial on this. Read up range() in Python.
53. repr()
repr() returns a representable string of an object.
>>> repr("Hello")
“‘Hello'”
>>> repr(7)
‘7’
>>> repr(False)
‘False’
54. reversed()
This functions reverses the contents of an iterable and returns an iterator object.
>>> a=reversed([3,2,1])
>>> a
<list_reverseiterator object at 0x02E1A230>
>>> for i in a:
print(i)
1
2
3
>>> type(a)
<class ‘list_reverseiterator’>
55. round()
round() rounds off a float to the given number of digits (given by the second argument).
>>> round(3.777,2)
3.78
>>> round(3.7,3)
3.7
>>> round(3.7,-1)
0.0
>>> round(377.77,-1)
380.0
The rounding factor can be negative.
56. set()
Of course, set() returns a set of the items passed to it.
>>> set([2,2,3,1])
{1, 2, 3}
Remember, a set cannot have duplicate values, and isn’t indexed, but is ordered. Read
on Sets and Booleans for the same.
57. setattr()
Like getattr(), setattr() sets an attribute’s value for an object.
>>> orange.size
7
>>> orange.size=8
>>> orange.size
8
58. slice()
slice() returns a slice object that represents the set of indices specified by range(start, stop,
step).
>>> slice(2,7,2)
slice(2, 7, 2)
We can use this to iterate on an iterable like a string in python.
>>> 'Python'[slice(1,5,2)]
‘yh’
59. sorted()
Like we’ve seen before, sorted() prints out a sorted version of an iterable. It does not,
however, alter the iterable.
>>> sorted('Python')
[‘P’, ‘h’, ‘n’, ‘o’, ‘t’, ‘y’]
>>> sorted([1,3,2])
[1, 2, 3]
60. staticmethod()
staticmethod() creates a static method from a function. A static method is bound to a class
rather than to an object. But it can be called on the class or on an object.
>>> class fruit:
def sayhi():
print("Hi")
>>> fruit.sayhi=staticmethod(fruit.sayhi)
>>> fruit.sayhi()
Hi
You can also use the syntactic sugar @staticmethod for this.
>>> class fruit:
@staticmethod
def sayhi():
print("Hi")
>>> fruit.sayhi()
Hi
61. str()
str() takes an argument and returns the string equivalent of it.
>>> str('Hello')
‘Hello’
>>> str(7)
‘7’
>>> str(8.7)
‘8.7’
>>> str(False)
‘False’
>>> str([1,2,3])
‘[1, 2, 3]’
62. sum()
The function sum() takes an iterable as an argument, and returns the sum of all values.
>>> sum([3,4,5],3)
15
63. super()
super() returns a proxy object to let you refer to the parent class.
>>> class person:
def __init__(self):
print("A person")
>>> class student(person):
def __init__(self):
super().__init__()
print("A student")
>>> Avery=student()
A person
A student
64. tuple()
As we’ve seen in our tutorial on Python Tuples, the function tuple() lets us create a tuple.
>>> tuple([1,3,2])
(1, 3, 2)
>>> tuple({1:'a',2:'b'})
(1, 2)
65. type()
We have been seeing the type() function to check the type of object we’re dealing with.
>>> type({})
<class ‘dict’>
>>> type(set())
<class ‘set’>
>>> type(())
<class ‘tuple’>
>>> type((1))
<class ‘int’>
>>> type((1,))
<class ‘tuple’>
66. vars()
vars() function returns the __dict__ attribute of a class.
>>> vars(fruit)
mappingproxy({‘__module__’: ‘__main__’, ‘size’: 7, ‘shape’: ’round’, ‘__dict__’: <attribute
‘__dict__’ of ‘fruit’ objects>, ‘__weakref__’: <attribute ‘__weakref__’ of ‘fruit’ objects>,
‘__doc__’: None})
67. zip()
zip() returns us an iterator of tuples.
>>> set(zip([1,2,3],['a','b','c']))