0% found this document useful (0 votes)
69 views78 pages

22CB923 Unit 1

This document is a confidential syllabus for a Python Programming course offered by RMK Group of Educational Institutions for the 2023-27 batch. It outlines course objectives, prerequisites, a detailed syllabus, course outcomes, and assessment schedules. The document also includes information on textbooks, references, and equipment needed for the course.

Uploaded by

Jayaram B
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views78 pages

22CB923 Unit 1

This document is a confidential syllabus for a Python Programming course offered by RMK Group of Educational Institutions for the 2023-27 batch. It outlines course objectives, prerequisites, a detailed syllabus, course outcomes, and assessment schedules. The document also includes information on textbooks, references, and equipment needed for the course.

Uploaded by

Jayaram B
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 78

Please read this disclaimer before

proceeding:
This document is confidential and intended solely for the
educational purpose of RMK Group of Educational Institutions. If
you have received this document through email in error, please
notify the system manager. This document contains proprietary
information and is intended only to the respective group / learning
community as intended. If you are not the addressee you should
not disseminate, distribute or copy through e-mail. Please
notify the sender immediately by e-mail if you have received this
document by mistake and delete this document from your system.
If you are not the intended recipient you are notified that
disclosing, copying, distributing or taking any action in reliance on
the contents of this information is strictly prohibited.
22CB923 Python
Programming

Department : CSBS
Batch/Year : 2023 – 27 BATCH / III
Created by : Mr. B.Jayaram ASP/CSBS RMKE C
&
Ms. K.Sasirekha AP/CSBS
RMDEC
Date
: 06.05.25
Table of Contents

S NO CONTENTS PAGE NO

1 Contents 5

2 Course Objectives 6

3 Pre Requisites (Course Names with Code) 6

4 Syllabus (With Subject Code, Name, LTPC 7


details)
5 Course Outcomes 9

6 CO- PO/PSO Mapping 10

7 Lecture Plan 11

8 Activity Based Learning 12

9 Lecture Notes 14

10 Assignments 71

11 Part A (Q & A) 72

12 Part B Qs 82

13 Supportive Online Certification Courses 84

Real time Applications in day to day life and


14 to 85
Industry

15 Contents Beyond the Syllabus 86

16 Assessment Schedule 87

17 Prescribed Text Books & Reference Books 88

18 Mini Project Suggestions 89


COURSE OBJECTIVES

• To understand and write simple Python programs.


• To write Python programs using functions and understand recursion
• To solve problems using Python data structures –- lists, tuples,
dictionaries.
• To understand files, modules and packages in Python.
• To use Exceptions, Standard Libraries and IDE for application
development.

PREREQUISIT
E

22CS101 – Problem Solving in C++

22CS201 – Data Structures and Algorithms

22CS202 – Java Programing


SYLLABUS
22CB93 PYTHON PROGRAMMING L T P C
2
2 0 2 3
UNIT I INTRODUCTION TO PYTHON 6+6

Introduction to Python programming – Arithmetic Operators - values


and types - variables, expressions, statements – Functions –
Conditionals and Recursion – Iteration.

List of Exercise/Experiments
a) Compute the GCD of two numbers.
b) Find the square root of a number (Newton’s method)
c) First n prime numbers

UNIT II FUNCTIONS 6+6

Fruitful functions: Return Values, Incremental Development,


Composition, Boolean functions, Recursion, Example, Checking Types –
Strings: len, Traversal with a for loop, String slices, Immutable,
Searching, Looping and Counting, String Methods, in Operator, String
Comparison – Case Study: Word Play.

List of Exercise/Experiments
String manipulation
a) Get a string from a given string where all occurrences of its first char
have been changed to '$', except the first char itself
b) Python function that takes a list of words and returns the length of
the longest one.
c) Python program to remove the characters which have odd index
values of a given string
d) Python program to count the occurrences of each word in a given
sentence.
e) Python program that accepts a comma separated sequence of words
as input and prints the unique words in sorted form
f) Python function to reverses a string if it's length is a multiple of 4

UNIT III LISTS, DICTIONARIES, TUPLES 6+6

Lists: Sequence, Mutable, Traversing, Operations, list slices, list


methods, Map, Filter and Reduce, Deleting elements, Lists and Strings,
Objects and Values, Aliasing, List Arguments. Dictionaries: Mapping,
Collection of Counters, Looping and Dictionaries, Reverse Lookup,
Dictionaries and Lists, Memos, Global Variables Tuples: Immutable,
Tuple Assignment, Tuple as Return Values, Variable-length Argument
Tuples, Lists and Tuples, dictionaries and Tuples, Sequences of
Sequences. Case Study: Data Structure Selection.
SYLLABUS
22CB93 PYTHON PROGRAMMING L T P C
2
2 0 2 3
List of Exercise/Experiments

a) Operations on Tuples:
a) finding repeated elements
b) slice a tuple
c) reverse a tuple
d) replace last value of a tuple
b) List operations
a) Find the maximum of a list of numbers
b) Python program to remove duplicates from a list.
c) Python program to get the smallest number from a list.
d) Python program to print a specified list after removing the 0th, 4th
and 5th elements.
e) Python program to print the numbers of a specified list after
removing even numbers from it.
f) Python program to find the second smallest number in a list.
c) Linear search and Binary search
d) Selection sort, Insertion sort
e) Merge sort
f) Multiply matrices

UNIT IV FILES, MODULES, PACKAGES 6+6

Files: Persistence, Reading and Writing, Format Operator, Filenames


and Paths, Catching Exceptions - Modules: Importing a module,
Packages, Creating a module.

List of Exercise/Experiments
Programs that take command line arguments (word count)
Find the most frequent words in a text read from a file

UNIT V EXCEPTIONS, LIBRARIES 6+6

Exception Handling – Built-in Exceptions – Application Development


with Python: Integrated
Development Environment, Python Standard Library.
List of Exercise/Experiments
Simulate elliptical orbits in Pygame
Simulate bouncing ball using Pygame

TOTAL: 30+30=60 PERIODS


SYLLABUS
22CB93 PYTHON PROGRAMMING L T P C
2
2 0 2 3
COURSE OUTCOMES:

Upon completion of the course, the students will be able to:


CO1 Implement simple Python programs.
CO2 Develop Python programs using functions.
CO3 Represent and solve compound data using Python lists, tuples,
dictionaries. CO4 Implement and perform operations on files, modules
and packages.
CO5 Apply Exceptions, Standard Libraries and IDE for application

TEXTBOOKS:

1. Allen B. Downey, “Think Python: How to Think Like a Computer


Scientist”, 2nd edition, Updated for Python 3, Shroff/O‘Reilly
Publishers, 2016 (http://greenteapress.com/wp/thinkpython/)
2. Martin C. Brown, Python: The Complete Reference, Mc-Graw Hill,
(Unit 4 – Chapter 5, Unit 5 – Chapter 7, 17)

REFERENCES:

3. David Beazley, Brian K. Jones, Python Cookbook, O’Reilly, Third


Edition, 2013.
4. ReemaThareja, “Problem Solving and Programming with Python”,
2nd Edition, Oxford University Press 2019
5. Guido van Rossum and Fred L. Drake Jr, ―An Introduction to Python –
Revised and updated for Python 3.2, Network Theory Ltd., 2011.
6. John V Guttag, ―Introduction to Computation and Programming
Using Python”, Revised and expanded Edition, MIT Press, 2013
7. Robert Sedgewick, Kevin Wayne, Robert Dondero, ―Introduction to
Programming in Python: An Inter-Disciplinary Approach, Pearson
India Education Services Pvt. Ltd., 2016
8. Timothy A. Budd, ―Exploring Python, Mc-Graw Hill Education (India)
Private Ltd., 2015.
9. Kenneth A. Lambert, ―Fundamentals of Python: First Programs‖,
CENGAGE Learning, 2012
10.Charles Dierbach, ―Introduction to Computer Science using Python:
A Computational Problem-Solving Focus, Wiley India Edition, 2013.
11.Paul Gries, Jennifer Campbell and Jason Montojo, ―Practical
Programming: An Introduction to Computer Science using Python 3‖,
Second edition, Pragmatic Programmers, LLC, 2013

LIST OF EQUIPMENTS:

Systems with Linux Operating System


Python Interpreter
Course
Outcomes Cognitive/
Affectiv
Expected
Cours e Level
Course Outcome Statement Level of
e of the
Attainme
Code Course
nt
Outcom
e
Course Outcome Statements in Cognitive Domain

Implement simple Python programs. Understan


CO1 d K2 70%

Develop Python programs using functions. Analys


CO2 e K4 70%

Represent and solve compound data using Understan


CO3 Python lists, tuples, dictionaries. d K2 70%

Implement and perform operations on files,


modules and packages. Analys
CO4 e K4 70%

Apply Exceptions, Standard Libraries and IDE for


application Analys
CO5 e K4 70%
CO-PO/PSO Mapping

Correlation Matrix of the Course Outcomes to Programme


Outcomes and Programme Specific Outcomes Including Course
Enrichment Activities

(CO Programme Outcomes (POs), Programme Specific Outcomes


s) (PSOs)

PO PO PO PO PO PO PO PO PO PO PO PO PS PS PS
1 2 3 4 5 6 7 8 9 10 11 12 O1 O2 O3

CO1 3 2 1 1 3 3 3 3 3

CO2 3 3 2 2 3 3 3 3 3

CO3 2 1 2 3 3 3

CO4 3 2 1 1 3 3 3 3 3

CO5 3 3 2 2 3 3 3 3 3

CO6 3 2 1 1 3 3 2 2 2

9
Lecture
Plan
UNIT – I

of delivery
Actual lecture Date
S No Topics

Taxonomy level
Proposed date

pertaining CO
of
Periods

Mode
No
Introduction to Python
programming 1
1 CO1 K1 PPT

Arithmetic Operators

2 1 CO1 K2 Chalk &


Talk
values and types
Chalk &
3 1 CO1 K2 Talk
variables
Chalk &
CO1 K2
4 1 Talk

expressions Chalk &


5 1 CO1 K2 Talk

statements
6 1 CO1 K2 PPT / Video

Functions
1
7 K2 PPT
CO1

Conditionals and Recursion


8 1 K2 PPT
CO1

9 Iteration
1 CO1 K3 PPT
Activity based
learning (Model
building/Prototype)

S NO TOPICS
Arithmetic Operators
Activity:
1 Build a simple calculator that performs addition, subtraction, multiplication,
division, modulus, and exponentiation based on user input.

Activity:
2 Create a script that takes multiple inputs (string, int, float, boolean) and prints
their types using type() function.

3 Write a script that stores temperature in Celsius in a variable and converts it to


Fahrenheit using a mathematical expression.
UNIT I
INTRODUCTION TO PYTHON
 Python is a popular programming language. It was created by Gudio
Van Rossum in the year 1991.

 Python is an example of a high-level language;


 Python is a general purpose programming language.
 It is an interactive, interpreted, object oriented and high level
programming
language.

Python Features
 Easy to learn
 Portable
 Interpreted
 Extensible
 Free and Open Source
 High Level Language
 Scalable
 Easy to understand and write.
 Interactive programming language.
 Used in various application areas such as Web, Gaming, Scientific and
Numeric computing, Text processing and Network programming.
 Free and Open Source.
Advantages:

 First, it is much easier to program in a high-level language. Programs written


in a high-level language take less time to write, they are shorter and easier
to read, and they are more likely to be correct.

 Second, high-level languages are portable, meaning that they can run on
different kinds of computers with few or no modifications
Difference between Interpreter and
Compiler Compiler
• Compiler takes the entire program as input
• Object code is generated
• It occupies more memory
• Program compiled only once
• It displays the error after compiling the
entire program.
Interpreter
• Interpreter reads the program line by line
• There is no intermediate object code
• It occupies less memory
• Program interpreted line by line.
• It displays the error immediately.

 Two kinds of programs process high-level


languages into low-level languages:
interpreters and compilers.
 An interpreter reads a high-level program
and executes it, meaning that it does what
the program says. It processes the
program a little at a time, alternately
reading lines and performing
computations.

 A compiler reads the program and


translates it completely before the
program starts running. In this context, the
high-level program is called the source
code, and the translated program is called
the object code or the executable. Once a
program is compiled, you can execute it
repeatedly without further translation.
Python Modes
There are two types of modes in python

 Interactive mode
 Script Mode

Interactive mode
 Interactive mode is used when user wants to run one single line or block of
code and get
the result immediately.
 The commands are typed and executed in python interpreter. It runs very
quickly and
gives the output instantly.
 We can’t save the code immediately.
 To exit this mode type exit() and press Enter.

 Interactive mode looks like this

Example
>>>a=10
>>>b=20
>>>c=a+b
>>>print(c)
>>>30
Script Mode
Script mode
 To access the Script mode or python shell, open the terminal and type
“python”
then press Enter key and the python shell will appear.
 This mode is used to execute Python program written in a file.
 The python interpreter read and execute the statement in the script
mode.
 We can save the code immediately. All the instruction necessary for
the task are stored in a file often called source file,
program, source code or a module.
 The saved file must have an extension .py.
 We can not see the results immediately.
 Script mode looks like this

Example:
 Type the following lines in any editor and save as firstprg.py
print(“Hello World!”)
 To execute the file firstprg.py in script mode type the following in the
command prompt.
>>>python firstprg.py
 Then it will print Hello World! as a Output
2. Values and Types, Variables,
Expressions, Statements
2. Values and Types, Variables, Expressions,
Statements

1. Values and
Types Values
 A value is one of the
basic things in a
program.
 A value is one of the
basic things a program
work with like letter or a
number.
 There are different
values in Python. Values
may be integers, float
and strings.
 Whole numbers are
called Integers.
 The numbers with a
decimal point belong to
a type called float.
 The values written in quotes will be considered as string, even it’s an
integer. If type of value is not known it can be interpreted as
string.
Example
2, 3.5, “Hello”

Types

 We use type() function to know which class a variable or which type


variable is or class belong to
Example
>>> type('Hello, World!')
<type 'str'>

>>> type(17)
<type 'int'>

>>> type('17')
<type 'str'>

>>> type('3.2')
<type 'str’>
 Every value in python has a data type.
 The data stored in memory can be of many types.
 Python has various data types that are used to define the operations
possible on
them and storage methods of each of them.
2.2. Variables

Variable
 A variable is a name that refers to a value.
 The name of the variable should be meaningful.
 Variables have reserved memory locations to store values.
 Based on the data type of a variable, the interpreter allocates memory and
decides what
can be stored in the reserved memory.

Variable declaration
In python variables need not to be declared explicitly.
Assigning values to variables
The equal sign is used to assign values to variables.
Example:
>>> message = 'And now for something completely different’
>>> n = 17
>>> pi = 3.1415926535897931
This example makes three assignments. The first assigns a string to a new
variable named message; the second gives the integer 17 to n; the third
assigns the (approximate) value of π to pi.
Rules
 Variable names should start with an alphabet.
 There is no space between variable names.
 Variables may be the combination of letters and digits and ‘_’.
 Variables also have types. The type of the variable belongs to the values
stored in
variable.
 Keywords should not be used as variable names.

Keywords
Python has a set of keywords that are reserved words that cannot be used
and def exec if not return assert del finally
as variable names. Python has these keywords :
break elif for in pass while import or try
class else from is print yield continue except global
lambda raise
2.3. Expressions

Expression
 An Expression is a combination of values, variables, and operators.
Example: c=a+b
x=m+10
 A value or a variable by itself is considered an expression.
Example: c=a
x=10
 If you type an expression in interactive mode, the interpreter evaluates it
and displays the result:
Example: >>>1+1
2

2.4. Statements

 A statement is a unit of code that the Python interpreter can execute.

 We have two kinds of statements: print and assignment


 This unit of code has an effect, like creating or displaying a value.
 We have seen two kinds of statement: print and assignment.
 The important difference is that an expression has a value; a statement
does not.
 A script usually contains a sequence of statements. If there is more than
one statement, the results appear one at a time as the statements
execute.
 For example, the script
print 1
x=2
print x
produces the output
1
2
 The assignment statement produces no output.
3. Operators and Precedence of
Operators
Operators:

• Operators are special symbols that perform operations on variables and values.
• Python operators are special symbols used to perform specific operations on
one or more operands.
• The variables, values, or expressions can be used as operands.
• The operators +, -, *, / and ** perform addition, subtraction, multiplication,
division and exponentiation, as in the following
Examples:
20+32 hour-1 hour*60+minute minute/60 5**2 (5+9)*(15-7)

The following are some of the terms related to Python operators:

• Unary operators: Python operators that require one operand to perform a


specific operation are known as unary operators.

• Binary operators: Python operators that require two operands to perform a


specific operation are known as binary operators.

• Operands: Variables, values, or expressions that are used with the operator to
perform a specific operation.

Python Supports

 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 Logical Operators
 Identity Operators
 Membership Operators
 Bitwise Operators
3.1.1 Arithmetic Operators

 Arithmetic operators are used to perform mathematical operations like


addition, subtraction, multiplication, etc.

 Arithmetic Operators can be used with numerical values.

Operator Name Example Values

>>5+2
+ Addition x+y
7
>> 5-2
- Subtraction x-y
3
>>
* Multiplication x*y
5*2 10
>>
/ Division x/y
5/2
2.5
>>5%2
% Modulus x%y
1
>>5**
** Exponentiation x ** y
2 25
>>5//
// Floor division x // y
22

Example 1: Arithmetic Operators in Python

a=7

b=2

# addition

print ('Sum: ', a + b)

# subtraction

print ('Subtraction: ', a - b)

# multiplication

print ('Multiplication: ', a * b)

# division

print ('Division: ', a / b)


# floor division

print ('Floor Division: ', a // b)

# modulo

print ('Modulo: ', a % b)

# a to the power b

print ('Power: ', a ** b)

Output

Sum: 9

Subtraction: 5

Multiplication: 14

Division: 3.5

Floor Division: 3

Modulo: 1

Power: 49
3.1.2 Assignment Operators
 Assignment Operators are used to assign the values to the variables. This
operator is used to assign the value of the right side of the expression to the left
side operand.

 It includes Addition Assignment Operator, Subtraction Assignment Operator,


Multiplication Assignment Operator, Division Assignment Operator, Modulus
Assignment Operator, Floor Division Assignment Operator, Exponentiation
Assignment Operator, Bitwise AND Assignment Operator, Bitwise OR
Assignment Operator, Bitwise XOR Assignment Operator, Bitwise Right Shift
Assignment Operator, Bitwise Left Shift Assignment Operator etc.

Operator Example Same As Output

= x=5 x=5 5

+= x += 3 x=x+3 8

-= x -= 3 x=x-3 5

*= x *= 3 x=x*3 15

/= x /= 3 x=x/3 5

%= x %= 3 x=x%3 2

//= x //= 3 x = x // 3 1.6

**= x **= 3 x = x ** 3 125

&= x &= 3 x=x&3 1

|= x |= 3 x=x|3 7

^= x ^= 3 x=x^3 6

>>= x >>= 3 x = x >> 3 Shift left

<<= x <<= 3 x = x << 3 Shift right


3.1.3 Comparison Operators

Comparison operators are used to compare the values of the variables and return
a boolean result: True or False
.

Operator Name Example Output

>>5==5
== Equal x == y
>>1

>>5!=5
!= Not equal x != y
>>0

>>5>2
> Greater than x>y
>>1

>>5<2
< Less than x<y
1

>>5>=3
>= Greater than or equal x >= y
>>1
to
>>5<=3
<= Less than or equal to x <= y
>>0

For Example: a = 5, b = 2

# equal to operator

print('a == b =', a == b)

# not equal to operator

print('a != b =', a != b)
# greater than operator

print('a > b =', a > b)

# less than operator

print('a < b =', a < b)

# greater than or equal to operator

print('a >= b =', a >= b)

# less than or equal to operator

print('a <= b =', a <= b)

Output

a == b = False

a != b = True

a > b = True

a < b = False

a >= b = True

a <= b = False
3.1.4 Logical Operators

 Logical operators are used to combine the logical statements.


 Logical operators are used on conditional statements (either True or False). They
perform Logical AND, Logical OR, and Logical NOT operations.

 They are used in decision-making.

Operator Description Example Output

Returns True if x < 5 and


and >> 1
both statements x<
are true 10

Returns True if
or x < 5 or x < 4 >> 1
oneof the
statements is true

Reverse the
not(x < 5 and
not result, returns >>0
x
False if the
< 10)
result is true
3.1.5 Identity Operators

Identity Operators are used to compare the memory location of an object

Python IS Operator

The is operator evaluates to True if the variables on either side of the operator
point to the same object in the memory and false otherwise.

Python IS NOT Operator

The is not operator evaluates True if both variables on the either side of the
operator are not the same object in the memory location otherwise it evaluates
False.

Operator Description Example Output

Returns True if both


is x is y 1
variables are the
same object

Returns True if both variables


is not x is not y 1
are not the same
object

Example:

x1 = 5

y1 = 5

x2 = 'Hello'

y2 = 'Hello'

x3 = [1,2,3]

y3 = [1,2,3]

print (x1 is not y1) # prints False

print (x2 is y2) # prints True

print (x3 is y3) # prints False


3.1.6 Membership
Operators
 Membership operators are used to test the sequence is present or not
 In Python, in and not in are the membership operators. They are used to test
whether a value or variable is found in a sequence (string, list, tuple, set and
dictionary).
 In a dictionary, we can only test for the presence of a key, not the value.
Operator Description Example Output

Returns True if a Eg
in sequence with the x in y >>l=[1,2,3]
specified value is >>1 in l
present in the object >> True
Eg
Returns True if a >>l=[1,2,3]
not in sequence with the x not in y >>1 not in l
specified value is not >> false
present in the object

Python IN Operator
The in operator is used to check if a character/substring/element exists in a
sequence or not. Evaluate to True if it finds the specified element in a sequence
otherwise False.
Python NOT IN Operator
The ‘not in’ Python operator evaluates to true if it does not find the variable in
the specified sequence and false otherwise.
Example:
message = 'Hello world'
dict1 = {1:'a', 2:'b'}
# check if 'H' is present in message string
print('H' in message) # prints True
# check if 'hello' is present in message string
print('hello' not in message) # prints True
# check if '1' key is present in dict1
print(1 in dict1) # prints True
# check if 'a' key is present in dict1
print('a' in dict1) # prints False
3.1.7 Bitwise Operators

 Python bitwise operators are used to perform bitwise calculations on integers.


 The integers are first converted into binary and then operations are
performed on each bit or corresponding pair of bits, hence the name bitwise
operators.
 The result is then returned in decimal format.

Operator Name Description

& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits

Zero fill Shift left by pushing zeros in from the right and
<<
left let the leftmost bits fall off
shift

Signed Shift right by pushing copies of the leftmost bit in


>>
right from the left, and let the rightmost bits
shift fall off

Bitwise AND Operator

Python Bitwise AND (&) operator takes two equal-length bit patterns as
parameters. The two-bit integers are compared. If the bits in the compared
positions of the bit patterns are 1, then the resulting bit is 1. If not, it is 0.

Example: Take two bit values X and Y, where X = 7= (111)2 and Y = 4 =


(100)2 . Take Bitwise and of both X & y
Bitwise OR Operator

The Python Bitwise OR (|) Operator takes two equivalent length bit designs as
boundaries; if the two bits in the looked-at position are 0, the next bit is zero.
If not, it is 1.

Example: Take two bit values X and Y, where X = 7= (111)2 and Y = 4 =


(100)2 . Take Bitwise OR of both X, Y

Bitwise XOR Operator

The Python Bitwise XOR (^) Operator also known as the exclusive OR
operator, is used to perform the XOR operation on two operands. XOR
stands for “exclusive or”, and it returns true if and only if exactly one of the
operands is true. In the context of bitwise operations, it compares
corresponding bits of two operands. If the bits are different, it returns 1;
otherwise, it returns 0.

Example: Take two bit values X and Y, where X = 7= (111)2 and Y = 4 =


(100)2 . Take Bitwise and of both X & Y

Bitwise NOT Operator

The preceding three bitwise operators are binary operators, necessitating


two operands to function. However, unlike the others, this operator operates
with only one operand.

Python Bitwise Not (~) Operator works with a single value and returns its
one’s complement. This means it toggles all bits in the value, transforming
0 bits to 1 and 1 bits to 0, resulting in the one’s complement of the binary
number.

Example: Take two bit values X and Y, where X = 5= (101)2 . Take Bitwise
NOT of X.
3.1.8 Operator
Precedence
Operators Meaning

() Parentheses

** Exponent

Unary plus, Unary minus,


+x, -x, ~x
Bitwise NOT

Multiplication, Division,
*, /, //, %
Floor division, Modulus

+, - Addition, Subtraction

<<, >> Bitwise shift operators

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

==, !=, >, >=, <, <=, is, Comparisons,


is not, in, not in Identity,
Membership
operators
not Logical NOT

and Logical AND

or Logical OR
4.
Comments
4. Comments
 As programs get bigger and more complicated, users get more difficult to
read.
 For this reason, it is a good idea to add notes to your programs to
explain in natural language what the program is doing.
 These notes are called comments, A comment is a piece of program
text that the interpreter ignores but that provides useful
documentation to programmers.
 Two types of comments
1. Single line comment
2. Multi line comment

Single line comment


Single line comment start with the # symbol. # symbol is used to give
single line comment.
Example:
# find the sum of digit
You can also put comments at the end of a line, that is called as
end-of-line comments.
Example:
f=c*(9/5)+32 # calculate c to
f
Everything from the # to the end of the line is ignored—it has no
effect on the program.

Multi line comment


Multi line comment is included inside triple quotes (single quote
or double quote).
That will start with the ‘’’ symbol and end with the ‘’’ symbol or
start with the “
““
symbol and end with the “ “ “ symbol
Example:
‘’’This program
is sum of odd
and even
number’’’
5.
Functions
1. Functions

Function

 A function is a block of code, only it runs when the function called.


 A function is a named sequence of statements that performs a computation.
 A function is a block of organized, reusable-code that is used to perform a
single, related action.
 A module is a file that contains a collection of related functions.
 Functions often require arguments, that is, specific data values, to perform
their
tasks.
Syntax

Here ‘def’ is a keyword. Function name is user defined


name. There is no space in between function names.

Example
def add():# function definition
a=5
b=2 c=a +
b print(c)
add() # function
call

‘add’ is a function name. ‘add’ is user defined


function. There are two types of function
User defined function.(user define their own
function)
Pre defined function.(inbuilt or library function)
Python Library Functions

Python provides some built-in functions that can be directly used in our program.

We don't need to create the function; we just need to call them.

Some Python library functions are:

1. print () - prints the string inside the quotation marks

2. sqrt () - returns the square root of a number

3. pow () - returns the power of a number

These library functions are defined inside the module. And to use them, we must
include the module inside our program.

For example, sqrt () is defined inside the math module.

Types of Functions in Python

• Built-in library function: These are Standard functions in Python that are
available to use.

• User-defined function: We can create our own functions based on our


requirements.

User-Defined Functions

• These are the functions we create ourselves. They're like our custom tools,
designed for specific tasks we have in mind.

• They're not part of Python's standard toolbox, which means we have the
freedom to tailor them exactly to our needs, adding a personal touch to our
code.

Built- in / Standard Library Functions

• Think of these as Python's pre-packaged gifts. They come built-in with Python,
ready to use.

• These functions cover a wide range of common tasks such as mathematics,


file operations, working with strings, etc.

• They've been tried and tested by the Python community, ensuring efficiency
and reliability.
Python Function Arguments

5.2 Types of arguments

Types of arguments
1. Default arguments
2. Keyword arguments.
3. Variable length arguments
4. Required arguments

1 Default arguments
.
The arguments can have default values are known as default
arguments

def printinfo (a , b=10):


print ( a,
b) printinfo (5)
It assigns a=5 and default value of b=10.

2 Keyword Arguments
When we call a function with values. This values get assigned to the
arguments according to their position.

def printinfo(name, age):


print(“name=“,name
“age=“,age)
printinfo(age=50,name=“aaa”)

Here age is in second position and name is in first position. While passing
the arguments according to the name of the arguments. It automatically
assign the values by using their names.
3 Variable length
. arguments
A function for more arguments is called variable length arguments.

Example
def printinfo(arg1,*t):
print(“number of arguments passed”,arg1)
for i in t:
print(i)
printinfo(10)
printinfo(10,20,3
0)

Here the 1st printinfo function gets only one value and 2nd printinfo
function takes three values. So in a single function we can pass more than one
values.This is known as variable length arguments.

4. Required arguments

The type of arguments passed in correct positional order is known


as required arguments.

def area(r):
return pi*r*r
print(area(5))
Recursion:
 Recursion is a programming technique that allows the programmer
to express operations in terms of themselves.
 It takes the form of a function that calls itself.
 A function that calls itself is known as a recursive function. And, this
technique is known as recursion.
 The process in which a function calls itself directly or indirectly is
called recursion and the corresponding function is called as recursive
function.
 Using recursive algorithm, certain problems can be solved quite
easily. Example of such problem is Towers of Hanoi
 In the recursive program, the solution to the base case is
provided and the solution of the bigger problem is expressed in
terms of smaller problems.

Base Case:

This is the condition that stops the recursion. It's crucial to have a
base case to prevent the function from calling itself indefinitely,
which would lead to a stack overflow error.

Recursive Step:

This is where the function calls itself with a modified version of the
original problem. The goal is to reduce the problem size with each
recursive call until it reaches the base case.

Basic Structure of Recursive Function

def recursive_function(parameters):

if base_case_condition:

return base_result

else:

return recursive_function(modified_parameters)
Example of recursion is calculating the factorial of a number:

def factorial(n):
if n == 0: # Base case: factorial of 0 is 1
return 1
else:
return n * factorial(n-1) # Recursive step

print(factorial(5))

Output

120

In this example, the factorial function calls itself with n-1 until n becomes 0.
When n is 0, the base case is reached, and the function returns 1. The results
of the recursive calls are then multiplied together to calculate the final
factorial.

Types of Recursions in Python

Recursion can be broadly classified into two types: tail recursion and non-tail
recursion. The main difference between them is related to what happens after
the recursive call.
 Tail Recursion: This occurs when the recursive call is the last operation
executed in the function, with no additional work or calculation following
the recursive call. In many programming languages, tail recursion can be
optimized by the compiler into iterative loops to improve performance
and prevent stack overflow.
 Non-Tail Recursion: This occurs when there are operations or calculations
that follow the recursive call. This type prevents the compiler or
interpreter from optimizing the recursion into an iteration.

def tail_fact(n, acc=1):

# Base case

if n == 0:

return acc

# Tail recursive call with an accumulator

else:

return tail_fact(n-1, acc * n)


def nontail_fact(n):

# Base case

if n == 1:

return 1

# Non-tail recursive call because the multiplication happens after the


call

else:

return n * nontail_fact(n-1)

# Example usage

print(tail_fact(5))

print(nontail_fact(5))

Output

120

120

Advantages of Recursion

1. Recursive functions make the code look clean and elegant.

2. A complex task can be broken down into simpler sub-problems using


recursion.

3. Sequence generation is easier with recursion than using some


nested iteration.

Disadvantages of Recursion

4. Sometimes the logic behind recursion is hard to follow through.

5. Recursive calls are expensive (inefficient) as they take up a lot of


memory and time.

6. Recursive functions are hard to debug.


6. Conditionals,
Iteration
1. Boolean values and operators
 The Boolean data type consists of only two data values - True and
False
 True and False are special values that belong to the type bool;
they are not strings:
>>> type(True)
<type 'bool'>
>>> type(False)
<type 'bool'>

 In numeric contexts (for example when used as the argument to an


arithmetic operator), they behave like the integers 0 and 1,
respectively.

6.2. Conditionals:
Conditional statements give us ability to check conditions and change the
flow of the program or behavior of the program accordingly.
Types of Conditional statements
1. if statement (conditional) 2. if-else statement
3. if-elif-else (alternative)
(chainedconditional) 4. Nested Conditional

A loop statement allows us to execute a statement or group of


statements multiple times. The following diagram illustrates a loop
statement −

6.2.1. if statement (conditional statement)


Conditional statement (if) is also called a one-way selection
statement, because it consists of a condition and a sequence of
statements. If the condition is true, the sequence of statements is run.
Otherwise, control proceeds to the next statement following the entire
selection statement.

Syntax: Flow diagram:


if condition:
statemen
ts
Example
a=5
if a>2:
print(“Hello”)
6.2.2. if-else statement (alternative execution)
The if-else statement is also a two-way selection statement.
The if block of code is executed once the condition is true. The block of
code in the else statements is executed when the condition is false.
Syntax: Flow diagram
if condition:
Statement - 1
else:
Statement – 2

Example: Check the given


number is positive
or negative
n=int(input(“Enter the number”))
if n>0:
print(“Positive number”)
else:
print(“Negative number”)

6.2.3. if-elif-else
(chainedconditional)

Sometimes a program is faced with testing several conditions that entail


more than two alternative courses of action. One way to express a
computation like that is a chained conditional.
When a condition evaluates to True, the corresponding action is
performed and control skips to the end of the entire selection
statement. If no condition evaluates to True, then the action after
the trailing else is performed.
Syntax: Flow diagram
if condition-
1:
statement
-1
elif condition-2:
statement
-2 else:
stateme
nt-3

Example: To find biggest among 3


numbers a=int(input(“Enter
the value of a”))
b=int(input(“Enter the value of
b”)) c=int(input(“Enter the
value of c”))print(“A is a>c:
if a>b and
elif b>c: big)
print(“B is
big”)
else:
print(“C is
big”)
6.2.4. Nested conditionals
One conditional can also be nested within
another.
Syntax:
if condition:
statement
-1 else:
if
condition-
2:
statement
-2 else:
if
condition-
3:
st
ateme
nt-3
else:
st
ateme
nt-4

Flow diagram

Example:
m=int(input(“Enter the marks”))
if (m>=91) and (m<=100):
print(“O grade”)
else:
if (m>=81) and (m<=90):
print(“A+ grade”)
else:
if (m>=71) and (m<=80):
print(“A grade”)
else:
if (m>=61) and (m<=70):
print(“B+ grade”)
else:
if (m>=50) and
(m<=60):
print(“B grade”)
6.3 Iteration
ITERATION (Loop):
Iteration allows a statement or a sequence of
statements to be repeatedly executed based on some loop
condition.
There are two types of iterations –
definite iteration – It repeats an action a predefined
number of times
indefinite iteration – It repeats an action until the program
determines that it needs to stop.
Itertion Statements
1. while loop (while and while…else)
2. for loop (for and for…else)

1. while loop
 It is entry-controlled loop statement.
 Condition is evaluated first, if the condition is true, then body of
loop (set of statements) is executed.
 A while loop statement in Python programming language repeatedly
executes a target statement as long as a given condition is true.

Syntax
while expression or
condition: Statements

Flow diagram

Example: Sum of digits of a


number n=int(input(“Enter
the value of n”)) s=0
while(n>0):
r=n%10 s=s+r
n=n//1
0
print(s)
3.2.2. While loop with else
 Python supports to have an else statement associated with a loop
statement.
 If the else statement is used with a while loop, the else statement is
executed when
the condition becomes false.
Syntax:
while
condition:
statements
-1
else:
statements-2
Example:
count = 0
while count < 5:
print (count)
count = count
+1
else:
print (“while
ended”)

3.2.3. for loop


It has the ability to iterate
over the items of any
sequence, such as a list or a
string.
Syntax
for variable in
sequence:
statements(s)

Flow diagram

Example
(i) Iterating by Iterating through each
items: item
Example:
for a in
'Hello':
print (a)
(ii)Iterating by Sequence iterating through each item is by index
Index: offset
into the sequence itself
Example:
a = ['banana', 'apple',
'mango'] for i in
range(len(a)):
print (a[i])

(iii) Iterating by range:


Syntax
for variable in range
(start_index,end_index+1,step_value):
statements
Example 1 print(i) Output: 1 2 3 4
for i in range(1,5):

Example 2
for i in
range(5):
print(i)
Here, Output:
start_index will take from 0, step value0 is 1incremented
2 3 4
by 1.

Example 3
for i in range(1,5,2):
print(i) Output:
1 3
Here, step_value is 2, so the index is incremented by 2.

Example 4
for i in range(5,1,-1):
print(i) Output: 5 4 3
2 Here, step_value is -1, so the index is
decremented by 1.

3.2.4. for loop with else

Python supports to have an else statement associated with a loop


statement.
If the else statement is used with a for loop, the else statement is
executed when the
loop has exhausted iterating the list.
Example:
a = ['banana', 'apple',
'mango'] for i in
range(len(a)):
print
(a[i]) else:
print
3.3. Unconditional statements inPython
1. break
2. continue
3. Pass

1. break statement
 break statement will break a particular looping statement.
 It terminates the current loop and resumes execution at the next
statement.
 If you are using nested loops, the break statement stops the
execution of the innermost loop and start executing the
next line of code after the block.
for i in range(0,5):
Example if(i==2): Output
break 0
else: 1
print
(i)
Flow diagram

3.3.2. continue statement


 It returns the control to the beginning of the while loop. The continue
statement rejects all the remaining statements in the current iteration
of the loop and moves the control back to the top of the loop.
 The continue statement can be used in both while and for loops.

Example
for i in range(0,5):
if(i==2): Output
continu 0
e print 1
(i) 3
else:
print (i) 4
Flow Diagram
3.3.3. pass statement

 It is used when a statement is required syntactically but you do not


want any command or code to execute.
 The pass statement is a null operation; nothing happens when it
executes.
 The pass is also useful in places where your code will eventually go,
but has not been written yet (e.g., in stubs for example):
Example
for i in
range(0,4):
pass
if(i==2):
print(“pass
executed”)
else print (i)
:
print (i)
Output
0
1
Difference Between break and
continue

break continue

1. break statement 1. continue statement takes


breaks the current next iteration
looping statement

2. Control passes to 2. Control passes to the


the next statement of next iteration
the current looping
statement
3. Terminates the loop Never terminate the loop

Recursion vs Iteration

Recursion:

• Recursion is often more intuitive and easier to implement when the


problem is naturally recursive, like tree traversals.

• It can lead to solutions that are easier to understand compared to


iterative ones.

Iteration:

• Iteration involves loops (for, while) to repeat the execution of a block of


code.

• It is generally more memory-efficient as it does not involve multiple


stack frames like recursion.
QUESTION
BANK
PART-A

1. Define values and types

A value is one of the basic things in a programs like a letter or a number. The
values are belonging to different types. For example

>>> type(‘Hello’)

<type ‘str’>

>>> type(17)

<type ‘float’>

2. Define variables.

A variable is a name that refers to a value. They can contain both letters
and numbers but they do not begin with a letter. The underscore ‘_’ can
appear in a name.

Example:

>>> n=176

Here n is a variable name. The value of that variable is 176.

3. Define Boolean Operators.

A Boolean expression is an expression that is either true (or) false. The


Operator == which compares two operands and produces True if they are
equal otherwise it is false.

>>> 5==5

True

>>> 5==6

False
4. Define String

A string is a sequence of characters. We can access the character one at a


time.

>>> fruit=’banana’

>>> letter = fruit[0]

>>> print

letter Output:
B

5. Define List
List is a sequence of values. The values are characters in a list they can be
of any type. The values in a list are called elements.

Examples

[10,20,30,40] number List

[‘a’,’b’,’c’,’d’]-> Character List

[‘a’,20,5,25.5,[20,30]]-> Nested List

[]-> Empty List

6.What do you mean by mutable list.

The values in the list are changed . So it is called mutable list.

>>> n=[17,35]

>>> n[0]=5

>>>n=[5,35]-> n[0] is changed as 5.

7. Define Expression
An expression is a combination of values , variables and operators. A value
all by itself is considered an expression.

8. Define Tuples
A Tuple is a sequence of values. The values can be of any type, They are
indexed by integers.

Tuples are immutable. A tuple is a comma separated list of values.

>>> t=(‘a’,’b’,’c’)
9. What is the function of slice in tuple?

It prints the values from starting to end-1.

>>> t[1:3]

>>(‘a’,’b’)

10.Write a program for swapping of two


numbers? a=5

b=6

a,b=b,

print
(a,b)

11. Wh
at
are
diff
ere
nt
Me
mb
ers
hip
Op
era
tor
s
in
pyt
ho
n?

In –
Evalua
tes to
true, if
it finds
a
variabl
e in
the
15. What are the different types of arguments?
1.Function arguments

2.keyword arguments

3.Default arguments

4.variable length arguments.

16.Write the syntax for alternate

conditions and give example. syntax:


if
conditi
o n:
statem
e nt -
1
else:
statement – 2
n=int(input(“enter the
number”)) if n>0:
print(“
positive
number”)
else:
print(“
negative
number”)

17.Write the syntax for


Nested conditionals
One conditional can also be
nested within another.
Syntax:
if
condi
ti on:
state
m
ent-1
e
l
s
e
:
if
condi
ti on-
2:
state
m
18. . What is the main difference between for loop and
whileloop?

19. Python program for finding minimum element in a list


usingbuilt-in- function
num = [1, 3, 2, 8, 5, 10, 6]
print('Minimum is:', min(num))
output:
Minimum is : 1

20.What is the use of passStatement?


•Pass is used when a statement is required syntactically but you do
not want any command or code to execute.
• The pass statement is a null operation; nothing happens when it
executes.
• The pass is also useful in places where your code will eventually go, but
has not been written yet (e.g., in stubs for example):
Example
for i in
range(0,4):
if(i==2):
pass
print(“pas
s
execute
d”)
print (i)
else:
print (i)
Unit 1 – GATE TYPE Questions

1. What is the output of the following code and why?


a=3
b = 4.0
c=a+b
print(c, type(c))
Answer:
Output: 7.0 <class 'float'>
Explanation: a is an int, b is a float. When added, Python promotes the result to
the more general type float.

2. Predict the output of the following:


x = 10
y=3
print(x // y, x % y)
Answer:
Output: 3 1
Explanation:
// is floor division → 10 // 3 = 3
% gives remainder → 10 % 3 = 1
3. Explain the difference between == and is in Python with example.
Answer:
== checks value equality
is checks object identity
a = [1, 2]
b = [1, 2]
print(a == b) # True
print(a is b) # False
Here, a and b have the same content but are different objects in memory.

4. Rewrite the following using a while loop instead of for:


for i in range(3):
print(i)

61
Answer:
i=0
while i < 3:
print(i)
i += 1

5. What is the output of the following code snippet?

a=5

if a > 10:

print("Greater than 10")

elif a == 5:

print("Equal to 5")

else:

print("Other")

Answer:
Output: Equal to 5
Explanation: The condition a == 5 is True, so the corresponding block runs.

6. What is the output?

i=0

while i < 3:

print(i)

i += 1

While loop up to 3
Answer: 0 1 2

7. What is the output of:

for i in range(3):

print(i)

range(3) → 0 1 2
Answer: 0 1 2

8. How is elif used in Python?


Meaning of elif
Answer: a) Else-if
9. What is the output of:

x = 10

if x % 2 == 0:

print("Even")

else:

print("Odd")

x = 10 → Even
Answer: Even

10. Which data type is returned by: type(3.0 + 1)?


type(3.0 + 1) → float
Answer: float

11. What will be the output of the expression 3 + 4.5 in Python?

3 + 4.5
Answer: 7.5

12. What is the type of the result of 5 // 2?


Type of 5 // 2
Answer: int

13. What does 5 % 3 evaluate to in Python?


5%3
Answer: 2

14. What will 2 ** 3 ** 2 return?


2 ** 3 ** 2 → 2 ** 9
Answer: 512

15. Which of the following is an invalid variable name in Python?

Invalid variable name


Answer: b) 1value

16. What is the result of this code?

a = 10

b = 20

a, b = b, a

print(a, b)

Swap values
Answer: 20 10
17. What will be the output of the following code?

x=3

y=4

x, y = y, x + y

print(x, y)

Answer:
x = 4, y = 7
Explanation: Tuple unpacking is used. Right-hand side is evaluated first → (4, 7)

18. Which of the following is not a valid Python expression?

a) 3 + 4.5
b) "abc" + 3
c) True * 5
d) 7 // 2

Answer:
b) "abc" + 3 — TypeError: can't concatenate str and int

19. What is the type of the variable x in the following?

x = 3 > 2 and 5 < 10

Answer:
x is of type bool → True

20. What will be the output of the following?

print(3 * "abc")

Answer:
abcabcabc
PART B

1. Discuss about the various data types in Python with


example.

2. List the various operators in Python and explain each


with example.
3. In detail Explain about functions in Python.

4. Write a program to exchange values of two variables


in Python.

5. Write a program to circulate the values of n variable in


Python.

6. Write a program to find the distance between two


points in Python.

7. Write a program to find the gcd of two numbers in


python.
8. Write notes on Conditional statements with examples

9. Explain Looping statements in Python with examples


10. Explain the Python Environment for program
execution
PART B (GATE QUESTIONS)
1. Write a Python program that takes an integer n as input
and prints all prime numbers less than or equal to n. Also,
count and display how many prime numbers were found.
Requirements:
• Use a function is_prime(num) to check if a number is
prime.
• Use a loop to iterate from 2 to n.
• Use proper conditional statements.
• Show example input/output.
2. Write a recursive Python function sum_digits(n) that
returns the sum of digits of a number n. Then, using
iteration, print the sum of digits for numbers from 1 to m
(inclusive), where m is user input.
3. Write a Python program to accept a list of integers from
the user, and:
1. Find the maximum and minimum values.
2. Count how many numbers are even and how many are
odd.
3. Print the sum and average of all numbers.
Use: Functions, Loops, Conditionals.
4. Write a Python program to find the GCD (Greatest
Common Divisor) of two numbers using recursion.
Also, find the LCM (Least Common Multiple) using the GCD.
5. Write a Python program to accept a string and count the
number of:
• Uppercase letters
• Lowercase letters
• Digits
• Special characters (non-alphanumeric)
Use functions and appropriate built-in string methods.
PART B (GATE QUESTIONS)

6. Write a Python program that accepts a number n and


prints a right-angled triangle pattern using stars (*), like the
following: For input n = 4: Also, print the total number of
stars printed.
7. Write a Python program to compute the sum of even
Fibonacci numbers not exceeding a number N entered by
the user.
Use recursion to generate Fibonacci numbers, and
conditionals to filter even values.
8. Write a Python program that:
 Accepts names and marks of n students
 Prints average marks
 Prints names of student(s) who scored the highest
Use lists, loops, conditionals, and functions
9. Write a recursive Python function is_palindrome(s) that
checks whether a given string s is a palindrome (reads the
same forwards and backwards). Ignore case and spaces.
10. Write a recursive function power(base, exponent) to
compute base^exponent without using the ** operator or
loops.
PART C

1. Define recursion and iteration in Python. Explain how Python internally handles
recursion.
2. Write both recursive and iterative versions of the Fibonacci sequence generator.
3. Write a Python program that accepts two numbers from the user and performs the
following operations:
 Addition, Subtraction, Multiplication, Division, Floor Division, Modulus, and
Exponentiation.
 Display the result in a formatted table
4. Write a Python program that defines a global variable and modifies it inside a function
using the global keyword. Additionally:
 Use a local variable inside the function.
 Define another nested function that modifies a non-local variable.
5. Design a program that accepts a user input and performs the following:
 If the number is divisible by 3 and 5, print "FizzBuzz".
 If divisible by only 3, print "Fizz".
 If divisible by only 5, print "Buzz".
 Else, print the number.
6. Write two functions to compute the factorial of a number:
 One using recursion.
 One using iteration (for or while loop).
PART C (GATE QUESTIONS)
1. Write a Python program that takes an integer input from the user and:
Checks if it is a prime number.
Calculates the factorial of the number (using recursion).
If the number is even, prints all numbers from 0 to that number using a for loop.
If the number is odd, prints a countdown using a while loop.
Requirements:
Use functions to separate logic.
Include appropriate conditionals and type-checking.

2.Write a program that simulates a simple calculator with the following functionality:
Ask the user for two values and an operator (+, -, *, /).
Use conditional statements to perform the correct operation.
Handle invalid inputs using type checks and exception handling.
If the result is an integer, print whether it’s even or odd using conditionals.
If the result is float, print its square using a function.

3. Write a Python program that takes an integer input from the user and:
Checks if it is a prime number.
Calculates the factorial of the number (using recursion).
If the number is even, prints all numbers from 0 to that number using a for loop.
If the number is odd, prints a countdown using a while loop.
Requirements:
Use functions to separate logic.
Include appropriate conditionals and type-checking.

4. Write a Python program that:


Accepts a number and finds all of its factors using a loop.
Uses a function to check if a factor is prime.
Separates factors into two lists: prime and non-prime.
Prints both lists and their counts.

5 .Design a program where:


A recursive function generates the sum of the digits of a number.
An iterative function determines whether the resulting sum is even or odd.
Based on the parity (even/odd), a different message is printed.

6. Write a recursive function to find the sum of digits of a number. Then:


Check whether the result is even or odd.
If even, print "Lucky Number", else "Try Again".
ASSIGNMEN
T

1. Write a Python function that takes a name as input K3 CO1


and prints a greeting message.

2. Write a program that accepts marks as input and K3 CO1


uses if-elif-else to print:
•Grade A for marks >= 90
•Grade B for 80–89
•Grade C for 70–79
•Fail for marks < 70

3. Design a Python program that simulates a basic K3 CO1


ATM:
•User can check balance, deposit money, withdraw
money.
•Use conditionals, loops, and functions.

4. Write a program that: K3 CO1


•Uses recursion to reverse a string.
•Uses iteration to count the number of vowels in
that string.

5. Write a function that takes a number and returns: K3 CO1


•True if it is an Armstrong number.
•False otherwise.
Use both conditionals and loops.
Supportive Online
Courses
Sl. Courses link
No.
1 Programming for https://www.coursera.org/learn/python
Everybody
(Getting Started
with Python)

2 Learn Python 3 https://www.codecademy.com/learn/learn-pyt


hon-3
3 MITx: Introduction https://www.edx.org/learn/computer-science/
to Computer massachusetts-institute-of-technology-introd
Science and uction-to-computer-science-and-programmin
g-using-python
Programming
Using Python.

4 Programming in https://onlinecourses.swayam2.ac.in/cec22_
Python cs20/preview
Real Time Applications in
Day to Day life and to
Industry
Sl. No. Real Time Application

Python finds extensive real-time applications across various


1 industries due to its versatility, rich libraries, and ease of
use. Some key areas include:

Data Science and Machine Learning:

Python is a dominant language in these fields, used for real-time


data analysis, predictive modeling, and machine learning
applications. Libraries like Pandas, NumPy, Scikit-learn, and
TensorFlow facilitate tasks such as data manipulation, statistical
analysis, and model building for real-time predictions and
decision-making.

Web Development:
Python frameworks like Django and Flask are used to build
dynamic websites and web applications, including those
requiring real-time updates and interactions.

Financial Services:
In finance, Python is used for algorithmic trading, risk
management, and fraud detection. Its ability to handle large
datasets and perform complex calculations in real-time makes it
invaluable for financial institutions.

Manufacturing:
Python is employed for predictive maintenance in
manufacturing, where sensor data is analyzed in real-time to
predict equipment failures and minimize downtime.

Healthcare:
Python aids in predicting patient outcomes by analyzing patient
data in real-time, helping hospitals optimize resources and
improve patient care.
Real Time Applications in
Day to Day life and to
Industry
Sl. No. Real Time Application

Retail:
2 Retailers use Python for personalized product recommendations
by analyzing customer purchase histories and behavior in real-
time, enhancing customer experience and boosting sales.

Cybersecurity:
Python is used for real-time threat detection and security
monitoring, helping organizations identify and respond to cyber
threats promptly.

DevOps and Automation:


Python's scripting capabilities make it ideal for automating tasks
in DevOps, such as software testing, deployment, and
infrastructure management.

Internet of Things (IoT):


Python is used in IoT applications for data processing and
analysis from connected devices in real-time.
Content Beyond the
1.Syllabus
Advanced Arithmetic and Math Modules
Beyond:
 Use Python’s built-in math module: math.sqrt(), math.ceil(), math.floor(),
math.factorial(), etc.
 Explore the decimal and fractions modules for precision-based
operations.
 Bitwise operators: &, |, ^, <<, >> (used in system programming and
optimizations)
2. Strong Typing and Type Annotations
Beyond:
 Dynamic vs Static Typing
 Use type hints (Python 3.5+):
def add(a: int, b: int) -> int:
return a + b
Introduce isinstance() and type casting strategies for validation.
3. Expressions and Evaluation
Beyond:
 Use eval() and exec() for dynamic expression evaluation (with caution).
 Understand Python’s expression vs statement distinction in deeper
syntax contexts.
4. Lambda Functions (Anonymous Functions)
Beyond Functions:
 One-line functions for small tasks:
square = lambda x: x * x
 Use with map(), filter(), reduce()
5. Higher-Order Functions & Functional Programming
Beyond Functions:
 Functions as first-class objects: pass them as arguments, return from
other functions
 Use of:
o map() – apply a function to a list
o filter() – filter elements based on a condition
o reduce() – apply rolling computation (from functools)
ASSESSMENT SCHEDULE

Tentative schedule for the Assessment During


2025- 2026 odd semester

Name of
S.NO Start Date End Date Portion
the
Assessme
nt
1 FIAT 1 & 2 Unit
3 & Unit
2 SIAT

All Units
3 MODEL

75
PRESCRIBED TEXT BOOKS AND REFERENCE
BOOKS

TEXT BOOKS

1. Allen B. Downey, “Think Python: How to Think Like a Computer Scientist”, 2nd edition,
Updated for Python 3, Shroff/O‘Reilly Publishers, 2016
(http://greenteapress.com/wp/thinkpython/)
2. Martin C. Brown, Python: The Complete Reference, Mc-Graw Hill, (Unit 4 – Chapter 5,
Unit 5 – Chapter 7, 17)

REFERENCE BOOKS:

1. David Beazley, Brian K. Jones, Python Cookbook, O’Reilly, Third


Edition, 2013.
2. ReemaThareja, “Problem Solving and Programming with Python”,
2nd Edition, Oxford University Press 2019
3. Guido van Rossum and Fred L. Drake Jr, ―An Introduction to Python –
Revised and updated for Python 3.2, Network Theory Ltd., 2011.
4. John V Guttag, ―Introduction to Computation and Programming
Using Python”, Revised and expanded Edition, MIT Press, 2013
5. Robert Sedgewick, Kevin Wayne, Robert Dondero, ―Introduction to
Programming in Python: An Inter-Disciplinary Approach, Pearson
India Education Services Pvt. Ltd., 2016
6. Timothy A. Budd, ―Exploring Python, Mc-Graw Hill Education (India)
Private Ltd., 2015.
7. Kenneth A. Lambert, ―Fundamentals of Python: First Programs‖,
CENGAGE Learning, 2012
8. Charles Dierbach, ―Introduction to Computer Science using Python:
A Computational Problem-Solving Focus, Wiley India Edition, 2013.
9. Paul Gries, Jennifer Campbell and Jason Montojo, ―Practical
Programming: An Introduction to Computer Science using Python 3‖,
Second edition, Pragmatic Programmers, LLC, 2013

76
MINI PROJECT SUGGESTIONS
Reference: https://www.freecodecamp.org/news/python-projects-for-beginners/

1. Mini Calculator App: Use Arithmetic operators, functions,


conditionals, expressions
Description:
Build a simple command-line calculator that supports:
• Addition, subtraction, multiplication, division, modulus,
exponentiation
• Handles invalid inputs (e.g., divide by zero)
• Uses functions for each operation
2. Student Grade Management System: Use Variables,
conditionals, iteration, functions
Features:
 Input marks for subjects
 Calculate total, average, and grade
 Use if-elif-else to assign grade (A, B, C, Fail)
Option to display records for multiple students
3. Number Analyzer Tool: Use Functions, recursion, conditionals, arithmetic
Features:
 Accept a number and analyze:
o Even/odd
o Prime or not
o Factorial (recursively)
o Sum of digits (using loops)
4. ATM Machine Simulation: Use Functions, variables, conditionals, loops
Features:
 PIN authentication
 Options: Check balance, deposit, withdraw, exit
 Transaction history
 Use a loop to allow multiple transactions until exit
5. Pattern Printing Generator: Use Iteration (for/while loops), expressions
Features:
 Print different patterns based on user input:
 Pyramid
 Reverse pyramid
 Floyd’s triangle
 Use nested loops and menu-driven design 77
Thank
you

Disclaimer:

This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document through
email in error, please notify the system manager. This document contains
proprietary information and is intended only to the respective group / learning
community as intended. If you are not the addressee you should not disseminate,
distribute or copy through e-mail. Please notify the sender immediately by e-mail if
you have received this document by mistake and delete this document from your
system. If you are not the intended recipient you are notified that disclosing,
copying, distributing or taking any action in reliance on the contents of this
information is strictly prohibited.

You might also like