0% found this document useful (0 votes)
4 views35 pages

SP Unit-1 Complete Python Notes

The document provides an introduction to Python programming, covering its syntax, variables, keywords, comments, operators, and data types. It explains the basic rules for defining variables, the types of operators available, and the different data types supported by Python. Additionally, it discusses input and output statements, as well as the characteristics of various data structures such as lists, tuples, sets, and dictionaries.

Uploaded by

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

SP Unit-1 Complete Python Notes

The document provides an introduction to Python programming, covering its syntax, variables, keywords, comments, operators, and data types. It explains the basic rules for defining variables, the types of operators available, and the different data types supported by Python. Additionally, it discusses input and output statements, as well as the characteristics of various data structures such as lists, tuples, sets, and dictionaries.

Uploaded by

txicz78
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

KMEC/II/SP/Unit-1 P.

VAMSHI KRISHNA

UNIT-1
INTRODUCTION TO PYTHON PROGRAMMING
Python is a general purpose high level programming language.
Python was developed by Guido Van Rossam in 1991.
Currently we are using Python 3 version.
The name for the language was inspired by the BBC TV show Monty Python’s Flying Circus.

Basic Syntax
 Syntax refers to set of rules to write a statements in a programming language.
 In python we don’t need to specify the datatype name before a variable_name.
 Python uses indentation (tabs or spaces) for code blocks (if block, else block, function block
etc).
 Python is a case sensitive language. That means if we define a=10 which is different from
A=10. Python consider them as different variables.
 All the conditional statements and class definition statements in python ends with colon ( :
) symbol. The colon symbol represents the start of new block.
 Python provides several inbuilt keywords, we cannot use keywords for naming any of
variables, functions or classes etc.

Variables
A variable is a name that refers to a value. An assignment statement creates new variables and
gives them values.
Syntax: variable_name = value

Example:
 n=10
 section='CSE-C'
 percentage=90.55
To display the value of a variable, you can use a print statement:
print(n)
10
print(section)
CSE-C
print(percentage)
90.55

Rules for defining a variable name:


 A variable name contains alphabets, digits and underscore symbol only.
 A variable name may start with either alphabet or underscore symbol.
 We cannot use any other special character other than underscore in variable name.
 Variable name should not start with digits.

1
KMEC/II/SP/Unit-1 [Link] KRISHNA

 Variable names are case sensitive.


 We cannot use python keywords as variable names.
 There is no length limit for Python variable names.
Note: The underscore character (_) is often used to combine names with multiple words such
as page_number, first_name, last_name etc. In python, the system library codes and functions
are starts with underscore symbols.

The below variable names are valid:


 section_name='CSE-C'
 Book_name='Python Programming'
 marks1=60
The below variable names are invalid:
 1marks=60
 if=51 (if is a keyword we can not use keywords as variable name)
 price$=100 ($ is a special symbol we can not use it in variable name).

Keywords in Python
The Python interpreter uses keywords to recognize the structure of the program, and they
cannot be used as variable names.

Python reserves 35 keywords:


and del from None TRUE
as elif global nonlocal try
assert else if not while
break except import or with
class False in pass yield
continue finally is raise async
def for lambda return await
Comments
 Comments can be used to explain Python code.
 In python comments starts with either # or '''.
 # is used for single line comment where as ''' are used for multi line comments.
Example:
if a>10: # if a is greater than 10
v=5 # assign 5 to v

Operators and Expressions


Operator is a symbol that performs certain operations.
Expressions consist of values and operators, and they can always evaluate down to a single
value.

2
KMEC/II/SP/Unit-1 [Link] KRISHNA

Types of operators:
1. Arithmetic Operators
2. Relational Operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Special operators

Arithmetic operators
Arithmetic operators are used for performing mathematical calculations.

Operator Name Example Description


+ Addition 10+4 14 It adds two operands
- Subtraction 10-4 6 It subtracts two operands
* Multiplication 10*4 40 It multiplies two operands
/ Division 10/4 2.5 It return floating point value after division
// Floor division 10//4 2 It return quotient of division
% Modulus 10%4 2 It return the remainder of division
** Exponent 10**4 10000 It returns 10 to the power of 4 value.

Relational operators
Relational operators also called as comparison operators.

They are used to compare values and return a either True or False value based on the
comparison.

Operator Name Example Description


> Greater than 10>7 Returns True if a>b else returns False
< Less than 10<7 Returns True if a<b else returns False
>= Greater than or 10>=7 Returns True if a>=b else returns False
equal to
<= Less than or 10<=7 Returns True if a<=b else returns False
equal to
== Equals to 10==10 Returns True if a is equals to b else returns False
!= Not equals to 10!=7 Returns True if a is not equals to b else returns False

Note: In python relational operators can also applied between strings.


Example: 'Python'=='python' (False because P and p are not same in python)
'python'=='python' (True)

3
KMEC/II/SP/Unit-1 [Link] KRISHNA

Logical Operators
Logical operators are used to combine logical expressions and evaluate complex conditions.
There are three main logical operators: and, or and not.
and : It returns True only if all expressions are true. Otherwise, it returns False.
Example: a=10 b=20 c=15
a>b and a<c  False and True returns False
a<b and a<c  True and True returns True

or : It returns True if atleast one of the expressions is true. Returns False only if all expressions
are false.
a>b and a<c  False or True returns True
a>b and a>c  False or False  returns False

not : used to negate a logical expression. It reverses the value of the expression. If the
expression is True, the not operator returns False. If the expression is False, the not operator
returns True
Example: not True  False
not False  True

Bitwise operators
Bitwise operations performed on integer values. First the integer value will be converted
integers into binary value and then apply bitwise operators on each bit of a binary value. Finally
we get the output result in the form of integer only.
There are 6 bitwise operators in python:

Operator Name Example Description


& Bitwise and 4&5 It return 1 when both bits are 1 else 0
| Bitwise or 4|5 It return 1 when at least one bit is 1 else 0
~ Bitwise ~1 It return 0 if bit=1 , it returns 1 if bit=0
compliment
^ Bitwise XOR 4^5 It returns 1 if the bits are different, if bits are same
then return 0.
>> Bitwise Right 10 >> 1 Shifts the bits of the number to the left and fills 0 on
shift voids right as a result.
<< Bitwise left shift 10 << 1 Shifts the bits of the number to the right and fills 0
on voids left.

4
KMEC/II/SP/Unit-1 [Link] KRISHNA

Assignment Operators
The assignment operator (=) is used to assign value to the variable.
Example: a=10
The following is the list of all possible compound assignment operators in Python
+= -= *= /= %= //= **= &= |= ^=
Python allows multiple values are assigned to multiple variables in a single statement.
Example : a,b=10,20
Where a=10 and b=20.

Ternary operator
The ternary operator in Python allows us to perform conditional checks and assign values or
perform operations on a single line.
Syntax: Variable = Value1 if condition else Value2

If condition is True then Value1 will be assigned to variable else Value2 will be assigned to
the variable.
Example: max= a if a>b else b.

Special operators
The following are special operators: is, is not, in , not in.

is and is not are called identity operators.


They are used to compare the address of two variables in python.
Example:1
a=10
b=10
print(a is b) # The variables a and b are poiting to same value object
output: True

Example:2
a=10
b=20
print(a is not b) # The variables a and b are not poiting to same value object
output: True

in and not in operators are called membershiop operators.


They are used to check whether the given object present in the given collection.
in :Returns True if the given object present in the specified Collection
not in : Retruns True if the given object not present in the specified Collection

Example_1 : s='Python'
print('y' in s)
output: True

5
KMEC/II/SP/Unit-1 [Link] KRISHNA

Example_2: s='Python'

print('a' not in s)
output: True

Input statement: input()


input() is a function that is used to take input from the keyboard. When input() function is
called, the program stops and waits for the user to type something.
The default datatype for input() is string type.
Example:
s=input()
Python Programming

print(s)
output: Python Programming

Python allows us to pass a string to input to be displayed to the user before pause for the input
from keyboard. We can also add new line (\n) character in the input().
Example:
name=input('Enter your name')
vamshi

print(name)
vamshi
String is the default datatype of input() function, so if we want to take an integer value as input,
then we have to use int() to convert to integer from string.
Example:
number = int(input('Enter an integer:'))
Enter an integer:5
print(number)
5
Output statement: print()
print() is a function that is used to display the output on the console.
Case_1: print() without any arguments.
print() without any argument, just prints the new line character.
Example: print('Python Programming')
output: Python Programming
print('Python \nProgramming')
output: Python
Programming

Case_2: print() with arguments.


Example: a,b=10,20
print("The Values are :",a,b)
Output:
The Values are : 10 20

6
KMEC/II/SP/Unit-1 [Link] KRISHNA

Case 3: print() with argument and sep argument:


The values inside the print function are seperated by spaces.
If we want we can specify seperator by using "sep" attribute inside the print().
a,b,c=10,20,30
print(a,b,c,sep=',')
output: 10,20,30
print(a,b,c,sep=':')
output:- 10:20:30

Case_4: print() with end attribute.


The default end value for print() is new line (\n).
If we want multiple print() statements are to be displayed on same line, we have to use end
attribute value.
print("Python", end='')
print("Programming",end='')
output: Python Programming

Datatypes
 In python we don’t need to specify the type explicitly.
 Python will automatically assign the type after we assign a value to the variable.
 The following datatypes are supported by python:
 int, float, bool, complex, str, range, list, tuple, set, dict, bytes, bytearray, frozenset, None.
Note: type( variable_name ) is an inbuilt function that can display the what type of datatype
the variable belongs to.

int data type


int is used to represent integral values (positive and negative values).
Eg: i=10
print(i)
10
type(i)
<class 'int'>

float data type


float data type is used to represent floating point values (decimal values)
Eg: f=3.14
print(f)
3.14
type(f)
<class 'float'>
Eg: f=3.2e4
print(f) 32000.0

7
KMEC/II/SP/Unit-1 [Link] KRISHNA

bool data type


Boolean data type consists of only two values, they are True and False.
Both are keywords in python.
Eg: x=True
print(x)
True

type(x)
<class 'bool'>
c=10<20
print(c)
False

str data type


A String is a sequence of characters.
Any data that is enclosed within single quotes or double quotes or triple quotes they belongs to
string type in python.

Ex: s='Python'
s="Python"
type(s)
<class 'str'>
'' and " " are used to represent only single line strings.
For multi line string we need to use Triple quotes ( ''' ... ''')
Ex: s='''Python is a high level
programming language'''
A single character can also treated as str type.
Ex: ch='a'
type(ch)
<class 'str'>

complex Data Type


A complex number of the form a+bj is stroed into a variable.
Where a is real part of complex number and b is the imaginary part of the complex number.
Complex numbers are used in scientific applications.
Eg: c1= 10+5j
c2= 10+5.5j
c3= 0.3+0.6j
type(c1)
<class 'complex'>
We can retrieve real and imaginary part of complex number by using the following: c1= 10+5j

8
KMEC/II/SP/Unit-1 [Link] KRISHNA

[Link]
10
[Link]
5

List Data type


A list consists of comma-separated values enclosed in a pair of square brackets.
Syntax: variable_name=[value_1, value_2, ….., value_n]
Example: l=[10,20,30,40]
print(l)
Output: [10,5.6,3’abc’,True]
type(l)
<class ‘list’>
An empty list can be created by using the l=[].
Features of list:
1. List is mutable. We can add and delete elements in the list.
2. List consists heterogeneous objects are allowed.
3. List can have duplicate elements.
4. List uses indexing.

Tuple Data type


A tuple consists of comma-separated values either with or without brackets ( ).
Syntax: variable_name=(value_1, value_2, ….., value_n)
Example: t1=10,20,'a',False
t2=(10,20,'a',False)
print(t1)
Output: (10,20,'a',False)
print(t2)
Output: (10,20,'a',False)
type(t1)
<class ‘tuple’>
type(t2)
<class ‘tuple’>
An empty set can be created by using the t=().
Features of tuple:
1. Tuple is immutable. We cannot add and delete elements in the tuple.
2. Tuple consists heterogeneous objects are allowed.
3. Tuple can have duplicate elements.
4. Tuple uses indexing.

set data type


A set consists of comma-separated values that are enclosed within {}.
A set is an unordered collection that does not contain duplicate elements.
Syntax: variable_name={value_1, value_2, ….., value_n}
Example: s1={10,20,'a',False}

9
KMEC/II/SP/Unit-1 [Link] KRISHNA

print(s1)
Output: {10,20,'a',False}
type(s1)
<class ‘set’>
An empty set can be created by using the s=set().
Features of set:
1. Set is mutable. We can add and delete elements in the set.
2. Set consists heterogeneous objects are allowed.
3. Set does not contain duplicate elements.
4. Set doesn't use indexing.

Dictionary data type


A Dictionary consists of comma-separated values that are enclosed within {} but the elements
are represented in key value pairs.
Syntax: variable_name={key1:value_1, key2:value_2, ….., keyn: value_n}
Example: d1={101:'A',102:'B',103:'C'}
print(d1)
Output: {101:'A',102:'B',103:'C'}
type(d1)
<class ‘dict’>
An empty dictionary can be created by using the d={}.

Features of dictionary:
1. Dictionary is mutable. We can add and delete elements in the dictionary.
2. Dictionary consists heterogeneous objects are allowed.
3. Duplicate keys are not allowed but values can be duplicated.
4. If we are trying to insert an entry with duplicate key then old value will be replaced with
new value.

range() data type


range() is immutable, that means elements in the range() are not modified.
range( ) represents a sequence of numbers.
Syntax: range(start, stop, step)
The range() takes 3 arguments, namely start, stop and step value.
 Start value is inclusive and optional. Default start value is 0.
 Stop value is exclusive and mandatory.
 Step value is also optional, the default value is 1.
Ex: range(5) or range(0,5) or range(0,5,1) will produce same output : 0,1,2,3,4.

None Data Type


 None means nothing or No value associated.
 Python distinguishes between an uninitialized variable and the value None.
 An uninitialized variable is a variable that has not been assigned a value, whereas the value
None is a value that indicates “no value.”
 That means, if the value is not available,then to handle such type of cases None is used.

10
KMEC/II/SP/Unit-1 [Link] KRISHNA

Example: def m1():


a=10
print(m1())
Output: None
Collections and methods often return the value None, and you can test for the value None in
conditional logic.

Conditional statements
The conditional statement in python ends with colon (:) symbol.

if statement
if is a conditional statement that ends with colon (:) symbol.
Syntax:
if condition:
#statements
/#statements
If the condition is true then statements inside if are executed.
Example: if a>0:
print(“Positive integer”)

if else statement:
If there are only two choices then we go for if else construct.
If condition is true then the corresponding statements of if will be executed, otherwise else part
statements are executed.
Both if and else statements end with colon(:).
Syntax:
if condition :
#statement_if
else :
#statement_else
Example:
a=10
b=20
if a>b:
print("max=",a)
else:
print("max=",b)

if-elif-else statement:
If there are more than two choices then we go for if elif else construct.
All the statements of if , elif and else statements are ends with colon (:) symbol.
Syntax:
if conditon:
#if_statements
elif condition:

11
KMEC/II/SP/Unit-1 [Link] KRISHNA

#elif statements
else:
#else statements
Example:
a,b,c=10,20,30
if a>b and a>c:
print("max=",a)
elif b>c :
print("max=",b)
else:
print("max=",c)

Loops
 Loops are iterative statements or repetitive statements. If we want to repeat statements
multiple time then we use loops.
 Python supports for loop and while loop.

for loop
The statement of for loop in python ends with colon( : ).
Syntax:
for i in iterable:
#statements
 The iterable may be a sequence data or any collection such list, tuple, string etc.
 The statements inside the for loop is executed for every element present in the sequence.

Example_1: Print the characters in a string:


string='Python'
for char in string:
print(char)
output:
P
y
t
h
o
n

Example_2:Print the items in the list:


list = ['a', 'b', 'c']
for item in list:
print(item, end=' ')
output:
abc

12
KMEC/II/SP/Unit-1 [Link] KRISHNA

Example_3:Print first 5 natural numbers.


for i in range(1,6,1):
print(i, end=' ')
output:
12345

while loop
If we want to execute a group of statements iteratively until some condition false,then we
should go for while loop.
Syntax:
while condition :
#statements
 If the condition is true the statements inside of while are executed.
 If the condition is false, then the loop will be terminated.
Example_1: Program for printing for 5 natural numbers
i=1
while i<=5:
print(i, end= ' ')
i=i+1
output: 1 2 3 4 5

Example_2: Program for printing sum of digits in a positive integer.


n=int(input("Enter n:"))
sum=0
while n!=0:
rem=n%10
sum=sum+rem
n=int(n/10)
print("sum",sum)
output:
Enter n: 123
sum: 6

Nested loops
A loop within a loop is called nested loop.
Example_1: Program to print the following pattern.
1
12
123
1234
12345
for line in range(1,6,1):
for num in range(1,line+1,1):

13
KMEC/II/SP/Unit-1 [Link] KRISHNA

print(num,end='')
print()

Infinite loops
An infinite loop in Python is a loop that continues to execute indefinitely.
Syntax:
while True:
#statements
The condition True always evaluates to true, causing the loop to run forever.
Example_1:
while True:
print('Python')

 The above code print Python for infinite number of times. The loop will never terminate.
 Purpose of using infinite loops:
 We can terminate the infinite loops by using "break" statement.

break statement
 The break statement enables to exit from a loop.
 We can use break statement inside loops to break loop execution based on some condition.
Example_1: Write a python program to take an integer from user input() untill it receives a
negative integer.
while True:
n=int(input("Enter an integer:"))
if n<0:
print("Loop exited")
break
else:
print(n)

output:
Enter an integer:1
1
Enter an integer:5
5
Enter an integer:-3
Loop exited

The above program executed continuously for all positive numbersm, but when we give input
as negative number then the loop terminated.
So when we dont know how many number of time the loop will be executed and the loop
termination depends on some value, then we go for infinite loops.

14
KMEC/II/SP/Unit-1 [Link] KRISHNA

continue statement
 The continue statement essentially returns to the top of the loop and continues with the next
value of the loop variable.
 We can use continue statement to skip current iteration and continue next iteration.
Example_1: Write a program to print odd numbers.
for i in range(10):
if i%2==0:
continue
print(i, end=' ')
output: 1 3 5 7 9
The code will be skipped for all the even values of i.

Functions
 A function is a block of code in a program.
 A function is a named sequence of statements that performs a computation.
 When you define a function, you specify the name and the sequence of statements.
 The main advantage of functions is code Reusability.
 A function “takes” an argument or parameters and “returns” a result. The result is called
the return value.
 The parameters and return values are optional in function.
Python supports 2 types of functions:
1. Built in Functions
2. User Defined Functions

Built in Functions
 Python provides a number of important built-in functions that we can use without needing
to provide the function definition.
 These functions are used to solve common problems and included them in Python for
programmers to use.
Ex: len(), id(), input(), print(), eval() etc.

len():
 len() takes one object (iterator) as parameter, and returns the total number of elements in
that object or iterator.
 That means, len() returns a numeric value that denotes the number of items in the given list,
tuple, array, dictionary, etc.
 In case of string, it returns the total numbers of characters.
Example_1: s='Python'
len(s)
6
Example_2: l=[10,20,30,40]
len(l)
4

15
KMEC/II/SP/Unit-1 [Link] KRISHNA

type()
It is used to return the type of a variable.
Syntax: type(variable_name)
Example: a=10
type(a)
<class 'int'>

id()
It is used to get the address of the object.
Syntax: id(variable_name)
Example: a=10
id(a)
140710595070680

USER-DEFINED FUNCTIONS
 Apart from built_in functions python allows us to add user defined functions also.
 The functions which are written by programmers are called User defined functions.

The rules for defining a function:


1. Function blocks begin with the keyword def, followed by the function name and
parentheses.
2. Any input arguments should be placed within these parentheses.
3. The code block within every function starts with a colon (:) and is indented.
4. The statement return [expression] exits a function, passing back an expression to the caller.
5. A return statement with no arguments is the same as return None.
6. If a function does not specify the return statement, the function automatically returns None,
which is a special type of value in Python.
7. return statement is optional.
Syntax:
def function_name(list_of_parameters):
#statement_1
#statement_2
....
....
return value
function_name(list_of_parameters)
Note:
1. Once we write the definition of function we need to call the function by its name with
parameters_list.
2. def and return are keywords in python.
3. A Function can take input values as parameters and executes code inside function, and finally
returns output to the caller with return statement.

16
KMEC/II/SP/Unit-1 [Link] KRISHNA

Example_1: write a program that prints first 5 natural numbers without passing parameters
and return statement.

def natural():
for i in range(1,6,1):
print(i,end=' ')
natural()
output: 1 2 3 4 5

Example_2: write a program that prints prints the reverse of a given number by passing
parameters and using a return statement.

n=int(input("Enter integer:"))
def reverse(n):
rev=0
while n!=0:
rem=n%10
rev=rev*10+rem
n=n//10
return rev
r=reverse(n)
print("Reverse=",r)

output: Enter integer:123


Reverse= 321

Note_1: we can directly use reverse(n) in print statement directly, so the return value is
replaced with reverse(n) function.
Ex: print("Reverse=",reverse(n))

Specifying default values in a function


In a function we can specify default values.
Example_1:
def fun1(a, b=10):
print(a,b)
fun1(3)
output: (3, 10)

Example_2:
def fun2(book="Python"):
print(book,"Programming")
fun2()
output: Python Programming

Note:
1. If we don't pass any value as parameter to fun2() then only default value will be considered.
2. If we pass any value as parameter then the default value will be replaced.

17
KMEC/II/SP/Unit-1 [Link] KRISHNA

Example: fun2("Java")
output: Java Programming
3. The default will be passed as the last arguments. You cannot pass the normal parameters
after default parameters.

Functions with a variable number of arguments


Python enables you to define functions with a variable number of arguments. This functionality
is useful in many situations, such as computing the sum, average, or product of a set of
numbers.
#var_arg_fun.py
def sum(*values):
s=0
for i in values:
s=s+ i
return s
print("Sum:",sum())
print("Sum:",sum(10,20))
print("Sum:",sum(10,20,30))

output: Sum: 0
Sum: 30
Sum: 60

Returning Multiple Values from a Function


Python allows us to return multiple values in a function.
Example_1: Write a program that takes two arguments and return the values after adding,
subtracting and multiplying them.
def arithmetic(a,b):
add=a+b
sub=a-b
mul=a*b
return add,sub,mul
x,y,z=arithmetic(10,2)
print("Sum:",x)
print("Difference:",y)
print("product:",z)
output:
Sum: 12
Difference: 8
product: 20

pass statement
 pass is a keyword in python.
 pass essentially does nothing.

18
KMEC/II/SP/Unit-1 [Link] KRISHNA

 In python we want to write a function with no statement in it, then we write pass statement
inside the function.

Example_1: def fun():


fun()
output: Error

Example_2: def fun():


pass
fun()
output: No error will be given

pass can also be written inside the if statement.


Example_1: if True:
output: SyntaxError
Example_2: if True:
pass
Output: No error (valid statement)

Types of variables
Python supports 2 types of variables: Local variables, Global variables

Local variable:
A variable is local to a function if it is:
 a parameter of the function
 declared inside a function
 bound to a control structure (such as for, with, and except)
Local variables are available only for the function in which we declared it. That means a local
variable of one function cannot be accessed by other function.
def f1():
a=10
print(a) # valid
def f2():
print(a) #invalid
f1()
f2()

Global variable:
A variable that are declared outside a function are called global variables.
Example: a=10
def f1():
a=20
print("inside f1():",a)
def f2():
print("inside f2():",a)
f1()

19
KMEC/II/SP/Unit-1 [Link] KRISHNA

f2()
Output:
inside f1(): 20
inside f2(): 10

In the above program a=10 is global to both f1() and f2().


The value of variable a=10 can be accessed by both f1() and f2(), but if any changes made
inside the function can not reflect on the other functions.

global keyword:
We can use global keyword for the following 2 purposes:
1. To declare global variable inside function
2. To make global variable available to the function so that we can perform required
modifications
Example:
def f1():
global a
a=10
print("inside f1():",a)
def f2():
print("inside f2():",a)
f1()
f2()
Output:
inside f1(): 10
inside f2(): 10

Recursive Functions
A function that calls itself is known as Recursive Function.
The main advantages of recursive functions are:
1. We can reduce length of the code and improves readability
2. We can solve complex problems very easily.

Example_1: Program for printing factorial of a given number using recursion.


n=int(input("Enter n:"))
def factorial(n):
if n==0:
result=1
else:
result=n*factorial(n-1)
return result
print("Factorial:",factorial(n))
output:
Enter n:5
Factorial: 120

20
KMEC/II/SP/Unit-1 [Link] KRISHNA

Anonymous Functions or lambda functions


A function defined without a name called Anonymous functions.
 Anonymous functions are also called lambda functions or lambda expression, since they
are defined using lambda keyword.
 Anonymous functions are used for temporary (one time) purpose.
 Lambda functions are used to write concise code in python.
Syntax: lambda arguments_list: expression
Example: lamda x:x*5
Note: lambda is a function in python. In python functions are considered as objects, so need to
assign lambda function to some variable.
Example_1: Using lambda function to multiply 5 with a given number x.
f= lambda x:x*5
result(f(2))
print(result)

output: 10
Example_2: Using lambda function to multiply two integers.
f= lambda x,y:x*y
result(f(2,3))
print(result)

output: 6
Example_3: Using lambda function to find the maximum of two numbers.
f=lambda a,b:a if a>b else b
print(“Maximum=”, f(5,6))

output: Maximum= 6
Note:
1. In lambda functions we don’t need to write explicit return statement, internally lambda
function returns a value.
2. Python 3 supports iterators, such as filter(), map(), and reduce(), which are useful when you
need to iterate over the items in a list, create a dictionary, or extract a subset of a list.
3. lambda functions that are often used in combination with the functions filter(), map(), and
reduce().

map() function
The map() function is a built-in function that applies a function to each item in an iterable.
Syntax: map(function,sequence)

For every element present in the given sequence (list or range),it apply some modification and
generate new element with the required modification.

21
KMEC/II/SP/Unit-1 [Link] KRISHNA

Example: The function can be applied on each element of list and generates new list.

Example_1: Write a program that take a list of values and multiply each element of the list
with 2 using a fuction name multiply().
l=[1,2,3,4,5]
def multiply(x):
return 2*x
m=list(map(multiply,l))
print(m)
output: [2,4,6,8,10]
Example_2: Write a program that take a list of values and multiply each element of the list
with 2, using a lambda fuction.
l=[1,2,3,4,5]
m=list(map(lambda x:x*2,l))
print(m)
output: [2,4,6,8,10]

map() function can be applied on multiple lists. We need to make sure that the lists should have
same length.
Example: list1=[1,2,3,4]
list2=[5,6,7,8]
list3=list(map(lambda x,y:x*y,list1,list2))
print(list3)
output: [5,12,21,32]
Note: In the above program x takes the values from list1 and y takes the values from list2.

filter() function
The filter() function allows you to extract a subset of values based on conditional logic.
Syntax: filter( function, sequence)

Where the sequence can be any of tuple, list, string.


Example_1: Write a program that take a list of values and create list of even numbers using
function even().
def even_fun(x):
if x%2==0:
return True

22
KMEC/II/SP/Unit-1 [Link] KRISHNA

else:
return False
l=[1,2,3,4,5,6]
even_list=list(filter(even_fun,l))
print(even_list)
output: [2, 4, 6]
Example_2: Write a program that take a list of values and create list of even numbers using
lambda function.
l=[1,2,3,4,5,6]
even_list=list(filter(lambda x:x%2==0,l))
print(even_list)
output: [2, 4, 6]

reduce() function
The reduce() function reduces sequence of elements into a single element by applying the
specified function.
Syntax: reduce(function,sequence)

reduce() function present in functools module.


If we want to use reduce() function first we need to import the functools module by using either
of the following statements:
1. from functools import reduce
2. from functools import *
3. import functools
Example: Write a program to find sum of all integers items in the list using lambda function.
from functools import reduce
l=[1,2,3,4,5]
sum=reduce(lambda x,y:x+y,l)
print("Sum=",sum)
output: Sum= 15
Example: Write a program to find sum of first 10 natural numbers.
from functools import reduce
sum=reduce(lambda x,y:x+y,range(1,11))
print("Sum_natural=",sum)
output: Sum_natural= 55

23
KMEC/II/SP/Unit-1 [Link] KRISHNA

Modules
A module in Python is a file containing Python code (functions, classes, or variables) that can
be reused in other programs.
• It helps organize large programs into smaller, manageable pieces.
• It avoids code duplication and improves reusability

Every Python file (.py) acts as a module.


Inorder to use the module we need to use the keyword "import".

Types of Modules:
1. Built_in 2. User Defined 3. Third party Modules

Built_in modules
Python provides several inbuilt modules such as random, math,datetime, os,sys,time etc.
Example:
import math
print([Link](25))
5.0
print([Link](8))
2.0

User Defined Modules


 Python also allows users to create their own User defined modules.
 Every Python file (.py) acts as a module.
 To create a user defined module, first we need to create a python file.
Consider the below program "[Link]" that have three functions sum(), sub(), mul() and
we can use the python program file as module in other program.
#[Link]
def sum(a,b):
print("Sum:",a+b)
def sub(a,b):
print("Subtraction:",a-b)
def mul(a,b):
print("product:",a*b)

#use_module.py
import arithmetic
[Link](10,20)
[Link](10,20)
[Link](10,20)

output: python use_module.py


Sum: 30
Sum: -10
Sum: 200

24
KMEC/II/SP/Unit-1 [Link] KRISHNA

Third party Modules


Python allows install third party modules using pip.
To install numpy module we need to use the following statement.
pip install numpy
After installing numpy we can use it as builtin module using import keyword.
Example : import numpy

Renaming a module
A module can be renamed using the keyword "as"
Example: rename arithmetic module with new name "a".
import arithmetic as a
[Link](10,20)
[Link](10,20)
[Link](10,20)

output: >>>python use_module.py


Sum: 30
Sum: -10
Sum: 200

from keyword
We can also import a module using "from" keyword.
Advantage: We can access members directly without using module name.
Example: from arithmetic import *
sum(10,20)
sub(10,20)
mul(10,20)
output: >>>python use_module.py
Sum: 30
Sum: -10
Sum: 200

The statement from arithmetic import *, imports all members (variables and functions) of a
module. We can import a specific function in a module as follows:
from arithmetic import sum
sum(10,20)
output:
sum: 30

PYTHON STANDARD MODULES


random module:
This module is used to generate random values such as integers, floating piont values.
random module consists of several inbuilt functions.
Floating point functions:
1. random()--> return random floating point value inbetween 0 & 1.
2. uniform(x,y) --> return random floating point value between x and Y.

25
KMEC/II/SP/Unit-1 [Link] KRISHNA

import random
[Link]()
0.12570589738398708
[Link](1,10)
2.7490802349697097

Integer functions:
1. randint(start, stop)--> returns random integer value between start value and stop value where
stop value is also included.
2. randrange(start, stop, step): return random integer value between start value and stop value
(with help of step value) where stop value is not included.
import random
[Link](1,10)
5
[Link](1,10)
5

Iterable functions:
1. choice(sequence): returns a random element from the given sequence data. Sequence may
be a range(), string, list, tuple or belongs any of sequence type variable.
2. shuffle(list): returns the list with values to be swapped in random order.

Note: The argument must be list or list values only. Because list is mutable where as string,
tuple are immutable and set and dictionary doesnot support indexing so swapping is not
possible.
Example: import random
l=['A','B','C','D','E']
[Link](l)
'B'
[Link](l)
print(l)
['A', 'E', 'D', 'C', 'B']
math module:
This module provides several inbuilt functions for mathematical operations such as square root
and cube roots, logarithmic, and trigonometric functions.
Example: sqrt(), cbrt(), ceil(), floor(),log(),sin(),cos() etc
import math
[Link](25)
5.0
[Link](8)
2.0
[Link](2.56)
3
[Link](2.56)
2

26
KMEC/II/SP/Unit-1 [Link] KRISHNA

Operator precedence
Operator precedence decide which operator is evaluated first when multiple operators are
present in a single line of expression.
Operators with higher precedence are evaluated before those with lower precedence.
When operators have the same precedence, their associativity dictates the order of
evaluation, most operators have left-to-right associativity, except for a few like
exponentiation (**), which have right-to-left associativity.
Precedence
Operator(s) Description Associativity
Level
1 () Parentheses (grouping) Left-to-right
x[index],
Subscription, slicing, function call,
2 x[index:index], x(...), Left-to-right
attribute reference
[Link]
3 await x Await expression N/A
4 ** Exponentiation Right-to-left
Positive, negative, bitwise NOT (unary
5 +x, -x, ~x Right-to-left
operators)
Multiplication, matrix multiplication,
6 *, @, /, //, % Left-to-right
division, floor division, remainder
7 +, - Addition and subtraction Left-to-right
8 <<, >> Bitwise left and right shifts Left-to-right
9 & Bitwise AND Left-to-right
10 ^ Bitwise XOR Left-to-right
11 | Bitwise OR Left-to-right
in, not in, is, is not, <, Comparisons, including membership
12 Left-to-right
<=, >, >=, !=, == and identity tests
13 not x Boolean NOT Right-to-left
14 and Boolean AND Left-to-right
15 or Boolean OR Left-to-right
16 if-else Conditional expressions Right-to-left
17 lambda Lambda expressions N/A
Assignment expressions (walrus
18 = Right-to-left
operator)

Example_1: 6*3/4  4.5


Here * is executed then / is executed, because * comes first because * , / have same
precedence.
Example_2: 6/3*4  8.0
In the above example first / is executed then * is executed, because / comes first and /
because * have same precedence.
Example_3: 2*3+4**3  70
In the above example first 4**3 is executed then 2*3 is executed because ** have high
precedence than *.

27
KMEC/II/SP/Unit-1 [Link] KRISHNA

INTRODUCTION TO SCIENTIFIC PROGRAMMING

Overview of Scientific Computing


Scientific computing is a multidisciplinary field that applies advanced computing techniques,
numerical methods, and mathematical models to solve complex scientific and engineering
problems. It is essential for simulations, data analysis, and problem-solving in fields like
physics, biology, chemistry, engineering, and finance.

Applications of Python

1. Numerical Methods & Algorithms


Scientific computing relies on numerical methods to approximate solutions to mathematical
problems that cannot be solved analytically. Common numerical techniques include:
 Linear Algebra – Matrix operations, eigenvalue problems (used in physics, engineering,
AI).
 Optimization – Finding minima or maxima (used in machine learning, finance).
 Differential Equations – Solving ODEs and PDEs (used in fluid dynamics, climate
modeling).
 Fourier Analysis – Signal processing, image processing.

2. High-Performance Computing (HPC)


Large-scale scientific problems require immense computational power. High-performance
computing techniques involve:
 Parallel Computing – Distributing tasks across multiple processors.
 Supercomputers & Clusters – Machines designed for large-scale calculations.
 Cloud Computing – Scalable computational resources.

3. Scientific Programming Languages


Several programming languages and frameworks are widely used:
 Python (NumPy, SciPy, TensorFlow, Pandas)
 MATLAB (Widely used in academia and industry for simulations)
 C/C++ (High-performance applications)
 Fortran (Legacy scientific computing language, still widely used in physics and
engineering)
 Julia (Emerging language optimized for numerical computing)

4. Simulation & Modeling


Scientific computing enables realistic simulations in various fields:
 Climate Models – Predicting weather and climate changes.
 Molecular Dynamics – Studying chemical and biological interactions.
 Computational Fluid Dynamics (CFD) – Simulating airflow, liquid flow.
 Astrophysical Simulations – Studying galaxy formation, black holes.

5. Data Science & Machine Learning in Scientific Computing


 Big Data Analysis – Handling large datasets in genomics, physics, and astronomy.
 Machine Learning & AI – Predictive modeling, neural networks for pattern recognition.

28
KMEC/II/SP/Unit-1 [Link] KRISHNA

 Monte Carlo Methods – Probabilistic simulations in finance, physics, and biology.

6. Applications of Scientific Computing


 Physics – Particle simulations, quantum mechanics.
 Biology & Medicine – Genome sequencing, drug discovery, epidemiology.
 Engineering – Structural analysis, robotics.
 Finance – Risk modeling, quantitative analysis.

Conclusion
Scientific computing is an indispensable field that bridges mathematics, computer science, and
domain-specific sciences to enable cutting-edge discoveries and innovations. It is the backbone
of modern research and technological advancements, making it a critical area of study for
scientists, engineers, and data analysts.

String Data Structure


A String is a sequence of characters. Any data that is enclosed within single quotes or double
quotes or triple quotes they belongs to string type in python.
Ex: s='Python'
s="Python"
type(s)
<class 'str'>
' ' and " " are used to represent only single line strings.
For multi-line string we need to use Triple quotes ( ''' ... ''')

Ex: s='''Python is a high level


programming language'''
A single character can also treated as str type.
Ex: ch='a'
type(ch)
<class 'str'>
Strings are immutable. We cannot change the existing string. If we try to change the string then
a new string object is created with the changes but the original string will remain unchanged.

Arithmetic operators on Strings: + and *


String concatenation: + is used to concatenate two strings where as * is used to multiply the
string.
Example_1: 'abc'+'xyz'

Output: 'abcxyz'
When we perform string concatenation with + operator we need to make sure that both the
objects must be string type only, otherwise we will get error.

String multiplication: * is used to print the string multiple times.


Example: 'abc'*3
Output: 'abcabcabc'
Here one object must be a string and other must be an integer only, otherwise we will get error.

29
KMEC/II/SP/Unit-1 [Link] KRISHNA

String unpacking
We can “unpack” the letters of a string and assign them to variables.
Example: s = "abc"
x,y,z=s
print('x=',x,'y=',y,'z=',z)
output: x=a y=b z=c

Comparison operators on strings


We can use > >= < <= == and != are used to compare the string.
Comparison will be performed based on alphabetical order.
Python is a case sensitive language, here capital letters and small letters are not same.
That means: 'p' is different from 'P'. Hence 'Python' is not same as 'python'.
Example: s1='Python'
s2='python'
s1==s2 s1>s2 s1<s2 s1!=s2
False False True True

Membership operators
Using "in" and "not in" operator We can check whether the character or string is present in
the given string or not.
Let s='Python'
Example_1: 'P' in s
True

Example_2: 'th' in s
True

Example_3: 'yto' in s
False
Example_4: 'a' not in s
True

Write a program that access string characters using indexing.


s='Python'
for i in s:
print(i)
output:
P
y
t
h
o
n

String length
Len() is used to find the total number of characters in a string.
Example: s='abcd'
print("Length=",len(s))
output: Length= 4

30
KMEC/II/SP/Unit-1 [Link] KRISHNA

Indexing in strings
 String characters accessed by using index values of string.
 Python supports positive and negative indexing.
 Positive indexing traverse from left to right. Positive index values always starts from 0
from the left side.
 Negative indexing traverse from right to left. Negative index values always starts from -1
from the left side.
Example: s='Python'
-6 -5 -4 -3 -2 -1
P y t h o n
0 1 2 3 4 5

s[0] s[1] s[2] s[3] s[4] s[5]


output: P output: y output: t output: h output: o output: n

s[-1] s[-2] s[-3] s[-4] s[-5] s[-6]


output: n output: o output: h output: t output: y output: P
Write a program to access string characters using index values.
s='Python'
for i in range(len(s)):
print(s[i])
output:
P
y
t
h
o
n

Slicing in Strings
We can extract substring of a string using slicing operators [:].
Syntax: string_name[start : stop : step]
 The start value in inclusive and default start value=0. It is optional
 The stop value is end value, it is exclusive.
 The step value is increment value, the default step value=1. It is optional.
Slicing supports both positive index as well as negative index.
 If step value is positive (i.e. step=1) , then it operates on the left to right direction.
 If step value is negative (i.e. step=-1) , then it operates on the right to left direction.

Examples:
To access first 3 characters of string, we can use:
s[0:3:1]  'Pyt'
s[:3:]  'Pyt'
To access entire string we can use:
s[::]  'Python'
To access string in reverse order (right to left):
s[::-1]  'nohtyP'

31
KMEC/II/SP/Unit-1 [Link] KRISHNA

Access string characters from index 1 to 3 from left to right.


s[1:4]  'yth'
Access string characters from index -1 to -4 from right to left.
s[-1:-4:-1] 'noh'

String functions
Find substrings:
 find() and index() are used to find substring in forward direction.
 rfind() and rindex()are used to find substring in backward direction.
find(): It returns index of first occurrence of the given substring.
If the substring is not available then -1 will be returned.
Example: s='Python Programming'
[Link]('Python')
0
[Link]('thon')
2
[Link]('java')
-1
We can also specify the boundaries to search using slicing operator.
[Link]('Pro',4,11)
7
The above function dictates find the substring 'Pro' from index 4 to 10.

rfind(): is used to find substring in backward direction.


[Link]('Pro')
7
index() and rindex():
These methods returns index of first occurrence if substring is found otherwise it returns
error.
[Link]('Pro')
7
[Link]('yth')
1
[Link]('ong')
ValueError: substring not found
To remove spaces in a string:
strip() , rstrip(), lstrip() are 3 functions used to remove spaces in a string.
strip(): Removes leading and trailing white spaces.
 leading means left most side and trailing means right most side.
 The middle spaces will remain unchanged with strip functions.
case_1: If we don't give any argument inside strip() then it removes white spaces by default.
s=' abcd efgh '
[Link]()
'abcd efgh'

32
KMEC/II/SP/Unit-1 [Link] KRISHNA

' Python Programming '.strip()


'Python Programming'
rstrip(): Removes trailing white spaces
' Python Programming '.rstrip()
' Python Programming'
lstrip(): Removes leading white spaces.
' Python Programming '.lstrip()
'Python Programming '
case_2: used to remove characters that are given as arguments in strip().
s='*** Python ***'
[Link]('*')
' Python '
[Link]('*')
' Python ***'
[Link]('*')
'*** Python '
Note: White spaces are not deleted here, because we have provided the character that we
want to delete.
s='Python Programming'
[Link]("Ping")
'ython Programm'
[Link]("Ping")
'ython Programming'
[Link]("Ping")
'Python Programm'
Counting substring: count( )
Count() is used to find the number of occurrences of substring present in the given string.
s='malayalam'
[Link]('al')
2
[Link]('a')
4
replace( ): Used to replace a specified string with another string.
Syntax: [Link](oldstring,newstring,count)
Example_1: s='Python Programming'
[Link]('Python','Java')
'Java Programming'
Example_2: s='Python is a programming language'
[Link](' ','-')
'Python-is-a-programming-language'
[Link](' ','-',2)
'Python-is-a programming language'

33
KMEC/II/SP/Unit-1 [Link] KRISHNA

Splitting of Strings
split() function is used to divide the given string according to specified separator given as argument.
split(): convert string to list by splitting the string from left to right side.
Syntax: split( seperator, maxsplit )
Note : If we don’t specify any separator then by default it take ‘space’ as separator.
s="Python Programming"
[Link]()
['Python', 'Programming']
Example: price=100$200$300$400$
[Link]('$')
['100', '200', '300', '400', '']
[Link]('$',maxsplit=2)
['100', '200', '300$400$']
rsplit(): convert string to list by splitting the string from the right to left side.
Syntax: rsplit( separator, maxsplit)
Example: grade='A,B,C,D,F'
[Link](',')
['A', 'B', 'C', 'D', 'F']
[Link](',',maxsplit=2)
['A,B,C', 'D', 'F']
Joining of Strings
join(): Combine elements from iterable (list or tuple) with respect to seperator.
Syntax: 'seperator'.join(iterable)
Condtion: The iterable must contains only characters.
Example_1: l= ['Python', 'Programming']
''.join(l)
'PythonProgramming'
' '.join(l)
'Python Programming'
'-'.join(l)
'Python-Programming'
Example_2: marks={'Physics':86, 'Chemistry':70}
' and '.join(marks)
'Physics and Chemistry'
Note: If we give dictionary as argument in join(), it only joins keys, values of dictionary are ignored.

String conversion functions


Consider: s='Python programming'
Name Output Description
[Link]() 'PYTHON convert all characters to upper case
PROGRAMMING'
[Link]() 'python programming' convert all characters to lower case
[Link]() 'Python Programming' convert all characters to title case

34
KMEC/II/SP/Unit-1 [Link] KRISHNA

[Link]() 'pYTHON PROGRAMMING' converts all lower case to upper case


and upper case characters to lower case
[Link]() 'Python programming' Only first character will be converted
to upper case and all remaining
characters can be converted to lower
case

Check for type of characters


These functions are used to check if all the characters in a string have specific type or not.
Name Output Description
'Python3'.isalnum() True Checks if all characters are alphanumeric(a-z ,A-Z
,0-9 )
'Python'.isalpha() True Checks if all characters are only alphabets(a-z ,A-Z)
'Python3'.isdigit() False Checks if all characters are digits only( 0 to 9)
'563'.isdigit() True
'python'.islower() True Checks if all characters are lower case alphabets
'Python3'.islower() False
'[Link]() True Checks if all characters are upper case alphabets
'Python Program'.istitle() True Checks if string is in title case
' '.isspace() True Checks if string contains only spaces
[Link]('Pyt') True Checking starting with substring
[Link]('ing') True Checking ends with substring

35

You might also like