0% found this document useful (0 votes)
2 views24 pages

python unit-1

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 24

Python Programming

UNIT-1
Introduction: Python is a widely used high-level programming language for general-purpose
programming, created by Guido van Rossum and first released in 1991. Python features a
dynamic type system and automatic memory management and supports multiple programming
paradigms, including object-oriented, imperative, functional programming, and procedural
styles. It has a large and comprehensive standard library.
There are two major Python versions- Python 2 and Python 3.
➢ On 16 October 2000, Python 2.0 was released with many new features.
➢ On 3rd December 2008, Python 3.0 was released with more testing and includes new
features
Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
Python is a Beginner's Language − Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple text
processing to WWW browsers to games.

1.1. History of Python.


✓ Python laid its foundation in the late 1980s.
✓ The implementation of Python was started in December 1989 by Guido Van Rossum at
CWI in Netherland.
✓ In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
alt.sources.
✓ In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
✓ Python 2.0 added new features such as list comprehensions, garbage collection systems.
✓ On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify the fundamental flaw of the language.
✓ ABC programming language is said to be the predecessor of Python language, which was
capable of Exception Handling and interfacing with the Amoeba Operating System.
1.2. List Python features.
SNO FEATURE DESCRIPTION
1 Simple Python is a simple and minimalistic language.

2 Easy to learn Python has a very simple syntax, meaning learners can very
quickly learn and start writing code.
3 Free and open Most Linux operating systems have Python by default. The
source standard modules and the Python interpreter are free.
Page |1 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram
Python Programming

4 High level When you write programs in Python, you never need to bother
language about the low-level details such as managing the memory used by
your program, etc.
5 portable Python programs can execute on any platform like Windows,
Linux, etc., without requiring any changes at all.
6 interpreted Python converts the source code into an intermediate form
called byte code
7 Object oriented Python supports procedure-oriented programming as well as
object-oriented programming.
8 Extensible If one needs a critical piece of code to run very fast or want to have
some piece of algorithm, you can code that part of your program
in C or C++ and then use/execute it from inside a Python program.
9 Embeddable One can embed Python within a C or C++ program.
10 Extensive The Python Standard Library is very exhaustive libraries for
libraries regular expressions, documentation generation, unit testing,
threading, databases, web browsers, CGI, FTP, email,
XML(Extensible Markup Language), XML-RPC, HTML, WAV
files, cryptography, GUI (graphical user interfaces), and other OS
related operations.

1.3. Explain Applications of Python.


Python supports cross-platform operating systems which makes building applications with it all
the more convenient. Some of the globally known applications such as YouTube, BitTorrent,
DropBox, etc
1. Web Development
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. One of Python web-framework named Django
2. Game Development
Python comes loaded with many useful extensions (libraries) that come in handy for the
development of interactive games. For instance, libraries like PySoy (a 3D game engine
that supports Python 3) and PyGame are two Python-based libraries used widely for
game development.
3. Machine Learning and Artificial Intelligence and Data Science and Data Visualization
AI and ML applications. Some of the best Python packages for AI and ML are:
• SciPy for advanced computing
• Pandas for general-purpose data analysis
• Seaborn for data visualization
• Keras, TensorFlow, and Scikit-learn for ML
• NumPy for high-performance scientific computing and data analysis

Page |2 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram


Python Programming
4. Desktop GUI
Python offers many GUI toolkits and frameworks that make desktop application
development a breeze. PyQt, PyGtk, Kivy, Tkinter, WxPython, PyGUI, and PySide are
some of the best Python-based GUI frameworks that allow developers to create highly
functional Graphical User Interfaces (GUIs).
5. Web Scraping Applications
Python is a nifty tool for extracting voluminous amounts of data from websites and web
pages. The pulled data is generally used in different real-world processes, including job
listings, price comparison, R&D, etc.
6. Business Applications
Enterprise-level software or business applications are strikingly different from standard
applications, as in the former demands features like readability, extensibility, and
scalability. Essentially, business applications are designed to fit the requirements of an
organization rather than the needs of individual customers.
7. Audio and Video Applications
Python is flexible to perform multiple tasks and can be used to create multimedia
applications. Some multimedia applications which are made by using Python
are TimPlayer, cplay, etc
8. CAD Applications
The CAD (Computer-aided design) is used to design engineering related architecture. It is
used to develop the 3D representation of a part of a system. Python can create a 3D CAD
application

1.4. Describe Python Integrated Development and Learning Environment (IDLE)


IDLE (Integrated Development and Learning Environment) is an integrated development
environment (IDE) for Python. The Python installer for Windows contains the IDLE module
by default
IDLE can be used to execute a single statement just like Python Shell and also to create,
modify, and execute Python scripts. IDLE provides a fully-featured text editor to create
Python script that includes features like syntax highlighting, autocompletion, and smart
indent.

To start an IDLE interactive shell, search for the IDLE icon in the start menu and double
click on it.

Page |3 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram


Python Programming
This will open IDLE, where you can write and execute the Python scripts, as shown below.

You can execute Python statements same as in Python Shell as shown below.

To execute a Python script, create a new file by selecting File -> New File from the menu.

Enter multiple statements and save the file with extension .py using File -> Save. For
example, save the following code as hello.py.

Page |4 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram


Python Programming
Now, press F5 to run the script in the editor window. The IDLE shell will show the output.

Thus, it is easy to write, test and run Python scripts in IDLE.


Another method
Python Interpreter: Shell/REPL
Python is an interpreter language. It means it executes the code line by line. Python
provides a Python Shell, which is used to execute a single Python command and display
the result.
It is also known as REPL (Read, Evaluate, Print, Loop), where it reads the command,
evaluates the command, prints the result, and loop it back to read the command again.
To run the Python Shell, open the command prompt or power shell on Windows and
terminal window on mac, write python and press enter. A Python Prompt comprising of
three greater-than symbols >>> appears, as shown below.

Now, you can enter a single statement and get the result. For example, enter a simple
expression like 3 + 2, press enter and it will display the result in the next line, as shown
below.

Page |5 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram


Python Programming

1.5. Give the process of Running Python Scripts.


Execute Python Script
As you have seen above, Python Shell executes a single statement. To execute multiple
statements, create a Python file with extension .py, and write Python scripts (multiple
statements).
For example, enter the following statement in a text editor such as Notepad.
print('welcome to python')
print("this is kumar")
Save it as samp.py, navigate the command prompt to the folder where you have saved
this file and execute the python samp.py command, as shown below. It will display the
result.

1.6. Explain Identifiers, Keywords, Indentation, Variables


Identifier
Any name is called as identifier. This names include variables name, functions name, class
name, object name, package name and module name , etc.

Like other programming knowledge, python also has same rules of giving identifier to an
entity: such as,
✓ They start with letter A-Z or a-z or underscore [ _ ]. Internally, they can have digits
but not to start with.
✓ Their length is not Limited. But referred to be meaningful.
✓ They should not contain whitespaces.
✓ They are case sensitive. That is 'num' and 'NUM' are different.
✓ They should not be keywords.(it will show error, saying "Syntax error: Invalid
syntax") .
Some example of valid and invalid identifiers :
num #valid
wordCount #valid
account_number #valid
x_co-ordinate #valid
_4 #valid, but meaningless
ErrorNumber4 #valid
Plot#3 #invalid because of special symbol #
account number #invalid because of space
255 #invalid because starts with digit
empno. #invalid because of special symbol .

Page |6 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram


Python Programming
and #invalid because and is a keyboard
Python keywords
Keywords are the words whose meaning are already known to the compiler and also called
as reserved words.
Python has total 35 keywords.

break continue False class await


elif else del def None
from for finally True except
and global if in import
lambda nonlocal is not as
raise return or assert pass
while with yield try async

Python Indentation
Indentation refers to the spaces at the beginning of a code line. Where in other programming
languages the indentation in code is for readability only, the indentation in Python is very
important. Python uses indentation to indicate a block of code.
Most of the previous programming languages uses pair of curly braces { } to define a logical
block. But Python uses indentation.
A logical block of code (such as, body of a function, loop, class, etc.) starts with indentation
and ends with the first unindented line.

Variable
Every variable in Python is an object. A Python variable is a reserved memory location
to store values. Every value in Python has a data type. Different data type
in Python are Numbers, List, Tuple, Strings, Dictionary, etc.
Therefore, by assigning different data type values to variables, users can store integers,
floating point numbers, or characters in these variables.
Assigning Different Values to Variables
➢ Binding a variable in Python means setting a name to a variable to hold a reference to
some object.
➢ In Python, assignment creates references, not copies.
➢ Variable names in Python do not have any data type but objects have types.
Page |7 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram
Python Programming
➢ Python determines the type of the data automatically based on what data is assigned to it.
➢ Python uses reference semantics.
a = 50
b=a

The variable b refers to the same object that a points to because Python does not create
another object.
Let's assign the new value to b. Now both variables will refer to the different objects.
a = 50
b =100

Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement, which is also
known as multiple assignments.
x=y=z=50
print(x)
print(y)
print(z)
You can also assign multiple objects to multiple variables. For example −
a,b,c=10,20.34,’kumar’
1.7. Explain various datatypes (Int, float, Boolean, string, and list)
Python Data Types
A Data Type describes the characteristic of a variable.
Python has six standard Data Types:
1. Numbers/Numeric
2. String
3. Boolean
4. List
5. Tuple
6. Set
7. Dictionary

Page |8 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram


Python Programming

1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has
no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.
Example:
a=5
print("The type of a", type(a))
b = 40.5
print("The type of b", type(b))
c = 1+3j
print("The type of c", type(c))
output:
The type of a <class 'int'>
The type of b <class 'float'>
The type of c <class 'complex'>
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.
str = "string using double quotes"
print(str)
s = '''''A multiline
string'''
print(s)
Output:
string using double quotes
A multiline
string
Accessing characters in Python String
In Python, individual characters of a String can be accessed by using the method of Indexing.
Page |9 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram
Python Programming
Indexing allows negative address references to access characters from the back of the String, e.g.
-1 refers to the last character, -2 refers to the second last character, and so on.
Index 0 1 2 3 4
Data K U M A R
Negative Index -5 -4 -3 -2 -1
str='satya kumar'
print('original string:: ' + str)
print('1st Character of String:: '+ str[0])
print('last character of string:: '+str[-1])
Boolean
Boolean type provides two built-in values, True and False. These values are used to determine
the given statement true or false. It denotes by the class bool. True can be represented by any
non-zero value or 'T' whereas false can be represented by the 0 or 'F'.
Example:
a = True
b = False
print (a)
print (b)
Output:
True
False
Python Lists
Lists are the most versatile of Python's compound data types. A list contains items separated by
commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C.
One difference between them is that all the items belonging to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the
list concatenation operator, and the asterisk (*) is the repetition operator.
Example Program:
list = [ 'bvcits', 786 , 2.23, 'kumar', 70.2 ]
list1 = [123, 'satya']
print(list) # Prints complete list
print(list[0]) # Prints first element of the list
print(list[1:3]) # Prints elements starting from 2nd till 3rd
print(list[2:]) # Prints elements starting from 3rd element
print(list1 * 2) # Prints list two times
print(list + list1) # Prints concatenated lists
Output:
['bvcits', 786, 2.23, 'kumar', 70.2]
bvcits
[786, 2.23]
[2.23, 'kumar', 70.2]
[123, 'satya', 123, 'satya']
['bvcits', 786, 2.23, 'kumar', 70.2, 123, 'satya']
P a g e | 10 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram
Python Programming
1.8. Explain declaration, initialization of variables.
In Python, we need not declare a variable with some specific data type.
Python has no command for declaring a variable. A variable is created when some value is
assigned to it. The value assigned to a variable determines the data type of that variable.
Thus, declaring a variable in Python is very simple.
✓ Just name the variable
✓ Assign the required value to it
✓ The data type of the variable will be automatically determined from the
value assigned, we need not define it explicitly.
Example:
x=2
print(x)
print(type(x))
x=2.0
print(x)
print(type(x))
x='2'
print(x)
print(type(x))
1.9. Explain Input and Output statements.
Python Output using print() function
The simplest way to produce output is using the print() function where you can pass zero or
more expressions separated by commas. This function converts the expressions you pass
into a string before writing to the screen.
Syntax: print(value(s), sep= ‘ ‘, end = ‘\n’, file=sys.stdout, flush=False)
Parameters:
value(s) : Any value, and as many as you like. Will be converted to string before printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than
one.Default :’ ‘
end=’end’: (Optional) Specify what to print at the end. Default : ‘\n’
file : (Optional) An object with a write method. Default : sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False
Returns: It returns output to the screen.
Example:
print(“Satya kumar")

x=5
# Two objects are passed
print("x =", x)

# code for disabling the softspace feature


print('G', 'F', 'G', sep ='')

# using end argument


print("Python", end = '@')
P a g e | 11 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram
Python Programming
print("Satya kumar")
Python input() Function
Example
Ask for the user's name and print it:
print('Enter your name:')
x = input()
print('Hello, ' + x)
Example
Use the prompt parameter to write a message before the input:
X = input('Enter your name:')
print('Hello, ' + x)
1.10. Explain formatted input output.
Python provides us with an alternative called formatted strings. A formatted string is a template
in which words or spaces that will remain constant are combined with placeholders for variables
that will be inserted into the string.
Character Output Format
d, i Integer
u Unsigned integer
f Floating point as m.ddddd
e Floating point as m.ddddde+/-xx
E Floating point as m.dddddE+/-xx
g Use %e for exponents less than −4−4 or greater than +5+5, otherwise use %f
c Single character
s String, or any Python data object that can be converted to a string by using
the str function.
% Insert a literal % character

Modifier Example Description


number %20d Put the value in a field width of 20
- %-20d Put the value in a field 20 characters wide, left-justified
+ %+20d Put the value in a field 20 characters wide, right-justified
0 %020d Put the value in a field 20 characters wide, fill in with leading
zeros.
. %20.2f Put the value in a field 20 characters wide with 2 characters to
the right of the decimal point.
(name) %(name)d Get the value from the supplied dictionary using name as the
key.
P a g e | 12 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram
Python Programming

print("Total students : % 3d, Boys : % 2d" %(240, 120))


print("Geeks : %2d, Portal : %5.2f" % (1, 05.333))
print('%20s %20s'%('satya','kumar’))

Taking multiple inputs from user in Python


Using split() method :
This function helps in getting multiple inputs from users. It breaks the given input by the
specified separator. If a separator is not provided then any white space is a separator. Generally,
users use a split() method to split a Python string but one can use it in taking multiple inputs.
Syntax:
input().split(separator, maxsplit)
x, y = input("Enter two values: ").split()
x, y, z = input("Enter three values: ").split(‘,’)

Python String format() Method


The format() method formats the specified value(s) and insert them inside the string's
placeholder.
The placeholder is defined using curly brackets: {}. Read more about the placeholders in the
Placeholder section below.
The format() method returns the formatted string.
Syntax
string.format(value1, value2...)

txt2="My name is {0}, I'm {1}".format('Kumar',36)


print(txt2)

The Placeholders
The placeholders can be identified using named indexes {price}, numbered indexes {0}, or even
empty placeholders {}.
txt1 = "My name is {fname}, I'm {age}".format(age = 36, fname = "Satya",sal=40000)
print(txt1)

Formatting Types
Inside the placeholders you can add a formatting type to format the result:
:< Left aligns the result (within the available space)
:> Right aligns the result (within the available space)
:^ Center aligns the result (within the available space)
:= Places the sign to the left most position
:, Use a comma as a thousand separator
#Use "<" to left-align the value:

txt = "My Name is {:>20} Hai."


print(txt.format('kumar'))
P a g e | 13 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram
Python Programming
#Use "^" to center-align the value:

txt = "My Name is {:^20} Hai."


print(txt.format('kumar'))

#Use ">" to right-align the value:

txt = "My Name is {:>20} Hai."


print(txt.format('kumar'))

1.11. State the usage of comments


Comments in Python are the lines in the code that are ignored by the interpreter during
the execution of the program. Comments enhance the readability of the code and help the
programmers to understand the code very carefully. There are three types of comments in Python
✓ Single line Comments
✓ Multiline Comments
✓ Docstring Comments
Single-Line Comments in Python
In Python, we use the hash symbol # to write a single-line comment.
Example:
# printing a string
print('Hello world')
Multi-Line Comments in Python
Python doesn't offer a separate way to write multiline comments. However, there are other ways
to get around this issue.
We can use # at the beginning of each line of comment on multiple lines.
Using multiple #
# it is a
# multiline
# comment
String Literals for Multi-line Comments
Even though there is no unique way to write multiline comments in Python, we know that the
Python interpreter ignores the string literals that are not assigned to a variable.
So, we can even write a single-line comment as:
#this is a comment
'this is an unassigned string as a comment '
In a similar way, we can use multiline strings (triple quotes) to write multiline comments.
The quotation character can either be ' or ".
Using String Literals to write Multi-line Comments
'''
I am a
multiline comment!
'''
print("Hello World")

P a g e | 14 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram


Python Programming
Python docstrings
By convention, the triple quotes that appear right after the function, method or class definition
are docstrings (documentation strings).
Docstrings are associated with objects and can be accessed using the __doc__ attribute.
def multiply():
"""Multiplies function comment line document """
# Print the docstring of multiply function
print(multiply.__doc__)

1.12. Explain various Operators.


The operator can be defined as a symbol which is responsible for a particular operation between
two operands. Operators are the pillars of a program on which the logic is built in a specific
programming language.
Python language supports the following types of operators.
 Arithmetic Operators
 Comparison/Relational Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
 Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, etc.
Assume variable a holds 10 and variable b holds 20, then

P a g e | 15 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram


Python Programming
 Comparison/Relational Operators
These operators compare the values on either sides of them and decide the relation among
them. They are also called Relational operators.

 Assignment Operators
Assignment operators are used in Python to assign values to variables

P a g e | 16 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram


Python Programming

 Logical Operators
Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are true x < 5 and x < 10

or Returns True if one of the statements is true x < 5 or x < 4

not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

 Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and
b = 13;

 Membership Operators
Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples.

P a g e | 17 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram


Python Programming

a = 10
b = 20
list = [1, 2, 3, 4, 5 ]

if ( a in list ):
print ("Line 1 - a is available in the given list")
else:
print ("Line 1 - a is not available in the given list")

if ( b not in list ):
print ("Line 2 - b is not available in the given list")
else:
print ("Line 2 - b is available in the given list")

a=2
if ( a in list ):
print ("Line 3 - a is available in the given list")
else:
print ("Line 3 - a is not available in the given list")
Output:
Line 1 - a is not available in the given list
Line 2 - b is not available in the given list
Line 3 - a is available in the given list
 Identity Operators
Identity operators compare the memory locations of two objects.

P a g e | 18 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram


Python Programming
x = "banana"
y = "apple"
z=x

print(x is z)

print(x is y)

print(x == y)
Output:
True
False
False
Example :
a=10
b=10
if (a is b):
print(True)
else:
print(False)
c=a
print(id(a),id(b),id(c))
a=30
print(id(a))
if (a is c):
print(True)
else:
print(False)
Output:
True
10914784 10914784 10914784 10915424
False

P a g e | 19 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram


Python Programming

1.13. Explain Boolean values.


Booleans are identified by True or False.
Boolean expression
Boolean expression is an expression that evaluates to a Boolean value. It almost always
involves a comparison operator.
Syntax: bool([x])
Returns True if X evaluates to true else false.
Without parameters it returns false.
x=5
y = 10
print(bool(x==y))
x = 0.0
print(bool(x))
x = ‘kumar'
print(bool(x))
Boolean Operators
Boolean Operations are simple arithmetic of True and False values. These values can be
manipulated by the use of boolean operators which include AND, Or, and NOT.
Common boolean operations are –
or
and
not
== (equivalent)
!= (not equivalent)

1.14. Explain Operator precedence rules.


Operator Description
( ) Parenthesis
** Exponentiation (raise to the power)
~ x, +x, -x Complement, unary plus and minus
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *=
Assignment operators
**=
is is not Identity operators
in not in Membership operators
not or and Logical operators

P a g e | 20 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram


Python Programming

Associativity of Python Operators


We can see in the above table that more than one operator exists in the same group. These
operators have the same precedence.
When two operators have the same precedence, associativity helps to determine the order
of operations.
Associativity is the order in which an expression is evaluated that has multiple operators of
the same precedence. Almost all the operators have left-to-right associativity.
For example, multiplication and floor division have the same precedence. Hence, if both of
them are present in an expression, the left one is evaluated first.
Python Operators Precedence Rule – PEMDAS
You might have heard about the BODMAS rule in your school’s mathematics class.
Python also uses a similar type of rule known as PEMDAS.
P – Parentheses
E – Exponentiation
M – Multiplication
D – Division
A – Addition
S – Subtraction
The precedence of operators is listed from High to low.

1.15. State the purpose of modules.


Python Modules
A Python module is a file containing Python definitions and statements. A module can define
functions, classes, and variables. A module can also include runnable code. Grouping related
code into a module makes the code easier to understand and use. It also makes the code logically
organized.
# A simple module, calc.py
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)

# importing module calc.py


import calc
print(calc.add(10, 2))

P a g e | 21 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram


Python Programming
1.16. Define functions.
Python Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()

1.17. List types of functions.(Built-in, User defined)


Function
The idea is to put some commonly or repeatedly done tasks together and make a function so that
instead of writing the same code again and again for different inputs, we can do the function calls
to reuse code contained in it over and over again.
Function are two types
Built-in functions
User defined functions
Built-in functions are pre-defined in the programming language’s library, for the programming to
directly call the functions wherever required in the program for achieving certain functional
operations. A few of the frequently used built-in function in the Python programs are abs(x) for
fetching the absolute value of x, bin() for getting the binary value, bool() for retrieving the
boolean value of an object, list() for lists, len() to get the length of the value, open() to open the
files, pow() for returning the power of a number, sum() for fetching the sum of the elements,
reversed() for reversing the order, etc
Python User defined functions
A function is a set of statements that take inputs, do some specific computation and produce
output. The idea is to put some commonly or repeatedly done tasks together and make a function
P a g e | 22 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram
Python Programming
so that instead of writing the same code again and again for different inputs, we can call the
function.
User defined functions

➢ Parameterized functions
➢ Default arguments
➢ Keyword arguments
➢ Variable length arguments
➢ Pass by Reference or pass by value?
➢ Function with return value
1.18. Explain Built-in Functions.
print( ) function
The print() function prints the specified message to the screen or another standard output device.
type( ) function
The type() function returns the type of the specified object.
input( ) function
The input() function allows taking the input from the user.
abs( ) function
The abs() function returns the absolute value of the specified number.
pow( ) function
The pow() function returns the calculated value of x to the power of y i.e, xy.
If a third parameter is present in this function, then it returns x to the power of y, modulus z.
dir( ) function
The dir() function returns all the properties and methods of the specified object, without the
values.
This function even returns built-in properties which are the default for all objects.
sorted( ) function
The sorted() function returns a sorted list of the specified iterable object.
You can specify the order to be either ascending or descending. In this function, Strings are
sorted alphabetically, and numbers are sorted numerically.
reverse Optional. A Boolean. False will sort ascending, True will sort descending. Default is
False

P a g e | 23 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram


Python Programming
max( ) function
The max() function returns the item with the maximum value or the item with the maximum
value in an iterable.
round( ) function
The round() function returns a floating-point number that is a rounded version of the specified
number, with the specified number of decimals.

1.19. Give the Steps in Develop a simple python program and execution.
Give the Steps in Develop a simple python program and execution
After writing the code, we need to run the code to execute and obtain the output. On running the
program, we can check whether the code is written is correct and produces the desired output.
Running a python program is quite an easy task.
Run on IDLE
To run a python program on IDLE, follow the given steps −
• Write the python code and save it.
• To run the program, go to Run > Run Module or simply click F5.

Run on Command Line


The python script file is saved with ‘.py’ extension. After saving the python script, we can run it
from the Command Line. In the cmd, type keyword ‘python’ followed by the name of the file
with which you saved the python script.
Example
Let us suppose, we have a python script saved with the name ‘hello.py’. To run it on command
line, type the following −
python hello.py

P a g e | 24 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram

You might also like