0% found this document useful (0 votes)
16 views

python 2025

This document provides an introduction to Python programming, detailing its features, applications, and installation methods. It covers fundamental concepts such as data types, operators, and programming modes, along with examples of Python code. Additionally, it discusses the importance of comments, indentation, and user input in Python programming.

Uploaded by

ghademandar
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)
16 views

python 2025

This document provides an introduction to Python programming, detailing its features, applications, and installation methods. It covers fundamental concepts such as data types, operators, and programming modes, along with examples of Python code. Additionally, it discusses the importance of comments, indentation, and user input in Python programming.

Uploaded by

ghademandar
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
You are on page 1/ 66

Python Programming

Prof. Parmeshwar Paul


Assistant Professor
Mechanical Engineering Department,
Rajiv Gandhi Institute of Technology, Versova, Andheri (W), Mumbai-53

E-Mail : parmeshwar.paul@mctrgit.ac.in

PROF. P. R. PAUL (ASST. PROFESSOR, RGIT, MUMBAI) 1


Python Programming, January 2023

Introduction to Python

Translator
(Compiler / Interpreter)

Python

❑ Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming


language.

❑ It was created by Guido van Rossum during 1985- 1990.

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 2


Python Programming, January 2023

Features of Python:
1. Python is interpreted language vs C, C++, Java

2. It is very easy to understand

3. Quick debugging

4. Short & compact code

5. Open source & no license is needed

6. Platform independent (runs on any OS)

7. Time saver coding

8. It supports OOP, multithreading, file handling etc.

9. Python provides huge set of libraries (web dev, data science, data analysis, AI & ML etc.)

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 3


Python Programming, January 2023

Applications of Python Programming:


Python supports cross-platform operating systems which makes building applications with it all the more
convenient. Some of the globally known applications such as YouTube, BitTorrent, DropBox, etc. use Python to
achieve their functionality.
1. Web Development

2. Game Development PySoy PyGame


Games such as Civilization-IV, Disney’s Toontown Online, Vega Strike etc. have been built using Python
3. Machine Learning and Artificial Intelligence
libraries such as Pandas, Scikit-Learn, NumPy and so many more
4. Data Science and Data Visualization
libraries such as Matplotlib, Seaborn, which are helpful in plotting graphs and much more.
5. Desktop GUI
Tkinter library, wxWidgets, Kivy, PYQT
6. Business Applications
7. Audio and Video Applications
8. CAD Applications

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 4


Python Programming, January 2024

Installation of Latest Version of Python on windows

Interactive Mode Programming


Interactive mode is where you type your code into the Python interpreter directly. This is useful for
trying out small snippets of code, or for testing things out as you’re writing them.

Script Mode Programming


Script mode is where you write your code in a .py file and then run it with the python command.
This is the most common way that people use Python because it lets you write and save your code
so that you can use it again later.

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 5


Python Programming, January 2024

Comments :
• Comments can be used to explain Python code.
• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code

Multiline Comments

Python does not really have a syntax for multiline comments.


To add a multiline comment you could insert a # for each line:

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 6


Python Programming, January 2024

Python Tokens: ❖ Smallest meaningful component in a program

1. Keywords Python has 35 keywords, also known as reserved words:

2. Variables/Identifier
Data/value can be stored in temporary storage spaces called variables. Variables are containers for storing data.

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 7


Python Programming, January 2024

Identifier
myvar = "John"
Names used for variables, functions, class or objects.
my_var = "John"
Rules:
_my_var = "John"
1. Identifiers can be started with underscore (_)
myVar = "John"
2. Identifiers are case sensitive: e.g., S & s are two different variables
MYVAR = "John"
3. First letter cannot be a digit
myvar2 = "John"
4. Python does not allow punctuation characters such as @, $, and % within identifiers.

age = 25
name = "PARAM"
print(age)
print(name)
print("My age is:" , age)
print("My name is: " , name)

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 8


Python Programming, January 2024

Data Types
❖ Every variable is associated with data type

Numeric Types: int, float, complex


Sequence Types: list, tuple, string, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType

10, 20, 500, 3.14, 17.15 True, False 3+2j, 5 -2i Hello World

Integer Float Boolean Complex String

NOTE: j is used in python for imaginary part

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 9


Python Programming, January 2024

Many Values to Multiple Variables


Python allows you to assign values to multiple variables in one line:

Note: Make sure the number of variables matches the number of values, or else you will get an error.
One Value to Multiple Variables
you can assign the same value to multiple variables in one line:

Unpack a Collection
If you have a collection of values in a list, tuple etc.
Python allows you to extract the values into variables.
This is called unpacking.

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 10


Python Programming, January 2024

Swapping Variables
a,b = 'red','blue'
Swapping means interchanging values. a,b = b,a
print(a,b)

Deleting Variables
a=5;
print(a) Casting
del a
print(a) x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

x = float(1) # x will be 1.0


name = "Rajesh" y = float(2.8) # y will be 2.8
age = 35 z = float("3") # z will be 3.0
height = 5.7 w = float("4.2") # w will be 4.2
print(type(name))
print(type(age))
print(type(height)) x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 11


Python Programming, January 2024

Type Conversion: The process of changing the data type of a value from one type to another.

i. Conversion: ii. Casting

a = 5 x = int(1) # x will be 1
b = 3.5 y = int(2.8) # y will be 2
sum = a + b z = int("3") # z will be 3
print(sum)

x = float(1) # x will be 1.0


y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2

x = str("s1") # x will be 's1'


y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 12


Python Programming, January 2024

3. Operators:
❑ Operators are used to perform operations on variables and values

1. Arithmetic Operator: ( +, -, * , /,//, %, **power, e.g. 34: 3**4 )


2. Relational Operator: ( <, >, ==, !=, >=, <= )
3. Logical Operator: ( & , | )
4. Assignment Operator: ( =, +=, -=, *=, /=, **= , %=, //=)

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 13


Python Programming, January 2024

1. Arithmetic Operator: ( +, -, * , /,//, %, **power, e.g. 34: 3**4 )

a = 7
b = 2

# addition
print ('Sum: ', a + b) Sum: 9
# subtraction
print ('Subtraction: ', a - b) Subtraction: 5
# multiplication
print ('Multiplication: ', a * b) Multiplication: 14
# division
print ('Division: ', a / b) Division: 3.5
# floor division
print ('Floor Division: ', a // b) Floor Division: 3
# modulo
print ('Modulo: ', a % b) Modulo: 1
# a to the power b
print ('Power: ', a ** b) Power: 49

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 14


Python Programming, January 2024

2. Relational/Comparison Operator: ( <, >, ==, !=, >=, <= )


a = 5
b = 2

# equal to operator
print('a == b =', a == b) a == b = False

# not equal to operator


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

# greater than operator


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

# less than operator


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

# greater than or equal to operator


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

# less than or equal to operator


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

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 15


Python Programming, January 2024

3. Assignment Operator: ( =, +=, -=, *=, /=, **= , %=, //=)

Operator Example Same As


= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 16


Python Programming, January 2023

4. Logical Operator: ( and , or, not )

# logical AND
print(True and True) # True
print(True and False) # False

# logical OR
print(True or False) # True

# logical NOT
print(not True) # False

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 17


Python Programming, January 2023

4. Python Indentation
Indentation refers to the spaces at the beginning of a code line
The indentation in Python is very important.
Python uses indentation to indicate a block of code. Python will give you an error if you skip the indentation
The number of spaces is up to you as a programmer, but it has to be at least one. You have to use the same
number of spaces in the same block of code, otherwise Python will give you an error.

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 18


Python Programming, January 2024

Python input function


Developers often have a need to interact with users, either to get data or to provide some sort of result. Python
provides us inbuilt function to read the input from the keyboard.
input ( ) : This function first takes the input from the user

Example: Take the two numbers from user and display its addition

a = int(input("Enter a first number:"))


b = int(input("Enter a second number:"))
c = a + b
print("The sum = ", c)

a = input("Enter a first number:")


b = input("Enter a second number:")
c = a + b
print("The sum = ", c)

Note: by default result for input function is always string

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 19


Python Programming, January 2024

1. Write a Program to input two numbers & print their sum

2. Write a Program to input side of a square & print its area

3. Write a Program to input two floating point numbers & print their average

3. WAP to input two integer numbers , a & b. Print True if a is greater than or
equal to b. If not print False

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 20


Python Programming, January 2024

❖ String is data type that stores a sequence of characters.


❖ It can be enclosed in a single or double quotation mark.
name = 'Parmeshwar'
name1 = "Parmeshwar"

❖ If single quotes are used inside the string , then the string should be enclosed within double quote or
vice versa.
name = "My name is 'Pushpa'"
name = "Hello! My name is "Pushpa", what's your name?"

NOTE: single or double quotes within a string can be escaped using backslash character.

name = "Hello! My name is \"Pushpa\", what\'s your name?"

Multiline string
name = '''My name is Pushpa....
String is enclosed within triple - single or double quotes Zukega nahi Sala'''

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 21


Python Programming, January 2024

Accessing individual character from the string

a = "RAjiv ganDhi Institute of tEchnology"


#Indexing & Slicing #String Repetition
print(a[:]) print(a[0] * 2)
print(a[0:])
print(a[1:])
#Python String Concatenate
print(a[0]) x = 'Rajiv '
print(a[-1]) y = ' Gandhi'
z = ' Institute'
print(a[-10:-1]) print(x+y+z, sep=',')
print(a[-10:])
print(a[0:15:2])
print(a.index('A'))

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 22


Python Programming, January 2023
1. capitalize() String Functions
x = 'rajiv ' 1 capitalize()
x = x.capitalize() Capitalizes first letter of string
print(x)
2 casefold()
2. casefold() 3. lower() Converts string into lower case
y = 'PUSHPA' y = 'PUSHPA' 3 center()
y = y.casefold() y = y.lower() centered string
print(y) print(y) 4 count()
the number of times a specified value occurs in a
4. count() string
txt ="Pushpa ... Pushparaj" 5 index()
x = txt.count("Pushpa", 0, 24) Searches the string for a specified value and returns
print(x) the position of where it was found
5. replace() 6 isalnum()
txt = "I like bananas" 7 isalpha()
x = txt.replace("bananas", "apples") 8 isdecimal()
print(x)
9 isdigit()
10 upper(), lower(), replace()

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 23


Python Programming, January 2024

❑ Lists are used to store multiple items in a single variable.

❑ Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are
Tuple, Set, and Dictionary, all with different qualities and usage.

Create a Python List:


list1 = [1, 2, 3, 4, 5]
list2 = ["a", "b", "c", "d"]
list3 = [10, 'Pushpa', 3.14, True]
list4 = [2] * 5
list5 = list((1, 2, 3)) # covert tuple into list
a = "RAJIV"
list7 = list(a) # covert string into list

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 24


Python Programming, January 2024

Characteristics: Lists are:


• Ordered - They maintain the order of elements.
• Mutable - Items can be changed after creation.
• Allow duplicates - They can contain duplicate values.

list = [1,2,3,4,5] list = [1,2,3]


list.append(6) list.append(3)
list.append(7) list.append(3)
print(list) print(list)

[1, 2, 3, 4, 5, 6, 7] [1, 2, 3, 3, 3]

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 25


Python Programming, January 2024

Characteristics:
Method Description
append() Adds an item to the end of the list
extend() Adds items of lists and other iterables to the end of the list
insert() Inserts an item at the specified index
remove() Removes the specified value from the list
pop() Returns and removes item present at the given index
clear() Removes all items from the list
index() Returns the index of the first matched item
count() Returns the count of the specified item in the list
sort() Sorts the list in ascending/descending order
reverse() Reverses the item of the list
Copy() Returns the shallow copy of the list

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 26


Python Programming, January 2024

Characteristics: Tuple are:


• Ordered - They maintain the order of elements.
• Immutable - Items can not be changed after creation.
• Allow duplicates - They can contain duplicate values.

tup = ("apple", "banana", "cherry", "apple", "cherry")


print(tup)
tup = ("apple",)
print(type(tup)) <class 'tuple'>

#NOT a tuple
tup = ("apple") <class 'str'>
print(type(tup))

tup = ()
print(type(tup)) <class 'tuple'>
Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 27
Python Programming, January 2024

❑ Elements of tuple can only be accessed and can not be changed


tup = (1,2,3,4,5) list =[1,2,3,4,5]
print(list)
print(tup[3])
tup = tuple(list)
print(tup[0:2])
print(type(tup))

tup[0] = 6
tup = (1,2,3,4,5,2,2)
print(tup)
print(tup.count(2))
tup = (1)
print(type(tup))
tup = ( 1, 3, 4, 2, 5, 6 )
tup1 = (1,) res = max(tup)
print(type(tup1)) res1 = min(tup)
print('Maximum of Tuple is', res)
tup = (1,2,3,4,5) print('Minimum of Tuple is', res1)
print(tup.index(2)) print(len(tup))

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 28


Python Programming, January 2024

❑ WAP to ask the user to enter names of their favorite movies and store them in a list.

❑ WAP to check if a list contains a palindrome of elements.

❑ WAP to count the number of students with the “A” grade in the following tuple.
(“C” , “D” , “A” , “A” , “B” , “B” , “A”)

❑ WAP to add items in following tuple:


tup = ("apple", "banana", "cherry")

❑ WAP to find the maximum and minimum value in a tuple.

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 29


Python Programming, January 2024

❑ Its used to store data values in key:value pairs.


❑ They are unordered, mutable, don’t allow duplicate keys
null_dict = {}

dict = {'name':'Pushpa', 'age': 30 , 4 : 'partnership percentage',


'family1' :('Shirvalli', 'aai') , 'B_partners' : ['Jali Reddy', 'Jakka Reddy', 'VP Reddy']
}
print(dict)

❑ Accessing Dictionary:
print(dict['name'])

dict['age'] = '32'

dict['surname'] = 'Mulleti'

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 30


Python Programming, January 2024

❑ Nested Dictionary:
student = {'Name':'Mulleti Pushparaj','subjects':{'Phy':67,'Chem':55,'Math':52 }}

print(student['subjects'])

print(student['subjects']['Phy'])

❑ Dictionary Methods:

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 31


Python Programming, January 2024

❑ Set may contain: integer, Boolean, float, tuple, string

❑ Create a Set: set = {"apple", "banana", "cherry", "apple"}


print(set)

NOTE: 1. Sets are unordered, so you cannot be sure in which order the items will appear.
2. Set do not allow duplicate items
3. Once a set is created, you cannot change its items, but you can remove items and add new items.

❑ Create a empty Set: set1 = set()


print(type(set1))

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 32


Python Programming, January 2024

❑ Set Methods:

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 33


Python Programming, January 2024

❑ if statement: a = 33
b = 200
if b > a:
print("b is greater than a")

NOTE: 1. like curly braces in C programming, Python relies on


indentation to define scope in the code.

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 34


Python Programming, January 2024

❑ elif statement: The elif keyword is Python's way of saying "if the previous conditions were not
true, then try this condition".
Example:
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 35


Python Programming, January 2024

❑ else statement: The else keyword catches anything which isn't caught by the preceding conditions.

Example:
a = 200
b = 200
if b > a:
print("b is greater than a")
elif a>b:
print("a is greater than b")
else:
print("a & b are equal")

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 36


Python Programming, January 2024

❑ Nested-if-else statement:

Example 1:
# Using if-else for Authentication

username = input("Enter your username: ")


password = input("Enter your password: ")

if username == "admin":
if password == "password123":
print("Login successful.")
else:
print("Invalid password.")
else:
print("Invalid username.")

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 37


Python Programming, January 2024

❑ Nested-if-else statement:
Example 2: # Password and Username Checking
username = input("Enter your username: ")
password = input("Enter your password: ")

if username == "admin":
if password == "password":
print("Login successful! Welcome, admin.")
elif password == "12345":
print("Weak password. Please reset your password.")
else:
print("Incorrect password. Please try again.")
else:
if username == "guest":
if password == "guest":
print("Login successful! Welcome, guest.")
else:
print("Incorrect password. Please try again.")
else:
print("Unknown user. Please try again.")
Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 38
Python Programming, January 2024

❑ Nested-if-else statement:
Example 2: WAP to check to check given no. is prime numbers using nested if else
num=int(input("enter a number"))
if num>1:
if num==2:
print("prime no.)")
for i in range(2,num):
if(num%i)==0:
print(num,"is not a prime number")
j=num/i
print(num,"devide by",i,"=",j)
break
else:
print(num,"is prime number")
else:
print(num,"is not a prime number")

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 39


Python Programming, January 2024

❑ WAP to check number entered by the user is odd or even.

❑ WAP to find the greatest of 3 numbers entered by user.

❑ WAP to check if a number is a multiple of 7 or not.

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 40


Python Programming, January 2024

Loops and Loop control statements


Python programming language provides following types of loops to handle looping requirements.
➢ while loop
➢ for loop
➢ Nested loop

❑ while loop:
• Repeats the piece of code until the condition becomes False

i = 1 1
while i < 6: 2
print(i) 3
i += 1 4
5

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 41


Python Programming, January 2024

Loops and Loop control statements

❑ find sum of all numbers till given no.

num = int(input("Enter a number: "))


sum=0
while(num > 0):
sum = sum+num
num = num-1
print("The sum is",sum)

Output: Enter a number: 10


The sum is 55

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 42


Python Programming, January 2024

Loops and Loop control statements


❑ break statement: With the break statement we can stop the loop even if the while
condition is true:
i = 1
while i < 6: 1
print(i) 2
if i == 3: 3
break
i += 1

❑ continue statement: With the continue statement we can stop the current iteration, and
continue with the next:
i = 0
while i < 6: 1
i += 1 2
if i == 3: 4
continue 5
print(i) 6

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 43


Python Programming, January 2024

Loops and Loop control statements


❑ for loop: With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.
for letter in 'Python': # First Example
print('Current Letter :', letter)

Output: Current Letter : P


Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n

numbers=[6,5,3,8,4,2,5,4]
sum=0
for val in numbers:
sum=sum+val
print("The sum is", sum)

Output: The sum is 37


Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 44
Python Programming, January 2024

Example 3: WAP to check to check given no. is prime numbers using nested if else

num=int(input("enter a number"))
if num>1:
if num==2:
print("prime no.)")
for i in range(2,num):
if(num%i)==0:
print(num,"is not a prime number")
j=num/i
print(num,"devide by",i,"=",j)
break
else:
print(num,"is prime number")
else:
print(num,"is not a prime number")

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 45


Python Programming, January 2024

Loops and Loop control statements


❑ Range function:
The range() function returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and stops before a specified number.

Syntax: range(start, stop, step)


x = range(6) x = range(3, 6) x = range(3, 20, 2)
for n in x: for n in x: for n in x:
print(n) print(n) print(n)
3
5
0 3 7
1 4 9
2 5 11
3 13
4 15
5 17
19
Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 46
Python Programming, January 2024

Function
• A function is a block of code which only runs when it is called.

• Functions are used to perform certain actions, and they are important for reusing code:
Define the code once, and use it many times.

Create a Function: def func_name(par1, par2...): #Function Definition


# some work
return val

func_name(arg1, arg2...) # Function Call

Example: def sum(a, b): #Function Definition def sum(a, b): #Function Definition
s = a +b s = a +b
print(s) return s

sum(2, 5) # Function Call print(sum(2, 5)) # Function Call

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 47


Python Programming, January 2024

Arguments/Parameters in function

1. Built-in function

2. User-defined function

3. Lambda functions

4. Recursive functions

Concept of global variable and local variable

a = 10 #Global variable a = 10 #Global variable


def f1(): def f1():
a= 20 #Local variable global a
print(a) a= 20 #Local variable
def f2(): print(a)
print(a) def f2():
f1() print(a)
f2() f1()
f2()
Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 48
Python Programming, January 2024

Types of functions in Python:

1. Default Arguments

2. Keyword Arguments

3. Positional Arguments

4. Arbitrary positional arguments

5. Arbitrary keyword arguments

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 49


Python Programming, January 2024

Types of functions in Python:

1. Default Arguments
• During function call, default arguments becomes optional

def add(a, b = 5, c = 6):


return(a+b+c)
print(add(3)) #only mandatory arguments
print(add(2,6)) #only one optional argument
print(add(2,6,6)) #giving all arguments

Output: 14
14
14

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 50


Python Programming, January 2024

Types of functions in Python:

2. Keyword Arguments
• Arguments that identifies the parameters by their names

def add(a, b = 5, c = 6): def grocery(item, price):


return(a + b * c) print('item = %s' %item, end=' ')
print(add(3)) #only mandatory arguments print('price = %.2f' %price)
print(add(2,c=6)) grocery(item = 'sugar',price=50)
print(add(2,7, c=9)) grocery(price = 40,item='oil')
print(add(c=6, b=4, a=2))
Output: item = sugar price = 50.00
Output: 33 item = oil price = 40.00
32
65
26

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 51


Python Programming, January 2024

Types of functions in Python:

3. Positional Arguments
• Maintain positions(orders) of arguments

def power(a,b):
print(a**b)
power(5,2)
power(2,5)

Output:
Output: 25
32

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 52


Python Programming, January 2024

Types of functions in Python:

3. Variable Length Arguments/Arbitrary Arguments


• If we don’t know the number of arguments needed for the function in advance
def sum(*num):
#avg of first test and best of following tests
sum = 0
def avg(first, *rest):
for i in num:
second=max(rest)
sum = sum + i
return (first+second)/2
print(sum)
sum(10,20)
result=avg(40,30,50,25)
sum(10,20,30)
print (result)
sum(10, 20, 30, 40)
Output: 45.0

Output: 30
60
100
Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 53
Python Programming, January 2024

Passing Arguments to Functions


In programming, there are two ways in which arguments can be passed to function:-
Pass by Value:
• Function creates a copy of the variable (Object in Python) passed to it as an argument.
• The actual object is not affected.
• Object is of immutable type, because immutable objects cannot be modified.

Immutable objects:
int, float, complex, string, tuple, frozen set [note: immutable version of set], bytes.

Pass by Reference:
• The actual object is passed to the called function.
• All the changes made to the object inside the function affect its original value.
• Object is mutable type, as mutable objects can be changed, the passed objects are updated.

Mutable objects:
list, dict, set, byte array

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 54


Python Programming, January 2024

Passing Arguments to Functions


Pass by Value:

Pass by Reference:

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 55


Python Programming, January 2024

Call by Value:

def change (a):


a = a + 10
print("inside func a =", a)
Output:
x = 10
print("x before calling:", x) x before calling: 10
change(x)
inside func a = 20
print("x after calling:", x)
x after calling: 10

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 56


Python Programming, January 2024

Call by Value:

def change (a):


print("This is original a", id(a))
a = a + 10
x before calling: 10
print("This is original a", id(a))
print("inside func a =", a) This is original a 134289387546920

a = 10 This is original a 134289387546920


print("x before calling:", a)
This is original a 134289387547240
print("This is original a", id(a))
change(a) inside func a = 20

print("x after calling:", a) x after calling: 10

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 57


Python Programming, January 2024

Call by Reference:

def change (list1):

list1[0] = list1[0] + 10

print("inside func a =", list1)

list1 = [10]

print("x before calling:", list1) x before calling: [10]

change(list1) inside func a = [20]

print("x after calling:", list1) x after calling: [20]

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 58


Python Programming, January 2024

Call by Reference:

def change (list1):


print("This is original list1", id(list1))
list1[0] = list1[0] + 10
x before calling: [10]
print("This is original list1", id(list1))
print("inside func a =", list1) This is original list1 2060301066368

list1 = [10] This is original list1 2060301066368


print("x before calling:", list1)
This is original list1 2060301066368
print("This is original list1", id(list1))
change(list1) inside func a = [20]

print("x after calling:", list1) x after calling: [20]


print("This is original list1", id(list1))
This is original list1 2060301066368

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 59


Python Programming, January 2024

Call by value & Call by Reference:


def inc(tup, lst, dct): inc(tup, lst, dct)
tup = tup + (99,) print("***after inc executed***")
lst.append(999) print(tup)
dct['val9999']=9999 print(lst)
print("***inside function***") print(dct)
print(tup)
print(lst) Output:
print(dct)
#immutable call by value (copy) ***Before***
# mutable call by reference (exact) (1, 2, 3)
[11, 22, 33]
tup = (1,2,3) {'val1': 111, 'val2': 222, 'val3': 333}
lst = [11,22,33] ***inside function***
dct = {"val1":111, "val2":222, "val3": 333} (1, 2, 3, 99)
[11, 22, 33, 999]
print("***Before***") {'val1': 111, 'val2': 222, 'val3': 333, 'val9999': 9999}
print(tup) ***after inc executed***
print(lst) (1, 2, 3)
print(dct) [11, 22, 33, 999]
{'val1': 111, 'val2': 222, 'val3': 333, 'val9999': 9999}
Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 60
Python Programming, January 2024

WAP to check number entered by the user is prime number or not using function.
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num/2) + 1):
if num % i == 0:
return False
return True
number = int(input("Enter a number: "))
if is_prime(number):
print(number," is a prime number.") Output:
else: Enter a number: 17
print(number,"is not a prime number.") 17 is a prime number.

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 61


Python Programming, January 2024

WAP for simple calculator using function.


# Take input from the user
# Python program for simple calculator select = int(input("Select operations form 1,
# Function to add two numbers 2, 3, 4 :"))
def add(num1, num2): number_1 = int(input("Enter first number: "))
return num1 + num2 number_2 = int(input("Enter second number: "))
# Function to subtract two numbers if select == 1:
print(number_1, "+", number_2, "=",
def subtract(num1, num2): add(number_1, number_2))
return num1 - num2
elif select == 2:
# Function to multiply two numbers print(number_1, "-", number_2, "=",
def multiply(num1, num2): subtract(number_1,
number_2))
return num1 * num2
elif select == 3:
# Function to divide two numbers print(number_1, "*", number_2, "=",
def divide(num1, num2): multiply(number_1,
number_2))
return num1 / num2
elif select == 4:
print("Please select operation -\n" \ print(number_1, "/", number_2, "=",
"1. Add\n" \ divide(number_1, number_2))
else:
"2. Subtract\n" \
print("Invalid input")
"3. Multiply\n" \
"4. Divide\n")

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 62


Python Programming, January 2024

Function
In python, a file operation take place in following order

• Open
• Read/Write (perform operation)
• Close file

Open File:
We have to open a file using built-in function open()

open() function, requires file path and mode as arguments:

file = open("TT.txt", "r") #Open file in current directory


file1 = open("H:\paul\File.txt","r") #Specifying full path
print(file1.read())

print(file1.read(3)) # specify how many characters you want to return

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 63


Python Programming, January 2024

readline() method:
• You can return one line by using the readline() method:
• By calling readline() two times, you can read the two first lines:
• By looping through the lines of the file, you can read the whole file, line by line:

file1 = open("H:\paul\File.txt","r")
print(file1.readline())
print(file1.readline())
# for x in file1:
# print(x)

Close Files: It is a good practice to always close the file when you are done with it.
file1 = open("H:\paul\File.txt","r")
print(file1.readline())
file1.close()

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 64


Python Programming, January 2024

Write to an Existing File


To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content

file1 = open("H:\paul\File.txt","a") file1 = open("H:\paul\File.txt","w")


#Specifying full path #Specifying full path
file1.write("Will ROHIT HIT CENTURY TODAY?") file1.write("Will ROHIT HIT CENTURY TODAY?")
file1.close() file1.close()
file1 = open("H:\paul\File.txt","r") file1 = open("H:\paul\File.txt","r")
print(file1.read()) print(file1.read())

Note: the "w" method will overwrite the entire file.

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 65


Python Programming, January 2024

Create a New File:


To create a new file in Python, use the open() method, with one of the following parameters:
"x" - Create - will create a file, returns an error if the file exists
"a" - Append - will create a file if the specified file does not exists
"w" - Write - will create a file if the specified file does not exists

f = open("myfile.txt", "x")

Delete a File:
To delete a file, you must import the OS module, and run its os.remove() function:

Prof. P. R. Paul (Asst. Professor, RGIT, Mumbai) 66

You might also like