Python Unit 1 Nots | PDF | Control Flow | Python (Programming Language)
0% found this document useful (0 votes)
597 views

Python Unit 1 Nots

The document is a syllabus for a Python Programming course from Anna University. It covers 5 units: 1) Basics of Python including variables, data types, conditionals, loops, functions, scope. 2) Data types in Python like lists, tuples, sets, strings, dictionaries, modules and packages. 3) File handling and exception handling in Python. 4) Using modules, packages and frameworks like NumPy, Pandas, Matplotlib in Python. 5) Object oriented programming concepts in Python like classes, inheritance, encapsulation and polymorphism. The course aims to develop Python programs using these fundamental concepts.

Uploaded by

mdsamadabdul28
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
597 views

Python Unit 1 Nots

The document is a syllabus for a Python Programming course from Anna University. It covers 5 units: 1) Basics of Python including variables, data types, conditionals, loops, functions, scope. 2) Data types in Python like lists, tuples, sets, strings, dictionaries, modules and packages. 3) File handling and exception handling in Python. 4) Using modules, packages and frameworks like NumPy, Pandas, Matplotlib in Python. 5) Object oriented programming concepts in Python like classes, inheritance, encapsulation and polymorphism. The course aims to develop Python programs using these fundamental concepts.

Uploaded by

mdsamadabdul28
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

lOMoARcPSD|34873126

Python Unit-1 nots

Master of Computer Applications (Anna University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by samad ahmed (mdsamadabdul28@gmail.com)
lOMoARcPSD|34873126

MC4103_Python Programming R-2021|Syllabus

ANNA UNIVERSITY SYLLABUS | R-2021


MC4103 PYTHON PROGRAMMING
LTPC
3003
OBJECTIVES:
• To develop Python programs with conditionals, loops and functions.
• To use Python data structures – lists, tuples, dictionaries.
• To do input/output with files in Python
• To use modules, packages and frameworks in python
• To define a class with attributes and methods in python
UNIT I BASICS OF PYTHON 9
Introduction to Python Programming – Python Interpreter and Interactive Mode– Variables
and Identifiers – Arithmetic Operators – Values and Types – Statements. Operators – Boolean Values
– Operator Precedence – Expression – Conditionals: If-Else Constructs – Loop Structures/Iterative
Statements – While Loop – For Loop – Break Statement-Continue statement – Function Call and
Returning Values – Parameter Passing – Local and Global Scope – Recursive Functions

UNIT II DATA TYPES IN PYTHON 9


Lists, Tuples, Sets, Strings, Dictionary, Modules: Module Loading and Execution – Packages –
Making Your Own Module – The Python Standard Libraries.

UNIT III FILE HANDLING AND EXCEPTION HANDLING 8


Files: Introduction – File Path – Opening and Closing Files – Reading and Writing Files –File
Position –Exception: Errors and Exceptions, Exception Handling, Multiple Exceptions

UNIT IV MODULES, PACKAGES AND FRAMEWORKS 10


Modules: Introduction – Module Loading and Execution – Packages – Making Your Own
Module – The Python Libraries for data processing, data mining and visualization- NUMPY, Pandas,
Matplotlib, Plotly-Frameworks- -Django, Flask, Web2Py

UNIT V OBJECT ORIENTED PROGRAMMING IN PYTHON 9


Creating a Class, Class methods, Class Inheritance, Encapsulation, Polymorphism, class
method vs. static methods, Python object persistence.
TOTAL: 45 PERIODS
OUTCOMES:
Upon completion of the course, students will be able to
Develop algorithmic solutions to simple computational problems
Represent compound data using Python lists, tuples and dictionaries.
Read and write data from/to files in Python Programs
Structure simple Python programs using libraries, modules etc.
Structure a program by bundling related properties and behaviours into individual objects.
REFERENCES:
1. ReemaThareja, “Python Programming using Problem Solving Approach”, Oxford University
Press, First edition, 2017

AVCCE/MCA/R-21/I-SEM/NS Page 1

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming R-2021|Syllabus

2. Allen B. Downey, “Think Python: How to Think Like a Computer Scientist”, Second Edition,
Shroff,O‘Reilly Publishers, 2016 (http://greenteapress.com/wp/thinkpython/)
3. Guido van Rossum, Fred L. Drake Jr., “An Introduction to Python – Revised and Updated
forPython 3.2, Network Theory Ltd., First edition, 2011
4. John V Guttag, “Introduction to Computation and Programming Using Python”,Revised
and Expanded Edition, MIT Press, 2013
5. Charles Dierbach, “Introduction to Computer Science using Python”, Wiley IndiaEdition,
First Edition, 2016
6. Timothy A. Budd, “Exploring Python”, Mc-Graw Hill Education (India) Private Ltd.,First
edition,2011
7. Kenneth A. Lambert, “Fundamentals of Python: First Programs”, Cengage Learning, second
edition,2012

Websites
1. https://www.learnpython.org/
2. https://www.codecademy.com/learn/learn-python
3. https://docs.python.org/3/tutorial/
4. https://runestone.academy/runestone/books/published/thinkcspy/index.html
5. https://nptel.ac.in/courses/106106182/
6. http://172.16.25.76/course/view.php?id=1225
7. https://www.educba.com/list-operations-in-python/
8. https://realpython.com/python-idle/
9. https://data-flair.training/blogs/python-interpreter/
10. https://techvidvan.com/tutorials/python-interpreter/

Online compiler

https://www.programiz.com/python-programming/online-compiler/
https://www.w3schools.com/python/python_compiler.asp

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

Unit- I | BASICS OF PYTHON


Introduction to Python Programming – Python Interpreter and Interactive Mode– Variables
and Identifiers – Arithmetic Operators – Values and Types – Statements. Operators – Boolean Values
– Operator Precedence – Expression – Conditionals: If-Else Constructs – Loop Structures/Iterative
Statements – While Loop – For Loop – Break Statement-Continue statement – Function Call and
Returning Values – Parameter Passing – Local and Global Scope – Recursive Functions.

1.1 Introduction to Python Programming

Python is a Second Most popular programming language in the world. It was created by
Guido van Rossum, and released in 1991. It is used for software development. It can be used
on a server to create web applications. It can connect to database systems. It can also read and
modify files. It is used to handle big data and perform complex mathematics. Python works
on different platforms(windows ,Linux, etc.,) It is similar to the English language and follows
simple syntax.

It is an interpreted language which means can be executed as soon as it is written. No


need to compile. Being an interpreted language, Python is slow as compared to C/C++. But
easy to execute the programme for beginners.

1.1.1 Features of Python

• Simple - Python’s syntax is very simple compared to other programming languages


like C,C++,java

AVCCE/MCA/R-21/I-SEM/NS Page 3

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

• Versatile - Used in many applications like robotics, machine learning. Even google
uses python programming.
• Free and Open Source - Can be downloaded at free of cost.
• High-level Language - Uses simple english and symbols
• Interactive - This interactive mode helps in displaying the output immediately as
soon as you enter the code.
• Object Oriented – Uses object oriented concepts like message passing,
inheritance,etc.,
• Interpreted - source code (line by line scaning) is translated to machine code by the
interpreter and can be directly executed. No need of pre compilation like C,C++.
• Easy to maintain
• Secure - Allow us to perform cryptographic techniques for security purpose.
• Multi-threaded - allow multiple threads to execute simultaneously.
• Garbage Collection -Performs automatic memory management.

1.1.2 Applications of Python

• Python is easy to pick-up even if you come from a non-programming background.


• Some of the cool things that you can do are.
– Build a website using Python
– Develop game programme in Python
– Perform Computer Vision (Facilities like face-detection and color-detection)
– Implement Machine Learning (Give a computer the ability to learn)
– Enable Robotics with Python
– Perform Web Scraping (Harvest data from websites)
– Perform Data Analysis using Python
– Automate a web browser
– Perform Scripting in Python
– Perform Scientific Computing using Python
– Build Artificial Intelligence

AVCCE/MCA/R-21/I-SEM/NS Page 4

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

1.1.3 Python Constructs – Some Basic Structure


• 1. Functions
– Functions are a group of statements given a name, so we can use them
whenever we want.
– We can call them in a program whenever and as many times as we want.
• 2. Classes and Objects
– Python is object-oriented, it can model the real world.
– The two most basic object-oriented concepts are classes and objects.
– A class is an abstract data type that acts as a blueprint for objects of its kind. It
holds no values itself.
– An object is an instance of a class and has properties and behavior.
• 3. Modules and Packages
– Modules are collections of related classes and functions.
– And packages are collections of related modules.
• 4. Data Structures

– Python has many different data structures like


• lists, tuples and dictionaries.
– List
• You can think of a list as a collection of values.
• Declared in the CSV (Comma-Separated Values) format and delimit
using square brackets:
– Tuple
• A tuple is like a list, but it is immutable (you cannot change its
values).
– Dictionary
• A dictionary is a collection of key-value pairs.
• Declare it using curly braces, and commas to separate key-value pairs.
• Also, separate values from keys using a colon (:).
• Comments and Docstrings
• Declare comments using an hash symbol (#). However, Python does
not support multiline comments.
• Docstrings are documentation strings that help explain the code.
• Python has a lot of other constructs.
– These include control structures, functions, exceptions, etc.

1.1.4 Implementations of Python

1. CPython - Written in C. Most widely accepted implementation of Python.


2. Jython - This is written in Java. Jython code can import any Java class and
compiles to Java bytecode.
3. IronPython - Written in C#. This can function as an extensibility layer to
application frameworks written in a .NET language.

AVCCE/MCA/R-21/I-SEM/NS Page 5

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

4. BRython - This is Browser Python; it runs in the browser.


5. RubyPython - This acts as a bridge between the Python and Ruby interpreters. It is
responsible for marshaling data between Python and Ruby virtual machines.
6. PyPy - This is an implementation of Python written in Python itself. This is faster
and easier to experiment with.
7. MicroPython - MicroPython is made to run on microcontrollers. It uses a
MicroPython board which runs MicroPython on bare metal.

1.1.5 Running Python


• Python ships with an in-built interpreter Integrated Development and Learning
Environment(IDLE),
• You can use an IDE too like PyCharm or the Jupyter Lab.
• Python files may have different extensions:
– .py – Python file
– .pyc – Compiled bytecode
– .pyd – Windows DLL file
– .pyo – File created with optimizations
– .pyw – Script for Windows
– .pyz – Script archive

1.1.6 Writing and Executing First Python Program


• Step 1: Open an editor.
• Step 2: Write the python program
• Step 3: Save it as a file with the filename having the extension program_name .py.
• Step 4: To execute the program at the command prompt, simply change your working
directory to C:\Python34
• Run as python program_name.py Or
Use IDLE to run the programs.

AVCCE/MCA/R-21/I-SEM/NS Page 6

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

1.2 Python Interpreter and Interactive Mode


Python interpreter can be used in two modes
1. Interactive mode
2. Script mode

Output:
Enter ur name SRINIVASAN
Your name is SRINIVASAN

AVCCE/MCA/R-21/I-SEM/NS Page 7

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

1.2.1 Python Interpreter

• Python doesn’t convert its code into machine code, It actually converts it into byte
code. So within python, compilation happens, but this byte code can’t be understood
by CPU. So we need actually an interpreter called the python virtual machine. The
python virtual machine executes the byte codes.

The Python interpreter performs following tasks to execute a Python program :


– Step 1 : The interpreter reads a python code or instruction. Then it verifies
that the instruction is well formatted, i.e. it checks the syntax of each line. If it
encounters any error, it immediately halts the translation and shows an error
message.
• Step 2 : If there is no error,
– i.e. if the python instruction or code is well formatted then the interpreter
translates it into its equivalent form in intermediate language called “Byte
code”. Thus, after successful execution of Python script or code, it is
completely translated into Byte code.
• Step 3 : Byte code is sent to the Python Virtual Machine(PVM).
– Here again the byte code is executed on PVM.
– If an error occurs during this execution then the execution is halted with an
error message.

1.3 Python Syntax

• The term syntax is referred to a set of rules and principles that describes the structure
of a language. The Python syntax defines all the set of rules that are used to create
sentences in Python programming.
• For example – we have to learn grammar when we want to learn the English
language.
• In the same way, you will need to learn and understand the Python syntax in order to
learn the Python language.

AVCCE/MCA/R-21/I-SEM/NS Page 8

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

1.3.1 Types of Syntax Structures in Python

1.3.1.1 Python Line Structure


• A Python program comprises logical lines. A NEWLINE token follows each of
those. The interpreter ignores blank lines.
• The following line causes an error.
– >>> print("Hi
– How are you?")
• Output:
– SyntaxError: EOL while scanning string literal

Python Multiline Statements


• This one is an important Python syntax. We saw that Python does not mandate
semicolons. A new line means a new statement. But sometimes, you may want to split
a statement over two or more lines. It may be to aid readability. You can do so in the
following ways.
– A.Use a backward slash
• >>> print("Hi\
• how are you?")
– Output:
• Hi how are you?
– B. Put the String in Triple Quotes
• >>> print("""Hi
• how are you?""")
– Output:
• Hi
how are you?
Multiple Statements in One Line
• Python also allows you to write multiple statements in a single line.
• For this purpose, we use semicolons to separate statements within the same line.
• This can reduce the readability of code so only use this if it is appropriate in the
situation.
• Code:
– >>>num1 = 10 ; num2 = 20 ; print(“Sum of numbers = ”, num1+num2)
• Output:
Sum of numbers = 30

AVCCE/MCA/R-21/I-SEM/NS Page 9

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

1.3.1.2 Python Docstrings


• A docstring is a documentation string.
– As a comment, this Python Syntax is used to explain code.
• But unlike comments, they are more specific.
– Also, they are retained at runtime.
• This way, the programmer can inspect them at runtime. Delimit a docstring using
three double-quotes. You may put it as a function’s first line to describe it.
– >>> def func():
"""
This function prints out a greeting
"""
print("Hi")
>>> func()
• Output:
Hi
1.3.1.3 Python Indentation

• Since Python doesn’t use curly braces to delimit blocks of code, this Python Syntax is
mandatory. You can indent code under a function, loop, or class.
– >>> if a>b:
print(“a is greater than b");

– Output:
• a is greater than b
1.3.1.4 Python Quotations
• Python supports the single quote and the double quote for string literals. But if you
begin a string with a single quote, you must end it with a single quote. The same goes
for double-quotes. The following string is delimited by single quotes.
– >>> print('Welcome to AVCCE’)
• Output:
– 'Welcome to AVCCE
– This string is delimited by double-quotes.
– >>> print(" Welcome to ‘AVCCE’ ");
• Output:
– Welcome to ‘AVCCE’
1.3.1.5 Python Blank Lines

• If you leave a line with just whitespace, the interpreter will ignore it.

1.3.1.6 Constants, Variables, Identifiers and Datatypes


• Characterset – Used to represent information.
• Two types
– Source characterset
– Execution characterset

AVCCE/MCA/R-21/I-SEM/NS Page 10

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

• Source Character Set


– Alphabets ( A – Z, a-z)
– Digits ( 0 - 9 )
– Special characters (.,/,@,&,*,# …)
– White spaces ( space bar)
• Execution Character Set(Escape Sequences )
• Some characters (like ", \) cannot be directly included in a string. Such characters
must be escaped by placing a backslash before them.

1.3.1.7 Variables

Variable means its value can vary. You can store any piece of information in a
variable. Variables are nothing but just parts of your computer’s memory where information
is stored. To be identified easily, each variable is given an appropriate name.
1. Identifiers are names given variable, function, class, module or other object.
2. Rules for naming Identifier
 Special characters are not allowed within identifier
 Identifier names are case sensitive, so creation and usage of identifier needs to be
taken care.For example, myvar and myVar are not the same.
 Use underscores( ‘_’) to separate multiple words in identifiers.
 It should not begin with a number.
 Punctuation characters such as @, $, and % are not allowed within identifiers.

1.3.17.1 Assigning or Initializing Values to Variables

Variables need not be explicitly declared, The


declaration is done automatically, when a value is
assigned to the variable using the equal sign (=). The
operand on the left side of equal sign is the name of
the variable and the operand on its right side is the
value to be stored in that variable. For eg: a=10
[where, a is operand/variable and 10 is the value
assigned to variable ]

AVCCE/MCA/R-21/I-SEM/NS Page 11

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

1.3.1.8 Literal Constants

The value of a literal constant can be used directly in programs. For example, 7, 3.9,
'A', and "Hello" are literal constants. Numbers are referred to as numeric value. Python
supports four types of numbers - integers, long integers, floating point and complex
numbers.
• Numbers like 5 or other whole numbers are referred to as integers.
• Bigger whole numbers are called long integers. For example, 535633629843L is a
long integer.
• Numbers like are 3.23 are termed as floating point numbers.
• Numbers like 3 + 7i are complex numbers.
Example:

1.3.1.8.1 Strings
• A string is a group of characters.
• Using Single Quotes ('):
– A string can be written as 'HELLO'.
• Using Double Quotes ("):
– A string can also be written in double quotes. Therefore, 'HELLO' is same as
"HELLO".
• Using Triple Quotes (''' '''):
– Multi-line strings can be written using triple quotes.
‘’’ hai hello
This is India’’’
1.3.1.9 Python Identifiers
An identifier is a name of a program element, and it is user-defined. This Python
Syntax uniquely identifies the element. There are some rules to follow while choosing an
identifier:
– An identifier may only begin with A-Z, a-z, or an underscore(_).
– This may be followed by letters, digits, and underscores- zero or more.
– Python is case-sensitive. Name and name are two different identifiers.
– A reserved keyword may not be used as an identifier.
– The following is a list of keywords.

1.3.1.9 .1 Reserved Keyword

and def False import not True


as del finally in or try
assert elif for is pass while
break else from lambda print with
class except global None raise yield
continue exec if nonlocal return

AVCCE/MCA/R-21/I-SEM/NS Page 12

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

Apart from these rules, there are a few naming conventions that you should follow
while using this Python syntax:
• Use uppercase initials for class names,
– lowercase for all others.
• Name a private identifier with a leading underscore ( _username)
• Name a strongly private identifier with two leading underscores ( __password)
• Special identifiers by Python end with two leading underscores.

Examples of Valid Identifiers:


 name
 _3name6
 get_all_names
 YES
Examples of Invalid Identifiers:
 1name
 name$
 get-score

1.4 Operators

It is a symbol that specifies an operation to be performed on the operands.


Types:
1. Arithmetic 5. Bitwise
2. Relational 6. Membership
3. Logical 7. Identity
4. Assignment 8. Boolean
1.4.1 Arithmetic Operator

Used to perform addition(+), subtraction(-), multiplication(*), division(/), modulo(%)


and floor(//) operation.

Arithmetic Operation

AVCCE/MCA/R-21/I-SEM/NS Page 13

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

Another Example
a=5 Output
b=2 7
print(a+b) 3
print(a-b) 10
print(a*b) 2.5
print(a/b) 1
print(a%b) 2
print(a//b)

1.4.2 Relational Operator

Used to compare two or more operands.


 Example: Compare age of 2 persons.

Operators:
Operator Description Example

== Two operands are equal (x==y)

!= Two operands are not (x!=y)


equal

> Left operand is grater (x>y)

< Left operand is lesser (x<y)

>= Greater than or equal to (x>=y)

<= Less than or equal to (x<=y)

AVCCE/MCA/R-21/I-SEM/NS Page 14

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

1.4.3 Logical Operator

Operator Description Example

Logical AND Both condition is true (x and y)

Logical OR Any one condition is true (x or y)

Logical Not Reverse of the condition is true Not(x)

1.4.4 Bitwise Operator


Used to manipulate data at bit level. It operates on integer (Binary) only.
OPERATOR SYNTAX DESCRIPTION

& x&y Bitwise AND

| x|y Bitwise OR

~ ~x, ~ y Bitwise NOT

^ x^y Bitwise XOR

<< x<<, y<< Bitwise left shift

>> x>>, y>> Bitwise right shift

AVCCE/MCA/R-21/I-SEM/NS Page 15

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

Bitwise AND operator:


If both bits are 1, it returns 1 else it returns 0.

Bitwise OR operator:
If any one of the bit is 1, it returns 1 else it returns 0.

Bitwise NOT operator:


One’s complement of the number is returned.

Bitwise XOR operator:


If one of the bit is 1 and the other is given as 0 it returns 1 else it returns 0.

Shift Operators:
By multiplying or dividing the given number by 2, the bits of the figure is shifted to
left or right by using the Shift operators.

Bitwise left shift:


Bitwise left shift is the same as that of multiplying the number with some power of
two. So it fills 0 on voids left as a result, and the bits of the number are shifted to the left.

Bitwise right shift:


The bitwise right shift is the same as that of dividing the number with some power of
two. So it fills 0 on voids left as a result, and the bits of the number are shifted to the right.

& 0 1 | 0 1
0 0 0 0 0 1
1 0 1 1 1 1

^ 0 1 x=7 0 1 1 1 x=7 0111 x=7 0 1 1 1


y=8 1 0 0 0 y=8 1000 y=8 1 0 0 0
0 0 1 x&y 0 0 0 0 x |y 1111 x^y 1 1 1 1
1 1 0

AVCCE/MCA/R-21/I-SEM/NS Page 16

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

1.4.5 Membership Operator

Compare memory locations of two objects.


Example:
x=20
y=20
if(x is y):
print("x and y have same identity")
else:
print("x and y does not have same identity")
Output: x and y have same identity

is Evaluate to true if both element has same id

is not Evaluate to true if both element does not have same id

1.4.6 Identity Operator


Test whether the element is present in sequence such as string,list or tuple.

in Evaluate to true if it find element in sequence

not in Evaluate to true if it does not find element in sequence


Example:
x=1
list=[1,2,3,4,5]
if(x in list):
print(“x is available in list”)
else:
print(“ x is not available in list”)
Output: x is available in lis

AVCCE/MCA/R-21/I-SEM/NS Page 17

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

1.4.7 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.

Operator Example Equivalent to Description


Assigns values from right side operands to left
= x=5 x=5
side operand
It adds right operand to the left operand and
+= x += 5 x=x+5
assign the result to left operand
It subtracts right operand from the left operand
-= x -= 5 x=x-5
and assign the result to left operand
It multiplies right operand with the left operand
*= x *= 5 x=x*5
and assign the result to left operand
It divides left operand with the right operand and
/= x /= 5 x=x/5
assign the result to left operand
It takes modulus using two operands and assign
%= x %= 5 x=x%5
the result to left operand
It performs floor division on operators and assign
//= x //= 5 x = x // 5
value to the left operand
Performs exponential (power) calculation on
**= x **= 5 x = x ** 5
operators and assign value to the left operand

Example Programme
a = 21
b = 10
c = 0

c = a + b
print "Line 1 - Value of c is ", c
c += a
print "Line 2 - Value of c is ", c
c *= a
print "Line 3 - Value of c is ", c
c /= a
print "Line 4 - Value of c is ", c
c = 2
c %= a
print "Line 5 - Value of c is ", c
c **= a
print "Line 6 - Value of c is ", c
c //= a
print "Line 7 - Value of c is ", c

AVCCE/MCA/R-21/I-SEM/NS Page 18

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

OUTPUT
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864

1.4.8 Booleans : represent one of two values: True or False.

Boolean Values
In programming you often need to know if an expression is True or False. You can
evaluate any expression in Python, and get one of two answers, True or False. When you
compare two values, the expression is evaluated and Python returns the Boolean answer:

Example Output
print(10 > 9) True
print(10 == 9) False
print(10 < 9) False

1.4.9 Operator Precedence & Associativity.

Priority of operators that needs to be evaluated at first.

RULES – PEMDAS
• P - parenthesis
• E - Exponent(Square root & power)
• MD - Multiplication and Division
• AS - Add and Subtract
Example: ( 5 * (4 / 2))
Here, 4/2 is evaluated at first, With that result than 5 is multiplied.

1.4. 10 Operator Hierarchy

 Any expression with hierarchy is first evaluated.


 If more than one pair of parenthesis is present, innermost parenthesis is evaluated
first.
 (4/(4*2)) -> (4*2 ) is evaluated first.
 Unary operators
 Multiplication and division
 Add and Subtract
 Relational
 Equality checking
 Logical operation
 Finally assignment operation

AVCCE/MCA/R-21/I-SEM/NS Page 19

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

1.5 Expression
An expression is a combination of values, variables, operators, and calls to
functions. Expressions need to be evaluated. If you ask Python to print an expression, the
interpreter evaluates the expression and displays the result.

1.5.1 Expression evaluation


Example 1:
Example 2:
( 3 - 9 ) / 3 + 77 * ( 3 – 1 )
2+ (3*5) -1+0
(-6) / 3 +77 * (2)
2+15-1+0
-2 + 77 * ( 2 )
16
-2 + 154
152
1.6 Statements
A statement is an instruction that the Python interpreter can execute. We have only
seen the assignment statement so far. Some other kinds of statements that
are while statements, for statements, if statements.

1.7 Conditionals:

In order to write useful programs, we almost always need the ability to check
conditions and change the behaviour of the program accordingly. Selection statements,
sometimes also referred to as conditional statements, give us this ability. The simplest form
of selection is the if statement.
A selection statement causes the program control to be transferred to a specific part of
the program based upon the condition. If the conditional test is true, one part of the program
will be executed, otherwise it will execute the other part of the program.

1.7.1 Types of Conditionals


o if o if-elif-else,
o if-else, o nested if-else

1.7.1.1 IF Constructs statement


The if statement is one in which the else clause is omitted entirely. This creates what
is sometimes called unary selection. In this case, when the condition evaluates to True, the
statements are executed. Otherwise the flow of execution continues to the statement after the
body of the if.

Syntax
if(cond):
statement
Example:
a=10
if(a>0):
print(“a is Non Zero”)

AVCCE/MCA/R-21/I-SEM/NS Page 20

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

Output:
a is non zero

1.7.1.2 IF-ELSE CONSTRUCTS


The if statement is called the condition. If it is true, then the immediately following
indented statements get executed. If not, then the statements indented under the else clause
get executed.
Syntax
if(cond):
statement
else:
statement
#Program for odd or even
a=5
if(a%2==0):
print(“a is even number”)
else:
print(“a is odd number”)
Output:
a is odd number
1.7.1.3 IF-ELIF-ELSE STATEMENT
Each condition is checked in order. If the first is false, the next is checked, and so on.
If one of them is true, the corresponding branch executes, and the statement ends. Even if
more than one condition is true, only the first true branch executes.

Syntax
if(cond):
statement
elif(cond):
statement
else:
statement
#program for student grade
mark=60
if(mark>80):
print(“ First class”)
elif(mark>=50 and mark<80):
print(” Second class”)
else:
print(“fail”)
Output:
Second class

AVCCE/MCA/R-21/I-SEM/NS Page 21

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

1.7.1.4 NESTED IF-ELSE STATEMENT

One conditional can also be nested within another.


Syntax
if(cond):
if(cond):
statement
else:
statement
else:
statement

#Programme to find the temperature

temp=32
if(temp>30):
if(temp>35):
print(“very hot”)
else:
print(“hot”)
else:
print(“normal”)
Output:
hot

1.8 Loop Structures/Iterative Statements

In some programs, certain set of statements are executed again and again based upon
some condition . i.e. executed more than one time. This type of execution is called looping or
iteration. Repeated execution of a sequence of statements is called iteration. Two types
– for loop (auto incremented)
– while loop (not auto incremented)

1.8.1 For Loop

The for loop processes each item in a list. Each


item in turn is (re-)assigned to the loop variable, and the
body of the loop is executed.

Syntax
for iteration in sequence:
statements(s)
Example:

AVCCE/MCA/R-21/I-SEM/NS Page 22

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

#Program to print multiplication table


num=2
for i in range(1,11):
table=num*i
print("{}X{}={}".format(num,i,table))
Output:
2X1=2
2X2=4
2X3=6
2X4=8
2X5=10
2X6=12
2X7=14
2X8=16
2X9=18
2X10=20

1.8.2 While Loop

The while statement provides a much more general mechanism for iterating. Similar
to the if statement, it uses a boolean expression to control the flow of execution. The body of
while will be repeated as long as the controlling boolean expression evaluates to True.

Syntax
while(condition):
body of loop
# Programme to print natural numbers
i=1
n=int(input("enter the end number"))
while i<=n:
print(i)
i=i+1
Output
1 2 3 4 5 6 7 8 9 10 11

1.8.3 Break Statement

If break statement is found the control goes out of the loop

AVCCE/MCA/R-21/I-SEM/NS Page 23

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

Program to demonstrate break statement :


for i in range(1,11):
if(i==5):
break;
print(i)
Output:
1234

1.8.4 Continue statement


On seeing the continue statement goes to the beginning statement of the loop

Program to demonstrate continue statement


for i in range(1,11):
if(i==5):
continue
print(i)
Output:
1 2 3 4 5 6 7 8 9 10

AVCCE/MCA/R-21/I-SEM/NS Page 24

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

1.9 Function
Function is a sub program which consists of set of instructions used to perform a
specific task. When the program is too complex and large they are divided into parts. Each
part is separately coded and combined into single program.
Functions make it more organized and manageable. Debugging, Testing and
maintenance becomes easy when the program is divided into subprograms. Functions are
used to avoid rewriting same code again and again in a program. Function provides code re-
usability; the length of the program is reduced.

1.9.1 Types of function

• Built in function - Functions that are built into Python.


• User defined function - Functions defined by the users themselves.

1.9.1.1 Built in function


Built in functions are the functions that are already created and stored in python.
These built in functions are always available for usage and accessed by a programmer. It
cannot be modified.

1.9.1.2 User Defined Functions

User defined functions are the functions that programmers create for their requirement
and use. These functions can then be combined to form module which can be used in other
programs by importing them.
Programmers working on large project can divide the workload by making different
functions. If repeated code occurs in a program, function can be used to include those codes
and execute when needed by calling that function. A function can be defined and can be
called at any place in a program.

AVCCE/MCA/R-21/I-SEM/NS Page 25

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

1.9.2 Function Call and Returning Values

1.9.2.1 Function definition: (Sub program)


def keyword is used to define a function. Give the function name after def keyword
followed by parentheses in which arguments are given. End with colon (:), Inside the function
add the program statements to be executed, End with or without return statement

Syntax:
def fun_name(Parameter1,Parameter2…Parameter n):
statement1
statement2…
statement n return[expression]

1.9.2.2 Function Calling: (Main Function)

Once we have defined a function, we can call it from another function, program or
even from the Python prompt. To call a function we simply type the function name with
appropriate arguments.

Syntax:
function_name(parameters);

1.9.2.3 Flow of Execution


The order in which statements are executed is called the flow of execution. Execution
always begins at the first statement of the program. Statements are executed one at a time, in
order, from top to bottom. Function definitions do not alter the flow of execution of the
program, but remember that statements inside the function are not executed until the function
is called. Function calls are like a bypass in the flow of execution.
Instead of going to the next statement, the flow jumps to the first line of the called
function, executes all the statements there, and then comes back to pick up where it left off.
When you read a program, don’t read from top to bottom. Instead, follow the flow of
execution. This means that you will read the def statements as you are scanning from top to
bottom, but you should skip the statements of the function definition until you reach a point
where that function is called.

AVCCE/MCA/R-21/I-SEM/NS Page 26

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

1.9.3 Function Prototypes

i. Function without arguments and without return type


ii. Function with arguments and without return type
iii. Function without arguments and with return type
iv. Function with arguments and with return type

i) Function without arguments and without return type

In this type no argument is passed through the function call and no output is return to
main function. The sub function will read the input values perform the operation and print the
result in the same block

ii) Function with arguments and without return type


Arguments are passed through the function call but output is not return to the main
function

iii) Function without arguments and with return type


In this type no argument is passed through the function call but output is return to the
main function.

iv) Function with arguments and with return type


In this type arguments are passed through the function call and output is return to the
main function

1.9.3.1 RETURN STATEMENT

The return statement is used to exit a function and go back to the place from where it
was called. If the return statement has no arguments, then it will not return any values. But
exits from function.

Syntax:
return [expression]

Example Programmes

AVCCE/MCA/R-21/I-SEM/NS Page 27

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

1.9.4 Parameters and Arguments

1.9.4.1 Parameters:

Parameters are the value(s) provided in the parenthesis when we write function
header. These are the values required by function to work. If there is more than one value
required, all of them will be listed in parameter list separated by comma.

Example: def my_add(a,b,c,d):

1.9.4.2 Arguments :

Arguments are the value(s) provided in function call/invoke statement. List of


arguments should be supplied in same way as parameters are listed.Bounding of parameters
to arguments is done 1:1, and so there should be same number and type of arguments as
mentioned in parameter list.

Example: my_add(x,y)

1.9.4.3 Parameter Passing

All parameters (arguments) in the Python language are passed by reference. It means
if you change a parameter refers to within a function that change also reflects back in the
calling function.

1.9.4.4 ARGUMENT TYPES

1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments

1.9.4.4.1 Required Arguments :

The number of arguments in the function call should match exactly with the function
definition.

Example

AVCCE/MCA/R-21/I-SEM/NS Page 28

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

def my_details( name, age ):


print("Name: ", name)
print("Age ", age)
return
my_details("srini",41)

Output:
Name: srini Age 41

1.9.4.4.2 Keyword Arguments:

Python interpreter is able to use the keywords provided to match the values with
parameters even though if they are arranged in out of order.

Example
def my_details(name,age):
print("Name: ", name)
print("Age :", age)
return
my_details(age=41,name="srini")

Output
Name: srini
Age 41

1.9.4.4.3 Default Arguments:

Assumes a default value if a value is not provided in the function call for that
argument.

Example
defmy_details( name, age=41 ):
print("Name: ", name)
print("Age :", age) return
my_details(name=“srini")
Output:
Name: srini Age:41

1.9.4.4.4 Variable length Arguments

If we want to specify more arguments than specified while defining the function,
variable length arguments are used. It is denoted by * symbol before parameter.
Example:
def my_details(*name ):
print(*name)
my_details("rajan","rahul","micheal", ärjun")

AVCCE/MCA/R-21/I-SEM/NS Page 29

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)


lOMoARcPSD|34873126

MC4103_Python Programming Unit -1| Basics of Python

Output:
rajan rahul micheal ärjun

1.9.5 Scope of Variables

All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable. The scope of a variable determines the
portion of the program where you can access a particular identifier.

There are two basic scopes of variables in Python


– Global variables
– Local variables

Global Variables

In Python, a variable declared outside of the function or in global scope is known as a


global variable. This means that a global variable can be accessed inside or outside of the
function.

Local Variables

A variable declared inside the function's body or in the local scope is known as a local
variable.

1.9.6 Recursive Functions.

A function that calls itself. A physical world example would be to place two parallel
mirrors facing each other. Any object in between them would be reflected recursively. In
Python, we know that a function can call other functions. It is even possible for the function
to call itself. These types of construct are termed as recursive functions.

# Programme to find factorial number

def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num =int(input("Enter the value : "))
print("The factorial of", num, "is :", factorial(num))

Output
Enter value 3

The factorial of 3 is : 6

***** SUCCESS!*****

AVCCE/MCA/R-21/I-SEM/NS Page 30

Downloaded by samad ahmed (mdsamadabdul28@gmail.com)

You might also like